instruction
stringlengths
21
27.8k
chosen
stringlengths
18
28.2k
rejected
stringlengths
18
33.6k
__index_level_0__
int64
0
50k
<p>I am very interested in streaming data for web-applications. I have tried out some javascript libraries, but the hacks and browser-incompatibilities drive me crazy ! HTML5 will hopefully standardize streaming data, but until then, hopefully I can resort to Flash to make this work in all browsers. Unfortunately, I'm not very familiar with all the functionality that Flash offers.</p> <p>I have tried loadVariables.onData in Flash 8, but it doesn't support streaming data. The data is only available after the request has been finished. Is there any way to call a function every time new data is returned ?</p>
<p>Though I'm not familiar with what you're doing, it sounds like you should be looking at <a href="http://help.adobe.com/en_US/AS3LCR/Flash_10.0/index.html" rel="nofollow noreferrer">URLStream</a>. When you're loading things that Flash intuitively understands (MP3s, JPGs, SWFs and so on) then you would normally use a <a href="http://help.adobe.com/en_US/AS3LCR/Flash_10.0/flash/display/Loader.html" rel="nofollow noreferrer">Loader</a>, and then too you can get <a href="http://help.adobe.com/en_US/AS3LCR/Flash_10.0/flash/display/LoaderInfo.html#event:progress" rel="nofollow noreferrer">progress events</a>, but I'm guessing you're talking about loading arbitrary data into a ByteArray, and URLStream should give you all the low-level access you need.</p> <p>That's assuming you're using AS3, and Flash Player 9+. I wouldn't swear to it, but I'm pretty sure what you're looking for is not possible under AS2. </p>
<p>As Moss Collum and fenomas have suggested, there's <code>URLStream</code> and <code>XMLSocket</code>. But if you want to interact with a server on a binary level, you can read and write bytes with a <code>Socket</code> object.</p> <p>Bear in mind that any network communication is subject to Flash Player's very rigid Security Model. You may find that learning about this will be time very well spent.</p>
47,834
<p>I'm using .NET 3.5, trying to recursively delete a directory using:</p> <pre><code>Directory.Delete(myPath, true); </code></pre> <p>My understanding is that this should throw if files are in use or there is a permissions problem, but otherwise it should delete the directory and all of its contents.</p> <p>However, I occasionally get this:</p> <pre><code>System.IO.IOException: The directory is not empty. at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath) at System.IO.Directory.DeleteHelper(String fullPath, String userPath, Boolean recursive) at System.IO.Directory.Delete(String fullPath, String userPath, Boolean recursive) ... </code></pre> <p>I'm not surprised that the method sometimes throws, but I'm surprised to get this particular message when recursive is true. (I <em>know</em> the directory is not empty.)</p> <p>Is there a reason I'd see this instead of AccessViolationException?</p>
<p><strong>Editor's note:</strong> Although this answer contains some useful information, it is factually incorrect about the workings of <code>Directory.Delete</code>. Please read the comments for this answer, and other answers to this question.</p> <hr> <p>I ran into this problem before.</p> <p>The root of the problem is that this function does not delete files that are within the directory structure. So what you'll need to do is create a function that deletes all the files within the directory structure then all the directories before removing the directory itself. I know this goes against the second parameter but it's a much safer approach. In addition, you will probably want to remove READ-ONLY access attributes from the files right before you delete them. Otherwise that will raise an exception.</p> <p>Just slap this code into your project.</p> <pre><code>public static void DeleteDirectory(string target_dir) { string[] files = Directory.GetFiles(target_dir); string[] dirs = Directory.GetDirectories(target_dir); foreach (string file in files) { File.SetAttributes(file, FileAttributes.Normal); File.Delete(file); } foreach (string dir in dirs) { DeleteDirectory(dir); } Directory.Delete(target_dir, false); } </code></pre> <p>Also, for me I personally add a restriction on areas of the machine that are allowed to be deleted because do you want someone to call this function on <code>C:\WINDOWS (%WinDir%)</code> or <code>C:\</code>.</p>
<p>None of the above answers worked for me. It appears that my own app's usage of <code>DirectoryInfo</code> on the target directory was causing it to remain locked.</p> <p>Forcing garbage collection appeared to resolve the issue, but not right away. A few attempts to delete where required.</p> <p>Note the <code>Directory.Exists</code> as it can disappear after an exception. I don't know why the delete for me was delayed (Windows 7 SP1)</p> <pre><code> for (int attempts = 0; attempts &lt; 10; attempts++) { try { if (Directory.Exists(folder)) { Directory.Delete(folder, true); } return; } catch (IOException e) { GC.Collect(); Thread.Sleep(1000); } } throw new Exception("Failed to remove folder."); </code></pre>
42,675
<p>I am using a GDI+ Graphic to draw a 4000*3000 image to screen, but it is really slow. It takes about 300ms. I wish it just occupy less than 10ms.</p> <pre><code>Bitmap *bitmap = Bitmap::FromFile("XXXX",...); </code></pre> <p>//-------------------------------------------- // this part takes about 300ms, terrible!</p> <pre><code>int width = bitmap-&gt;GetWidth(); int height = bitmap-&gt;GetHeight(); DrawImage(bitmap,0,0,width,height); </code></pre> <p>//------------------------------------------</p> <p>I cannot use CachedBitmap, because I want to edit the bitmap later.</p> <p>How can I improve it? Or is any thing wrong? </p> <p>This native GDI function also draws the image into the screen, and it just take 1 ms:</p> <pre><code>SetStretchBltMode(hDC, COLORONCOLOR); StretchDIBits(hDC, rcDest.left, rcDest.top, rcDest.right-rcDest.left, rcDest.bottom-rcDest.top, 0, 0, width, height, BYTE* dib, dibinfo, DIB_RGB_COLORS, SRCCOPY); </code></pre> <p>//--------------------------------------------------------------</p> <p>If I want to use StretchDIBits, I need to pass BITMAPINFO, But how can I get BITMAPINFO from a Gdi+ Bitmap Object? I did the experiment by FreeImage lib, I call StretchDIBits using FreeImageplus object, it draw really fast. But now I need to draw Bitmap, and write some algorithm on Bitmap's bits array, how can I get BITMAPINFO if I have an Bitmap object? It's really annoying -___________-|</p>
<p>If you're using GDI+, the TextureBrush class is what you need for rendering images fast. I've written a couple of 2d games with it, getting around 30 FPS or so.</p> <p>I've never written .NET code in C++, so here's a C#-ish example:</p> <pre><code>Bitmap bmp = new Bitmap(...) TextureBrush myBrush = new TextureBrush(bmp) private void Paint(object sender, PaintEventArgs e): { //Don't draw the bitmap directly. //Only draw TextureBrush inside the Paint event. e.Graphics.FillRectangle(myBrush, ...) } </code></pre>
<p>I have made some researching and wasn't able to find a way to render images with GDI/GDI+ more faster than</p> <pre><code>Graphics.DrawImage/DrawImageUnscaled </code></pre> <p>and at the same time simple like it.</p> <p>Till I discovered</p> <pre><code>ImageList.Draw(GFX,Point,Index) </code></pre> <p>and yeah it's really so fast and simple.</p>
33,167
<p>I am serializing a <code>JPEG</code> Image in <code>c#.net</code>. I am simply converting it into a byte steam and sending it through web service. </p> <p>I observed that serialized byte stream is 30 times more than that of the size of actual image. Can any one <strong>suggest me a better approach</strong> to serialize and stay relative to the size of the actual image? </p>
<p>JPEG is a compression technology, and it is expected that it will expand greatly once you read it in. This is the nature of the file format. Try to find a way to send the original JPEG file without reading it as an image first.</p>
<p>Why not convert it to a Base64String?</p> <pre><code>byte[] arr = File.ReadAllBytes(filename); string str = Convert.ToBase64String(arr); </code></pre> <p>On the other end you can change it back to a byte[] by going:</p> <pre><code>byte[] arr = Convert.FromBase64String(string); </code></pre>
9,498
<p>I've created a PHP DOM xml piece and saved it to a string like this:</p> <pre><code>&lt;?php // create a new XML document $doc = new DomDocument('1.0'); ... ... ... $xmldata = $doc-&gt;saveXML(); ?&gt; </code></pre> <p>Now I can't use the headers to send a file download prompt and I can't write the file to the server, or rather I don't want the file laying around on it.</p> <p>Something like a save this file link or a download prompt would be good. How do I do it?</p>
<p>I see from the comments that you're working from within a CMS framework and are unable to stop content from being output prior to where your code will be.</p> <p>If the script in which you're working has already output content (beyond your control), then you can't do what you're trying to achieve in just one script.</p> <p>Your script can either send headers saying "the following content is HTML" then output the HTML or send headers saying "the following content is XML, is an attachment and has a certain filename". You can't do both.</p> <p>You can either output HTML containing a link to a separate script for downloading an XML file or you can issue a file download and output no HTML.</p> <p>Therefore, you'll have to add a download link in the output of the CMS script you're modifying and then handle the download in a separate script.</p> <p>I have made a working example that should help. The example includes a simple HTML document containing a download link, and a PHP script that then handles the download.</p> <p>View the code below or take a look at the <a href="http://webignition.net/examples/xmldownload/" rel="nofollow noreferrer">live example</a>.</p> <p><strong>HTML (extraneous fluff removed, not necessarily valid)</strong></p> <pre><code>&lt;html&gt; &lt;head&gt; &lt;title&gt;XML Download Example&lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;a href="download.php"&gt;Download XML example&lt;/a&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p><strong>PHP</strong></p> <pre><code>&lt;?php // Populate XML document $doc = new DomDocument(); // ... various modifications to the document are made // Output headers header('Content-type: "text/xml"; charset="utf8"'); header('Content-disposition: attachment; filename="example.xml"'); // Output content echo $doc-&gt;saveXML(); ?&gt; </code></pre> <p>If you are fully unable to handle the download via a second script (perhaps you can't get access to the relevant data), you'll have to re-think the problem.</p>
<p>You could enable output_buffering in your php.ini, then you might have some options with sending headers.</p> <p><a href="http://us.php.net/manual/en/function.headers-sent.php" rel="nofollow noreferrer">http://us.php.net/manual/en/function.headers-sent.php</a></p>
24,732
<p>In C++, when is it best to use the stack? When is it best to use the heap?</p>
<p>Use the stack when your variable will not be used after the current function returns. Use the heap when the data in the variable is needed beyond the lifetime of the current function.</p>
<p>The question is ill formed.</p> <p>There are situations where you need the stack, others where you need the heap, others where you need the static storage, others where you need the const memory data, others where you need the free store.</p> <p>The stack is fast, because allocation is just an "increment" over the SP, and all "allocation" is performed at invocation time of the function you are in. Heap (or free store) allocation/deallocation is more time expensive and error prone.</p>
12,751
<p>I am thinking of running this custom targets to find out more about my project build status - jalopy - jdepend - cvs tagdiff report - custom task for NoUnit - generate UML diagram. ESS-Model</p> <p>What are your views?</p>
<p>I think that it's a great idea and use it myself. That way I'll never forget to run it.</p> <p>I also keep the reports for a decent amount of time and eventually create a spreadsheet of "progress".</p> <p>In your main ant task - call another task to do "whatever" </p> <p>and JDepend.xml ...</p> <p> </p> <pre><code>&lt;target name="statsAll"&gt; &lt;!-- master file that describes where everything is --&gt; &lt;property file="./ant/ant-global.properties" prefix="ant-global" /&gt; &lt;tstamp&gt; &lt;format property="gen.time" pattern="yyyyMMdd_hh"/&gt; &lt;/tstamp&gt; &lt;echo message="LOG:./ant/logs/jdepend.${version.FILETAG}.${gen.time}.rpt"/&gt; &lt;!-- generate stats to see if we're improving --&gt; &lt;jdepend outputfile="./ant/logs/jdepend.${version.FILETAG}.${gen.time}.rpt" &gt; &lt;exclude name="java.*"/&gt; &lt;exclude name="javax.*"/&gt; &lt;classespath&gt; &lt;pathelement location="./jar" /&gt; &lt;/classespath&gt; &lt;classpath location="./jar" /&gt; &lt;/jdepend&gt; &lt;/target&gt; &lt;target name="doJDepend" depends="getVersion,statsAll"&gt; &lt;echo message="FTP'ing report"/&gt; &lt;ftp verbose="yes" passive="yes" depends="yes" remotedir="/videojet/metrics" server="xxxxx" userid="xxxx" password="xxxxx" binary="no" systemTypeKey="UNIX"&gt; &lt;fileset dir="./ant/logs/" casesensitive="no"&gt; &lt;include name="**/jdepend.${version.FILETAG}*.rpt"/&gt; &lt;exclude name="**/*.txt"/&gt; &lt;/fileset&gt; &lt;/ftp&gt; &lt;/target&gt; </code></pre> <p></p> <p><a href="http://www.codinghorror.com/blog/archives/000149.html" rel="nofollow noreferrer">Magic build machine</a></p>
<p>I second the 'good idea' part, although for a project of reasonable size you might want to make it part of an automated build, like one of the CI Servers (Bamboo, Contiuum).</p> <p>You might also consider a code coverage tool to see how your test coverage is going. </p> <p>This will ensure the reports get run on a regular basis, could give you somewhere to publish them and won't slow down the developer's quick turnaround development cycle.</p>
29,363
<p>I have a python script that is a http-server: <a href="http://paste2.org/p/89701" rel="nofollow noreferrer">http://paste2.org/p/89701</a>, when benchmarking it against ApacheBench (ab) with a concurrency level (-c switch) that is lower then or equal to the value i specified in the socket.listen()-call in the sourcecode everything works fine, but as soon as put the concurrency level in apache bench above the value in the socket.listen()-call performance drops through the floor, some example:</p> <ul> <li>socket.listen(<strong>10</strong>) and ab -n 50 -c <strong>10</strong> <a href="http://localhost/" rel="nofollow noreferrer">http://localhost/</a> = <strong>1200req/s</strong></li> <li>socket.listen(<strong>10</strong>) and ab -n 50 -c <strong>11</strong> <a href="http://localhost/" rel="nofollow noreferrer">http://localhost/</a> = <strong>40req/s</strong></li> <li>socket.listen(<strong>100</strong>) and ab -n 5000 -c <strong>100</strong> <a href="http://localhost/" rel="nofollow noreferrer">http://localhost/</a> = <strong>1000req/s</strong></li> <li>socket.listen(<strong>100</strong>) and ab -n 5000 -c <strong>101</strong> <a href="http://localhost/" rel="nofollow noreferrer">http://localhost/</a> = <strong>32req/s</strong></li> </ul> <p>Nothing changes in the code between the two calls, I can’t figure out what is wrong - been at this problem for one day now. Also note that: The multiplexing version of the same code (I wrote to compare to the threaded version) works FINE no matter what socket.listen() is set to or what the concurrency (-c switch) in apache is set to.</p> <p><em>I've spent a day on IRC/python docs, posted on comp.lang.python and on my blog - I can't find ANYONE that even has an idea what could be wrong. Help me!</em></p>
<p>I cannot confirm your results, and your server is coded fishy. I whipped up my own server and do not have this problem either. Let's move the discussion to a simpler level:</p> <pre><code>import thread, socket, Queue connections = Queue.Queue() num_threads = 10 backlog = 10 def request(): while 1: conn = connections.get() data = '' while '\r\n\r\n' not in data: data += conn.recv(4048) conn.sendall('HTTP/1.1 200 OK\r\n\r\nHello World') conn.close() if __name__ == '__main__': for _ in range(num_threads): thread.start_new_thread(request, ()) acceptor = socket.socket(socket.AF_INET, socket.SOCK_STREAM) acceptor.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) acceptor.bind(('', 1234)) acceptor.listen(backlog) while 1: conn, addr = acceptor.accept() connections.put(conn) </code></pre> <p>which on my machine does:</p> <pre><code>ab -n 10000 -c 10 http://127.0.0.1:1234/ --&gt; 8695.03 [#/sec] ab -n 10000 -c 11 http://127.0.0.1:1234/ --&gt; 8529.41 [#/sec] </code></pre>
<p>I found <a href="http://www.mail-archive.com/dev@tomcat.apache.org/msg22589.html" rel="nofollow noreferrer">this article</a> on backlog on tomcat / java which gives an interesting insight in the backlog:</p> <blockquote> <p>for example, if all threads are busy in java handling requests, the kernel will handle SYN and TCP handshakes until its backlog is full. when the backlog is full, it will simply drop future SYN requests. it will not send a RST, ie causing "Connection refused" on the client, instead the client will assume the package was lost and retransmit the SYN. hopefully, the backlog queue will have cleared up by then.</p> </blockquote> <p>As I interpret it, by asking ab to create more simultaneous connection than your socket is configured to handle packets get dropped, not refused, and I do not know how ab handles that. It may be that it retransmits the SYN, but possibly after waiting a while. This may even be specced somewhere (TCP protocol?).</p> <p>As said, I do not know but I hope this hints at the cause. </p> <p>Good luck!</p>
27,024
<p>I have a J2EE-based system which is running currently on Apache Tomcat. We are in discussions to move our production servers to the Glassfish server.</p> <p>Can someone share their experiences with either of them?</p>
<p>Here's <a href="https://rogerkeays.com/blog/glassfish-vs-tomcat" rel="nofollow noreferrer">quite an old comparison</a>. As such, the capabilities of each server have doubtless improved.</p> <p>Edit: Here is <a href="http://wiki.glassfish.java.net/Wiki.jsp?page=GlassFishVsTomcat" rel="nofollow noreferrer">a current comparison.</a></p> <p>Both are more than stable enough for production use though. It's really going to come down to features.</p>
<p>This may be a little dated and maybe even a little biased, but it's from Oracle. You can skip down to the section for comparing Glass Fish to Tom Cat</p> <p><a href="http://java.sun.com/developer/technicalArticles/glassfish/GFandMySQL_Part1.html" rel="nofollow">http://java.sun.com/developer/technicalArticles/glassfish/GFandMySQL_Part1.html</a></p>
42,488
<p>I am performing a lot of JavaScript work in the browser and would like to have some of that backend functionality in the front-end. Specifically, it would be nice to have the functions <code>get()</code>, <code>save()</code>, <code>all()</code> and <code>count()</code> available to the client. Additionally, it would be great to have the field list of the model already available in the generated JavaScript object.</p> <p>Whether the current user can read or write the records is a separate issue I will deal with using Django's authentication. For the time being, retrieval would be a start.</p> <p>In short, is there code that would generate a JavaScript model from a Django model?</p> <p>Thanks.</p>
<p>It sounds like you're looking for a complete JavaScript interface to the model and queryset APIs. I can't imagine that this would have ever been done or even be a simple task. Not only would you need to somehow generate JavaScript instances of models (much more than JSON serialisation provides, since you also want the methods) but you'd need to expose a web service that can handle every kind of DB-API call. I can't even begin to imagine where to start and the security issues may be too numerous to easily overcome.</p> <p>The alternative (and much simpler) approach would be to use one of the various Django REST modules and JSON serialization. You could perform an AJAX GET request on a resource, which can be identified by a series of query parameters that would be equivalent to chained queryset filters. This would return the JSON representation of the model's values. You can then modify the JavaScript object and use an overloaded AJAX POST request to persist the changes back to the server. You wouldn't have access to the model's methods, so that functionality would have to be reimplemented but making any changes to a model should be straightforward enough - This is basically the JavaScript equivalent of using an HTML form to modify data.</p>
<p>It sounds like you want to <a href="http://docs.djangoproject.com/en/dev/topics/serialization/?from=olddocs" rel="nofollow noreferrer">JSON encode</a> your object data. See <a href="http://www.json.org" rel="nofollow noreferrer">JSON.org</a> for more on the data format.</p>
24,702
<p>I'm new to ASP.NET MVC and I'm trying to get the full url to a action when working in a view. I need this to submit to a third party API as a callback. For example what I need is</p> <blockquote> <p><a href="http://myserver.com/controller/action" rel="noreferrer">http://myserver.com/controller/action</a></p> </blockquote> <p>When I use </p> <pre><code>&lt;%= Url.Action("action", "controller") %&gt; </code></pre> <p>I get </p> <blockquote> <p>/controller/action</p> </blockquote> <p>I know several ways to add the server base-path to this but I'm wondering what is the preferred way to do this in the ASP.NET MVC view?</p> <p>EDIT: Just to clarify, it's not the URL for the current view/action it's for another action in the same controller.</p>
<p>In order to catch variations in the protocol (http / https), diffrent ports and virtual paths (can't always assume we will be in server root) I ended up with the following solution:</p> <pre><code>&lt;%= Request.Url.GetLeftPart(System.UriPartial.Authority) + Url.Action("action", "controller")%&gt; </code></pre> <p>I'm working on moving this to a extension method to make it prettier.</p>
<p>Request.Url returns the full URL including the protocol (http://), the url (www.mydomain.com/mypath), and the querystring (?id=5).</p> <pre><code>@Request.Url @*Razor tags*@ </code></pre> <p>For classic ASP.NET MVC tags it would be</p> <pre><code>&lt;%=Request.Url%&gt; &lt;%'Classic tags%&gt; </code></pre>
45,138
<p>Did you ever had a bug in your code, you could not resolve? I hope I'm not the only one out there, who made this experience ...</p> <p>There exist some classes of bugs, that are very hard to track down:</p> <ul> <li><strong>timing-related bugs</strong> (that occur during inter-process-communication for example)</li> <li><strong>memory-related bugs</strong> (most of you know appropriate examples, I guess !!!)</li> <li><strong>event-related bugs</strong> (hard to debug, because every break point you run into makes your IDE the target for mouse release/focus events ...)</li> <li><strong>OS-dependent bugs</strong></li> <li><strong>hardware dependent bugs</strong> (occurs on release machine, but not on developer machine)</li> <li>...</li> </ul> <p>To be honest, from time to time I fail to fix such a bug on my own ... After debugging for hours (or sometimes even days) I feel very demoralized.</p> <p>What do you do in this situation (apart from asking others for help which is not always possible)?</p> <p>Do you</p> <ul> <li>use pencil and paper instead of a debugger</li> <li>face for another thing and return to this bug later</li> <li>...</li> </ul> <p>Please let me know!</p>
<p>Some things that help: </p> <p>1) Take a break, approach the bug from a different angle. </p> <p>2) Get more aggressive with tracing and logging. </p> <p>3) Have another pair of eyes look at it.</p> <p>4) A usual last resort is to figure out a way to make the bug irrelevant by changing the fundamental conditions in which it occurs</p> <p>5) Smash and break things. (Stress relief only!)</p>
<p>For memory related bugs i have found that the Memory Profiling options of Ants Profiler have helped me quite a bit on finding bugs.</p>
18,735
<p>Amazon announced cloud hosting for Windows goes public beta today. </p> <p><a href="http://aws.amazon.com/windows/" rel="nofollow noreferrer">EC2 Windows Pricing</a></p> <p>The pricing doesn't seem that cheap over colocation of your own server. Is this a revolutionary step towards the obvious future of hosting? </p> <p>Does anyone have any first hand experience using .net on an amazon virtual box?</p> <p>Cheapest pricing btw is 12.5 cents per hour.</p>
<p>This seems very expensive. To be honest I am quite disappointed for several reasons. Firstly they only support Windows 2003 Server. Windows 2008 has been out for long enough that surely they could support that by now. Secondly, they don't mention what version of SQL Server they are supporting but I am guessing it is 2005 as well. </p> <p>For a Windows 2003 box with SQL Server Standard installed it will cost $1.10 an hour or about $750 month!!</p> <p>I wonder if it is possible to install your own version of SQL 2008.</p>
<p>Seems expensive at $180 per full month for just a small SQL Express + IIS box + Authentication. I think the issue is you get billed full rate on partial hours. If they did away with that and let you be billed on per cpu hour consumed or similar then it might be better.</p> <p>There are cheaper solutions out there such as Mosso or GoGrid which are cheaper and offer similar products. </p> <p>However possibly if you already have tight integration with AWS then it would be a goer.</p>
28,737
<h2>Problem</h2> <p>Our web host provider is changing the IP address of one of the servers we are on. We have been given a time frame for when the switch will take place, but no exact details. Therefore, our current <em>poor man's</em> check requires a periodic page refresh on a browser to see if our website is still there.</p> <h2>Question</h2> <p>We are all programmers here and this is killing me that any manual checking is required. I would know how to do this in other languages, but want to know if there is a way to write a script in <strong>PowerShell</strong> to tackle this problem. Does anyone know how I might going about this?</p>
<p>If you can alert if the page is gone or does not have an expected value, you could use a script like</p> <pre><code>$ip = 192.168.1.1 $webclient = new-object System.Net.WebClient $regex = 'regular expression to match something on your page' $ping = new-object System.Net.NetworkInformation.Ping do { $result = $ping.Send($ip) if ($result.status -ne 'TimedOut' ) { $page = $webclient.downloadstring("http://$ip") if (($page -notmatch $regex) -or ($page -match '404') -or ($page -eq $null)) { break} } } while ($true) write-host "The website has moved" </code></pre>
<p>This will list the IP Address for each network adapter in your system.</p> <pre><code>Get-WmiObject -Class Win32_NetworkAdapterConfiguration -Filter IPEnabled=TRUE -ComputerName . | Select-Object -Property IPAddress </code></pre>
22,957
<p>I seem to be in a never ending tail spin of Linux, or not, Windows or not. Web programming or system programming. Python or PHP.</p> <p>I'am self teaching myself programming. But it seems I keep being torn about which way to go. Unfortunately it is always seemingly good reasons to get side tracked. You know the whole open source or proprietary thing. Lately I have decided after a year that Linux just doesn't cut it for me and it mostly stems from me wanting to watch videos on Channel 9 etc, and the clunkiness that is Linux. So that lead me to, "Should I learn ASP.NET, since I am more so deciding Windows IS a "necessary" evil.</p> <p>I hope this made sense. The reason I settled in on Web Development as my course to learning programming is because I actually have a task to implement rather then aimlessly reading reference books etc.</p> <p>Does anyone have any advice at what they may have done to stay focused and not get lead down every tangent or idea.</p>
<p>You will only have a first language for a little while. Pick any direction that interests you, and follow it. There is no way around the introduction "Drink from the Firehose" experience.</p> <p>Keep early project simple, and tangible. Build useful things and the motivation will be there.</p> <p>Web / desktop / mobile / etc, its all good. Find the one that gets you thinking about code when your not coding, and you'll know your going in the right direction.</p>
<p>Don't worry so much about the direction you're going, just make sure that:</p> <p>a) You are enjoying it, and are understanding what you are doing. You don't have to initially understand concepts like polymorphism for example, but you should be understanding the basics of what you are doing. Just can't wrap your mind around Tuples and Dictionaries in Python after awhile? Then it's probably not for you. Of course, that's a very low level example as if you don't get Dictionaries, then there's a problem in general :-)</p> <p>b) You are working on things that you want to solve, not just because you think you NEED to learn this. You used the phrase "Windows is a necessary evil" No, it isn't. Many companies (big and small) do not use the .NET platform for development. Your approach to Linux was interesting as you could not achieve something you wanted on it and your result was "it's clunky" which seems kind of awkward.</p> <p>Either way, this isn't about Linux vs. Windows, but I hope that helps. Just go with the flow, and don't worry about what way you're going as long as you're enjoying and learning! :)</p>
45,154
<p>I've never used any kind of source control before although I understand the concept. What I am confused about (and perhaps just not aware) is what benefit do I achieve and/or why would I want to configure Subversion and Apache? Do I need to configure it with Apache to be able to access my repositories from other computers over a network? Please feel free to provide any other details you feel are relevant?</p> <p>My setup right now is a laptop (Windows&nbsp;XP Pro) and a virtual machine (Windows&nbsp;XP Pro). On my virtual machine I have Apache 2.2, MySQL 5 and PHP 5. This setup is my main concern although I'm happy to hear examples/situations that deviate from my scenario.</p>
<p>There's no need to set up Subversion with Apache. I've used Subversion for years and have never had to do so (although there are reasons why you would, mostly to do with authentication infrastructure). Since you're in a Windows world, I've seen that <a href="http://www.visualsvn.com/server/" rel="nofollow noreferrer">VisualSVN Server</a> comes highly recommended and is easy to simply set up and go.</p>
<p>You don't have to use Apache. There's a custom server - svnserve.exe can be used instead. It runs on port 3690 by default, but it can be set to a different port by using the <code>--port</code> switch when setting it up.</p> <p>Greg Hewgill gave you a link which will tell you what version of the Subversion server to use, and the different use cases. It basically boils down to <code>svnserve</code> if you don't need to integrate with any sort of authentication. Use Apache if you need more complex scenarios.</p> <p>I have a commercial Windows console that handles svnserve. My profile has a link to see that utility. If you do decide that you use Apache, I recommend that you use <a href="http://visualsvn.com/server/" rel="nofollow noreferrer">VisualSVN Server</a>.</p>
30,837
<p>If I have a date, how do I calculate the week number for that date within that year?</p> <p>For example, in 2008, January 1st to January 6th are in week 1 and January 7th to the 13th are in week 2, so if my date was January 10th 2008, my week number would be 2.</p> <p>An algorithm would be great to get me started and sample code would also help - I'm developing in C++ on Windows.</p> <h3>Related:</h3> <blockquote> <p><a href="https://stackoverflow.com/questions/348880/getting-week-number-off-a-date-in-ms-sql-server-2005">Getting week number off a date in MS SQL Server 2005?</a></p> </blockquote>
<p>Pseudocode:</p> <pre><code>int julian = getDayOfYear(myDate) // Jan 1 = 1, Jan 2 = 2, etc... int dow = getDayOfWeek(myDate) // Sun = 0, Mon = 1, etc... int dowJan1 = getDayOfWeek("1/1/" + thisYear) // find out first of year's day // int badWeekNum = (julian / 7) + 1 // Get our week# (wrong! Don't use this) int weekNum = ((julian + 6) / 7) // probably better. CHECK THIS LINE. (See comments.) if (dow &lt; dowJan1) // adjust for being after Saturday of week #1 ++weekNum; return (weekNum) </code></pre> <p>To clarify, this algorithm assumes you number your weeks like this:</p> <pre><code>S M T W R F S 1 2 3 &lt;-- week #1 4 5 6 7 8 9 10 &lt;-- week #2 [etc.] </code></pre> <p>getDayOfWeek() and getDayOfYear() are standard date-object operations in most languages. If yours doesn't have them, you can count-forward from some known date (Jan 1, 1970 is a common one), after looking up to see what day of the week it was.</p> <p>If you're going to implement your own date counting routines, remember that years that are divisible by 100 are <strong>NOT</strong> leap years, unless they are also divisible by 400. So 1900 was not a leap year, but 2000 was. If you're going to work far back in time, you have to mess with Gregorian vs Julian calendars, etc., see <a href="http://en.wikipedia.org/wiki/Calendar_reform" rel="noreferrer">Wikipedia</a> for loads of info on that.</p> <p><a href="http://www.codeproject.com/KB/datetime/datetimedisc.aspx" rel="noreferrer">This link</a> talks about date/time functions in Windows/C++ in greater detail.</p>
<pre><code>/** * @brief WeekNo * @param yr * @param mon * @param day * @param iso * @return * * Given a date, return the week number * Note. The first week of the year begins on the Monday * following the previous Thursday * Follows ISO 8601 * * Mutually equivalent definitions for week 01 are: * * the week with the year's first Thursday in it (the ISO 8601 definition) * the week with the Thursday in the period 1 – 7 January * the week starting with the Monday in the period 29 December – 4 January * the week starting with the Monday which is nearest in time to 1 January * the week ending with the Sunday in the period 4 – 10 January * the week with 4 January in it * the first week with the majority (four or more) of its days in the starting year * If 1 January is on a Monday, Tuesday, Wednesday or Thursday, it is in week 01. * If 1 January is on a Friday, Saturday or Sunday, it is part of week 52 or 53 of the previous year. * the week with the year's first working day in it (if Saturdays, Sundays, and 1 January are not working days). *** strftime has a conversion of struct tm to weeknumber. strptime fills in tm struct** * Code uses strptime, strftime functions. */ int WeekNo( int yr,int mon, int day, int iso) { struct tm tm; char format[32]; //memset(tm,0,sizeof(tm)); sprintf(format,"%d-%02d-%02d",yr,mon,day); strptime(format, "%Y-%m-%d", &amp;tm); // structure tm is now filled in for strftime strftime(format, sizeof(format), iso? "%V":"%U", &amp;tm); //puts(format); return atoi(format); } </code></pre> <p>invoke as Weekno(2015,12,23,1); //For ISO week number. Weekno(2015,12,23,0) //For non ISO week number</p>
34,635
<p>I want to provide some RSS feed(s) for my site. Is it worth providing Atom feeds? or is Atom the more common feed? Is there a winner?</p> <p>BTW, this relates to programming because I'm required to program the feed which we will provide (or use some open source code, etc).</p> <h2>Update</h2> <p>So far it looks like peeps are saying Atom should be the way to go if I need to only spend time supporting one? Anyone else agree with these thoughts (and hopefully backed up by some stats??)</p> <h2>Possible Solution</h2> <p>While stumbling around the net for some RSS schema details, I was reading the <a href="http://en.wikipedia.org/wiki/RSS_(file_format)" rel="nofollow noreferrer">RSS Wiki entry</a>, and they say</p> <blockquote> <p>As of January 2007[update], tracking data from www.syndic8.com indicates that the three main versions of RSS in current use are 0.91, 1.0, and 2.0. Of these, RSS 0.91 accounts for 13 percent of worldwide RSS usage and RSS 2.0 for 67 percent, while RSS 1.0 has a 17 percent share.[22] These figures, however, do not include usage of the rival web feed format Atom. As of August 2008[update], the syndic8.com website is indexing 546,069 total feeds, of which 86,496 were some dialect of Atom and 438,102 were some dialect of RSS.[23]</p> </blockquote> <p>This suggests that RSS is the dominant format over Atom. </p> <p>So I might have answered the question myself.</p>
<p>There are a few differences <a href="http://en.wikipedia.org/wiki/Atom_%28standard%29#Atom_compared_to_RSS_2.0" rel="noreferrer">there</a> which could be summed up :</p> <ul> <li>In Atom, the content can be specified (text, html) and can even be a binary (say, an audio track or a video) in base64 encoded form.</li> <li>Using the quite standard used XML date format (rfc3339).</li> <li>Handles content in different languages.</li> <li>Modularity</li> </ul> <p>Also, the Atom file format is part of a greater scheme with is Atom Publication Protocol, which can be used not only to read but also to write.</p>
<p>I wouldn't say either has or will win. Most readers support both, so there's no real push for one to take over the other.</p> <p>But, offering both is probably just a waste of effort. Just pick one, whichever you prefer -- from your comments, I'm guessing RSS.</p>
45,218
<p>I am looking for a bells and whistles CSS framework. I have found a number online that deal with "grids", and some that deal with "typography" and others that deal with "resetting".</p> <p>What I have not found is something that will give my web applications a consistent reusable style or theme.</p> <p>I guess it would have to have a number of predefined elements that do things, for example:</p> <pre><code>div.boxed {...} </code></pre> <p>And then a number of themes or plugins that provide these in a consistent way. Javascript toolkits like ExtJS, YUI, and also GWT have their own skinability, and I guess this is the featureset that I want, but independent of any Javascript library.</p> <p>(Open source would be best, but we don't mind paying)</p> <p><strong>Edit:</strong> 5 good answers, but I have seen all those frameworks, and they are not enough of what I am looking for. Perhaps what I am looking for doesn't exist. Or I haven't explained properly. I will give them a good going over and see.</p>
<p><a href="http://acts-as-architect.blogspot.com/2008/11/introducing-compass.html" rel="nofollow noreferrer">Compass</a> really changes things for you.</p> <p>In addition to providing everything from grids to mixins like horizontal-list, it's built on top of SASS so you get stuff like reuse and variables and other such things.</p> <p>It makes things you don't even realize are painful pain-free. Definitely worth looking over.</p>
<p>I found <a href="http://www.yaml.de/en/" rel="nofollow noreferrer">YAML</a> (Yet Another Multi-columned Layout) to be an excellent, comprehensive, highly adaptable all-rounder.</p>
41,742
<p>Can anyone suggest me on what data structure to use for a <a href="http://en.wikipedia.org/wiki/Soundex" rel="nofollow noreferrer">soundex algorithm</a> program? The language to be used is Java. If anybody has worked on this before in Java. The program should have these features: be able to read about 50,000 words should be able to read a word and return the related words having the same soundex</p> <p>I don't want the program implementation just few advices on what data structure to use.</p>
<p>TIP: If you use SQL as a databackend then you can let SQL handle it with the two sql-functions SOUNDEX and DIFFERENCE.</p> <p>Maybe not what you wanted, but many people do not know that MSsql has those two functions.</p>
<p>Since soundex is a hash, I'd use a hash table, with the soundex as the key.</p>
34,039
<p>I'm using the <code>System.Windows.Forms.WebBrowser</code>, to make a view a-la Visual Studio Start Page. However, it seems the control is catching and handling all exceptions by silently sinking them! No need to tell this is a very unfortunate behaviour.</p> <pre><code>void webBrowserNavigating(object sender, WebBrowserNavigatingEventArgs e) { // WebBrowser.Navigating event handler throw new Exception("OMG!"); } </code></pre> <p>The code above will cancel navigation and swallow the exception.</p> <pre><code>void webBrowserNavigating(object sender, WebBrowserNavigatingEventArgs e) { // WebBrowser.Navigating event handler try { e.Cancel = true; if (actions.ContainsKey(e.Url.ToString())) { actions[e.Url.ToString()].Invoke(e.Url, webBrowser.Document); } } catch (Exception exception) { MessageBox.Show(exception.ToString()); } } </code></pre> <p>So, what I do (above) is catch all exceptions and pop a box, this is better than silently failing but still clearly far from ideal. I'd like it to redirect the exception through the normal application failure path so that it ultimately becomes unhandled, or handled by the application from the root.</p> <p>Is there any way to tell the <code>WebBrowser</code> control to stop sinking the exceptions and just forward them the natural and expected way? Or is there some hacky way to throw an exception through native boundaries?</p>
<p>I haven't seen the browser eat exceptions, unless you mean script errors. Script errors can be enabled via the <code>browser.ScriptErrorsSuppressed</code> property.</p> <p>If you're talking about real exceptions, not just script errors, can you show us some code that reproduces the problem? We've used the browser extensively and haven't seen what you're describing.</p> <p><em>edit</em> the code sample wasn't there when I asked for a code sample</p>
<p>11 years late to the party here, but the following solution works for me.</p> <p>In <code>webBrowserNavigating</code>, replace <code>MessageBox.Show(exception.ToString());</code> with <code>Dispatcher.BeginInvoke(() =&gt; { throw exception; });</code>.</p> <p>As soon as the <code>webBrowserNavigating</code> method completes and control returns to the windows event loop, the exception is thrown and handled by the normal mechanism.</p>
3,867
<p>I'm building a code in which I'd like to be able to generate an event when the user changes the focus of the cursor from an Entry widget to anywhere, for example another entry widget, a button...</p> <p>So far i only came out with the idea to bind to TAB and mouse click, although if i bind the mouse click to the Entry widget i only get mouse events when inside the Entry widget.</p> <p>How can I accomplish generate events for when a widget loses cursor focus?</p> <p>Thanks in advance!</p>
<p>The events &lt;FocusIn&gt; and &lt;FocusOut&gt; are what you want. Run the following example and you'll see you get focus in and out bindings whether you click or press tab (or shift-tab) when focus is in one of the entry widgets.</p> <pre><code>from Tkinter import * def main(): global text root=Tk() l1=Label(root,text="Field 1:") l2=Label(root,text="Field 2:") t1=Text(root,height=4,width=40) e1=Entry(root) e2=Entry(root) l1.grid(row=0,column=0,sticky="e") e1.grid(row=0,column=1,sticky="ew") l2.grid(row=1,column=0,sticky="e") e2.grid(row=1,column=1,sticky="ew") t1.grid(row=2,column=0,columnspan=2,sticky="nw") root.grid_columnconfigure(1,weight=1) root.grid_rowconfigure(2,weight=1) root.bind_class("Entry","&lt;FocusOut&gt;",focusOutHandler) root.bind_class("Entry","&lt;FocusIn&gt;",focusInHandler) text = t1 root.mainloop() def focusInHandler(event): text.insert("end","FocusIn %s\n" % event.widget) text.see("end") def focusOutHandler(event): text.insert("end","FocusOut %s\n" % event.widget) text.see("end") if __name__ == "__main__": main(); </code></pre>
<p>This isn't specific to tkinter, and it's not focus based, but I got an answer to a similar question here:</p> <p><a href="https://stackoverflow.com/questions/165495/detecting-mouse-clicks-in-windows-using-python">Detecting Mouse clicks in windows using python</a></p> <p>I haven't done any tkinter in quite a while, but there seems to be "FocusIn" and "FocusOut" events. You might be able to bind and track these to solve your issue.</p> <p>From: <a href="http://effbot.org/tkinterbook/tkinter-events-and-bindings.htm" rel="nofollow noreferrer">http://effbot.org/tkinterbook/tkinter-events-and-bindings.htm</a></p>
25,843
<p>I'm looking for a tool ($, free, open source; I don't care) that will allow me to view not just the memory statistics for a .NET program, but also the object hierarchy. I'd really like to be able to drill down each thourgh each object and view it's foot print, as well as all the object's it references.</p> <p>I've looked at things like Ants Profiler from RedGate, but it's not quite what I want: I can't view specific instances.</p> <p>EDIT: I've used the .NET Memory Profiler (the one that ships with visual studio, and the one that used to be part of the SDK (?))before, and while it's really good (and shows views most other don't), what I'm really after is being able to drill down through my object hierarchy, viewing each object instance.</p>
<p>I have used JetBrains DotTrace and Redgate Ants, both of which I would recommend. A lesser known profiler I have also used is .Net Memory Profiler (<a href="http://memprofiler.com/" rel="nofollow noreferrer">http://memprofiler.com/</a>), which at the time I used it provided a different perspective on memory usage than the former two profilers mentioned. I find DotTrace and Ants to be very similar, though each one is slightly different.</p>
<p><a href="http://www.jetbrains.com/profiler/" rel="nofollow noreferrer">JetBrains dottrace profiler</a> is the best. I wouldn't work without it. It is hard to find a tool that is free and performs well in this arena. Dottrace is hands down the best profiler I have used for .Net.</p>
7,296
<p>There are several web applications which allow you to send photos from your mobile phone and post them to web site/application. How do these work and what sort of technologies would one use to implement such a feature? Is it an MMS server or does one need to get into socket programming? For example, some applications provide you with an email address to email your photos to via mobile phone. I'm curious to know how these things work. I can somewhat figure out on my own how they work, but I would like to know this feature is normally implemented. </p> <p>Thanks</p>
<p>I think you have three options to support this:</p> <ol> <li>MMS - you would need an <a href="http://www.google.com/search?hl=en&amp;q=mms+gateway&amp;btnG=Google+Search&amp;aq=1&amp;oq=mms+gate" rel="nofollow noreferrer">MMS gateway</a> to recieve MMS messages. This can be software/hardware that you run yourself, or there are services were you pay per message. You would likely need to write your own handling of the message at the application end.</li> <li>Email - you just provide users with an email address to send picture to and you either interface with the email server via POP/IMAP or with the message store directly.</li> <li>Web form - you implement a web form specifically designed for mobile devices that lets them upload pictures. In truth I have no idea if and how many devices support <code>&lt;input type="file" /&gt;</code>, so this may not actually be an option at all.</li> </ol> <p>You can use whatever server-side technology you prefer for processing each of these.</p>
<p>many popular phones including the iPhone unfortunately do not allow from the browser due to sandboxing, so you would either have to use a native application or one of the other methods</p>
20,636
<p>Generally, MVC frameeworks have a structure that looks something like:</p> <pre><code>/models /views /controllers /utils </code></pre> <p>However, in a web application suite, I've decided that clumping all models, views, and controllers together probably wouldn't be the best for clarity, unless I treated the system as one application instead of an application suite. However, some things tie every "application" together, like the notion of users and user roles.</p> <p>So I have three possible solutions:</p> <p>(1) Do what I don't really want to do, and keep every model, view, and controller together, regardless of which app it belongs to. This is treating the suite as a single application, since they are tied together by several common threads, including users.</p> <p>(2) Group the code by application.</p> <pre><code>/app1 /models /views /controllers /utils /app2 /models /views /controllers /utils </code></pre> <p>(3) Group the code by type, letting utility code be shared among all of the applications.</p> <pre><code>/models /app1 /app2 /views /app1 /app2 /controllers /app1 /app2 /utils </code></pre> <p>Is there an option I missed? What would be the most logical scheme for future developers? I personally prefer 2 and 3, but perhaps most people would expect 1.</p>
<p>It seems like 2) would be your best option, assuming you want some separation of applications. You could also have a "/common" folder at the "/app#" level for shared resources across all applications... like a shared utility class or whatever.</p>
<p>If your apps share data, it could make sense (to me) to group the models together. </p> <p>However, for the views and controllers it probably makes more sense to keep them separate, since I'm assuming they have separate business logic and presentations.</p> <p>Further, if your apps are kept separately in version control (you are using version control, right? :), that makes the first or third option difficult to implement.</p> <p>So all things considered, I'd probably separate the apps at the top level, as in your second example.</p>
21,501
<p>Automated tests MUST be fast to reflect real time project state. The idea is that:</p> <ol> <li>after any commit to repository automated build is performed (as fast as it can be done).</li> <li>if build succeeded automated tests are started. MUST be fast.</li> </ol> <p>This is the best way i know to find out if your changes break anything.</p> <p>At first it seemed that making a build fast is hard, but we managed to keep it around 100 sec. for a solution of 105(!) projects (MSVS 2008 C#).</p> <p>Tests appeared to be not that simple (we use NUnit FW). Unit testing is not a big problem. It is integration tests that kills us. And not the fact that they are slower (any ideas on how to make them faster are much appreciated) but the fact that the environment must be set up which is MUCH slower(atm ~1000 sec)!</p> <p>Our integration tests use web/win services (19 so far) that needs to be redeployed in order to reflect latest changes. That includes restarting services and a lot of HDD R/W activity.</p> <p>Can anyone share the experience on how environment and the work flow should/can be organized/optimized to fasten automated testing phase. What are the "low level" bottlenecks and workarounds.</p> <p>P.S. books and broad articles are welcome, but real world working solutions are much more appreciated.</p>
<p>There are a number of optimization strategies you can do to improve the throughput of tests, but you need to ask yourself what the goal of this testing is, and why it needs to be fast.</p> <p>Some tests take time. This is a fact of life. Integration tests usually take time, and you usually have to set up an environment in order to be able to do them. If you set up an environment, you will want to have an environment which is as close to the final production environment as possible.</p> <p>You have two choices:</p> <ol> <li>Optimize the tests, or the deployment of the tests.</li> <li>Don't do them as often.</li> </ol> <p>In my experience, it's better to have an integration environment which is correct, and finds bugs, and represents the final production environment adequately. I usually choose option 2 (1).</p> <p>It's very tempting to say that we'll test everything all of the time, but in realilty you need a strategy.</p> <p>(1) Except if there are loads of bugs which are only found in integration, in which case, forget everything I said :-)</p>
<p>Buildbot: <a href="http://buildbot.net/trac" rel="nofollow noreferrer">http://buildbot.net/trac</a> I can not recommend this enough if you're doing Continuous Integration (automated testing). With a quick configuration all of our unit tests are run each time there is a commit, and the longer integration tests get run periodically through the day (3 times last I checked, but this can be easily changed). </p>
22,328
<p>In my code segment, when I script the file name, it gives me a permission denied on the following line: </p> <pre><code>Set objTextFile = objFSO.OpenTextFile(strDirectory &amp; strFile, ForAppending, True) </code></pre> <p>Here is the script </p> <pre><code>'output log info Function OutputToLog (strToAdd) Dim strDirectory,strFile,strText, objFile,objFolder,objTextFile,objFSO strDirectory = "c:\eNet" strFile = "\weeklydel.bat" 'strText = "Book Another Holiday" strText = strToAdd ' Create the File System Object Set objFSO = CreateObject("Scripting.FileSystemObject") ' Check that the strDirectory folder exists If objFSO.FolderExists(strDirectory) Then Set objFolder = objFSO.GetFolder(strDirectory) Else Set objFolder = objFSO.CreateFolder(strDirectory) 'WScript.Echo "Just created " &amp; strDirectory End If If objFSO.FileExists(strDirectory &amp; strFile) Then Set objFolder = objFSO.GetFolder(strDirectory) Else Set objFile = objFSO.CreateTextFile(strDirectory &amp; strFile) 'Wscript.Echo "Just created " &amp; strDirectory &amp; strFile End If set objFile = nothing set objFolder = nothing ' OpenTextFile Method needs a Const value ' ForAppending = 8 ForReading = 1, ForWriting = 2 Const ForAppending = 2 Set objTextFile = objFSO.OpenTextFile(strDirectory &amp; strFile, ForAppending, True) ' Writes strText every time you run this VBScript objTextFile.WriteLine(strText) objTextFile.Close End Function </code></pre> <p>I have assigned the vbscript domain administrator permissions. Any ideas? </p> <p>thanks in advance</p>
<p>I don't think this has to do with File Permissions per se. It has to do with the fact that you've created the file using:</p> <pre><code>Set objFile = objFSO.CreateTextFile(strDirectory &amp; strFile) </code></pre> <p>That creates the file...and carries a reference to that file (objFile)</p> <p>Then you don't close the file before you destroy the reference</p> <pre><code>... 'Missing objFile.Close here Set objFile = nothing Set objFolder = nothing ... </code></pre> <p>Consequently you're destroying the reference but leaving the textstream open in memory thus locking your file.</p> <p>You are then proceeding to attempt to re-open the file while the file is already "open". This is a little long winded, you've already got a reference after you've created the file - it would be easier just to write straight to that rather than destroy the reference before creating another one.</p>
<p>balabaster is exactly right. You either need to close the file before reopening it a second time for writing, or using the existing open handle.</p>
48,222
<p>I'm going to have my website hosted soon on a VPS or dedicated server (with Windows 2008), so I'm trying to plan ahead. I wonder whether the built-in SMTP server that comes with IIS7 is reliable enough for a production server or should I look for an alternative? I heard good things about hmailserver and best of all it's free, do you have any experience with using the bulit-in SMTP on a high traffic website.</p> <p>Thanks a lot for any suggestions</p>
<p>I hit this thread via Google but I was looking for an outbound only SMTP server for transactional emails (customer registration confirmation etc. but not marketing), then some things I discovered are:</p> <p>SMTP does still exist in Windows Server 2008.</p> <p>Server Manager > Features (not Roles) > Right-click, Add > SMTP Server - then Configure IIS 7 SMTP to point to the local server.</p> <p>Then use the Framework to do the business: <a href="http://msdn.microsoft.com/en-us/library/system.net.mail.smtpclient.aspx" rel="noreferrer">http://msdn.microsoft.com/en-us/library/system.net.mail.smtpclient.aspx</a></p> <p>Jango have a paid for but cheap enough service for exactly this kind of thing. The Free account only allows 200/month but might be useful for some folk.</p> <p><a href="http://www.jangosmtp.com/Pricing.asp" rel="noreferrer">http://www.jangosmtp.com/Pricing.asp</a></p> <p>Good luck!</p> <p><strong>UPDATE</strong></p> <p>I blogged about setting up the original MS SMTP Server on Windows Server 2008.</p> <p><a href="http://www.lukepuplett.com/2010/06/how-to-send-email-from-microsoft-server.html" rel="noreferrer">http://www.lukepuplett.com/2010/06/how-to-send-email-from-microsoft-server.html</a></p>
<p>Maybe sending it via gmail is a good one :P Ok serious. <strike>IIS7 seems I heard to have some decent improvement.</strike> If that's not doing it, I guess you could try free stuff like mailenable. (No I can't find the evidence on the improvement on IIS SMTP, people who know about this please comment)</p> <p>Long term you might end up split it to a linux based smtp though, that gives you some flexibility on server farming if it goes too insane. </p> <p>And if its for any kind of mass mailing that might trigger spam server blocking, don't ever try to host it together with your other important stuff- you want to keep yourself have a back step if your server gets blocked.</p>
34,583
<p>I've used MS Word automation to save a .doc to a .htm. If there are bullet characters in the .doc file, they are saved fine to the .htm, but when I try to read the .htm file into a string (so I can subsequently send to a database for ultimate storage as a string, not a blob), the bullets are converted to question marks or other characters depending on the encoding used to load into a string.</p> <p>I'm using this to read the text:</p> <pre><code>string html = File.ReadAllText(myFileSpec); </code></pre> <p>I've also tried using StreamReader, but get the same results (maybe it's used internally by File.ReadAllText).</p> <p>I've also tried specifying every type of Encoding in the second overload of File.ReadAllText:</p> <pre><code>string html = File.ReadAllText(originalFile, Encoding.ASCII); </code></pre> <p>I've tried all the available enums for the Encoding type.</p> <p>Any ideas?</p>
<p>On my system (using US-English) Word saves *.htm files in the Windows-1252 codepage. If your system uses that codepage, then that is what you should read it in as.</p> <pre><code>string html = File.ReadAllText(originalFile, Encoding.GetEncoding(1252)); </code></pre> <p>It is also possible that whatever you are using the view the results may be creating the question marks for you, though, so be sure and check for that too.</p>
<p>Did you try opening the file in binary mode. If you open in test mode I think it will chop up the unicode characters.</p>
34,402
<p>I need to read smallish (few MB at the most, UTF-8 encoded) XML files, rummage around looking at various elements and attributes, perhaps modify a few and write the XML back out again to disk (preferably with nice, indented formatting).</p> <p>What would be the best XML parser for my needs? There are lots to choose from. Some I'm aware of are:</p> <ul> <li><a href="http://www.jdom.org/" rel="noreferrer">JDOM</a></li> <li><a href="http://wiki.fasterxml.com/WoodstoxHome" rel="noreferrer">Woodstox</a></li> <li><a href="http://xom.nu/" rel="noreferrer">XOM</a></li> <li><a href="http://dom4j.sourceforge.net/" rel="noreferrer">dom4j</a></li> <li><a href="http://vtd-xml.sourceforge.net/" rel="noreferrer">VTD-XML</a></li> <li><a href="http://xerces.apache.org/xerces-j/" rel="noreferrer">Xerces-J</a></li> <li><a href="http://xml.apache.org/crimson/" rel="noreferrer">Crimson</a></li> </ul> <p>And of course the one in the JDK (I'm using Java 6). I'm familiar with Xerces but find it clunky.</p> <p>Recommendations?</p>
<p>I think you should not consider any specific parser implementation. <a href="http://en.wikipedia.org/wiki/JAXP" rel="noreferrer">Java API for XML Processing</a> lets you use any conforming parser implementation in a standard way. The code should be much more portable, and when you realise that a specific parser has grown too old, you can replace it with another without changing a line of your code (if you do it correctly).</p> <p>Basically there are three ways of handling XML in a standard way: </p> <ul> <li><a href="http://en.wikipedia.org/wiki/Simple_API_for_XML" rel="noreferrer">SAX</a> This is the simplest API. You read the XML by defining a Handler class that receives the data inside elements/attributes when the XML gets processed in a serial way. It is faster and simpler if you only plan to read some attributes/elements and/or write some values back (your case).</li> <li><a href="http://en.wikipedia.org/wiki/Document_Object_Model" rel="noreferrer">DOM</a> This method creates an object tree which lets you modify/access it randomly so it is better for complex XML manipulation and handling.</li> <li><a href="http://en.wikipedia.org/wiki/StAX" rel="noreferrer">StAX</a> This is in the middle of the path between SAX and DOM. You just write code to pull the data from the parser you are interested in when it is processed.</li> </ul> <p>Forget about proprietary APIs such as JDOM or Apache ones (i.e. <a href="http://xerces.apache.org/xerces-j/apiDocs/org/apache/xml/serialize/XMLSerializer.html" rel="noreferrer">Apache Xerces XMLSerializer</a>) because will tie you to a specific implementation that can evolve in time or lose backwards compatibility, which will make you change your code in the future when you want to upgrade to a new version of JDOM or whatever parser you use. If you stick to Java standard API (using factories and interfaces) your code will be much more modular and maintainable.</p> <p>There is no need to say that all (I haven't checked all, but I'm almost sure) of the parsers proposed comply with a JAXP implementation so technically you can use all, no matter which.</p>
<p>If you care less about performance, I'm a big fan of Apache Digester, since it essentially lets you map directly from XML to Java Beans.</p> <p>Otherwise, you have to first parse, and then construct your objects. </p>
48,884
<p>When editing really long code blocks (which should definitely be refactored anyway, but that's beyond the scope of this question), I often long for the ability to collapse statement blocks like one can collapse function blocks. That is to say, it would be great if the minus icon appeared on the code outline for everything enclosed in braces. It seems to appear for functions, classes, regions, namespaces, usings, but not for conditional or iterative blocks. It would be fantastic if I could collapse things like ifs, switches, foreaches, that kind of thing!</p> <p>Googling into that a bit, I discovered that apparently C++ outlining in VS allows this but C# outlining in VS does not. I don't really get why. Even notepad++ will so these collapses if I select the C# formatting, so I don't get why Visual Studio doesn't.</p> <p>Does anyone know of a VS2008 add-in that will enable this behavior? Or some sort of hidden setting for it?</p> <p>Edited to add: inserting regions is of course an option and it did already occur to me, but quite frankly, I shouldn't have to wrap things in a region that are already wrapped in braces... if I was going to edit the existing code, I would just refactor it to have better separation of concern anyway. ("wrapping" with new methods instead of regions ;)</p>
<p>Starting with Visual Studio 2017, statement collapsing is built-in.</p> <p>There are several extensions that perform this task for pre-2017 versions of VS, starting with VS 2010 version:</p> <ul> <li><a href="http://visualstudiogallery.msdn.microsoft.com/4d7e74d7-3d71-4ee5-9ac8-04b76e411ea8" rel="noreferrer">C# outline</a></li> <li><a href="https://visualstudiogallery.msdn.microsoft.com/bc07ec7e-abfa-425f-bb65-2411a260b926" rel="noreferrer">C# outline 2012 (@MSDN)</a></li> <li><a href="https://visualstudiogallery.msdn.microsoft.com/6c3c5dec-1534-4c42-81b1-cfd4615fd0e9" rel="noreferrer">C# outline 2013 (@MSDN)</a></li> <li><a href="https://visualstudiogallery.msdn.microsoft.com/9390e08c-d0aa-42f1-b3d2-5134aabf3b9a" rel="noreferrer">C# outline 2015 (@MSDN)</a></li> <li><a href="https://visualstudiogallery.msdn.microsoft.com/699ecb9d-bd8f-4f6b-b290-05c42407b43e" rel="noreferrer">Visual Basic and C# Outliner</a></li> </ul> <p>The last extension supports only VS 2015 and VS 2017, but it's the most powerful one.<br> It supports syntax coloring inside collapsed blocks, it is more fault-tolerant and optimized.</p> <blockquote> <p>If the extension doesn't seem to install after you used a browser to download it, try using the built-in Visual Studio extension manager.</p> </blockquote>
<p># region ,#endregion is the smart option.</p>
36,229
<p>I want to use small flex charts with just 3 labels, for example a chart over the past 2 hours , with 3 horizontal label, as shown below:</p> <pre><code> | | | 9:46 10:46 11:46 </code></pre> <p>(of course, there are more than 3 values to display!)</p> <p>I have been told this is not trivial, but how would you do it? </p> <p>Also, do you know of any books that present how to achieve sophisticated layouts in Flex? The books I have found are code-oriented and usually limit formatting to a minimum, and it's not always straightforward to connect the names of attributes to what you are trying to do.</p>
<p>Take a look in the online <a href="http://livedocs.adobe.com/flex/3/langref/index.html" rel="nofollow noreferrer">Flex Language Guide</a> at the <a href="http://livedocs.adobe.com/flex/3/langref/mx/charts/AxisRenderer.html" rel="nofollow noreferrer">AxisRenderer</a> class. </p> <p>It also has some helpful sample code and output.</p>
<p>Have you looked at the CategoryAxis type? Using this you can explicitly set the labels.</p>
11,845
<p>Would someone explain how to get LINQ working with Sqlite.</p>
<p><a href="http://code.google.com/p/dblinq2007/" rel="noreferrer">Here you have an SQL Linq provider for SQLite, and some other DBs</a></p>
<p>Check this provider:</p> <p><a href="http://kkubasik.wordpress.com/2007/10/25/sqllite-linq-provider/" rel="nofollow noreferrer">SqlLite Linq Provider</a></p> <p>Also you can consider using <a href="http://www.microsoft.com/Sqlserver/2005/en/us/compact.aspx" rel="nofollow noreferrer">SQL Compact</a> which has very good LINQ-to-SQL support.</p>
41,268
<p>How do I ask PowerShell where something is? </p> <p>For instance, "which notepad" and it returns the directory where the notepad.exe is run from according to the current paths.</p>
<p>The very first alias I made once I started customizing my profile in PowerShell was 'which'.</p> <pre class="lang-sh prettyprint-override"><code>New-Alias which get-command </code></pre> <p>To add this to your profile, type this:</p> <pre class="lang-sh prettyprint-override"><code>"`nNew-Alias which get-command" | add-content $profile </code></pre> <p>The `n at the start of the last line is to ensure it will start as a new line.</p>
<p>There also always the option of using which. there are actually three ways to access which from Windows powershell</p> <ul> <li>The first, (though not the best) is wsl(windows subsystem for linux)</li> </ul> <pre class="lang-sh prettyprint-override"><code>wsl -e which command </code></pre> <p>This requires installation of windows subsystem for Linux and a running distro.</p> <ul> <li><p>Next is <a href="http://gnuwin32.sourceforge.net/packages.html" rel="nofollow noreferrer">gnuwin32</a> which is a port of several gnu binaries in .exe format as standle alone bundled lanunchers</p> </li> <li><p>Third, install <a href="https://www.msys2.org/" rel="nofollow noreferrer">msys2</a> (cross compiler platform) if you go where it installed in /usr/bin you'll find many many gnu utils that are more up-to-date. most of them work as stand alone exe and can be copied from the bin folder to your home drive somewhere amd added to your PATH.</p> </li> </ul>
8,927
<p>I've often heard Ruby's inject method criticized as being "slow." As I rather like the function, and see equivalents in other languages, I'm curious if it's merely Ruby's <strong>implementation</strong> of the method that's slow, or if it is inherently a slow way to do things (e.g. should be avoided for non-small collections)?</p>
<p><code>inject</code> is like <code>fold</code>, and can be very efficient in other languages, <code>fold_left</code> specifically, since it's tail-recursive.</p>
<p><code>each_with_object</code> may be faster than <code>inject</code>, if you're mutating an existing object rather than creating a new object in each block.</p>
41,219
<p>I can't stand HTML intermixed with other code. I'm working on a codebase that has to remain in PHP, and I don't want to touch an HTML template with a proverbial pole. So what I'm currently doing looks like this:</p> <pre><code>&lt;?php $page = new html_page('My wonderful page'); $page-&gt;add_contents(new html_tag('p', 'It works', array('id' =&gt; 'helloworld', 'class' =&gt; 'somecssclass'))); echo $page-&gt;render(); ?&gt; </code></pre> <p>Everything belongs to a nice hierarchy of objects, which is good and dandy. Of course I have a lot of smaller classes, and I'm thinking of using dynamic classes (for example, 'html_a' will automagically create an html_tag object of type 'a'.)</p> <p>It seems that nobody else is doing this. Why not? What am I missing?</p> <p>(I clearly remember an open source library that did exactly this, but can't find it anymore. So unless I'm actually imagining things, I'm not the only one who thought of this approach to render HTML)</p> <p>Do you have any thoughts on this?</p> <p>Here are some additional details:</p> <ol> <li>I'm the only developer in this project.</li> <li>How I'm mixing code with HTML: an &quot;html_tag&quot; object from my library is pretty similar to, say, a node in the DOM. The &quot;render&quot; method is the one that creates HTML, but I don't write any opening or closing tag anywhere.</li> <li>I create small objects for several tasks. These objects have methods to build tag objects; these resulting objects are then inserted into, say, tables or pages.</li> <li>My library have some primitive access methods to find objects. So the iterator example posted in <a href="https://stackoverflow.com/questions/262652/php-tag-library#262881">26288</a> can be implemented with relative ease.</li> <li>I'm not worried about performance (yet).</li> </ol>
<p>Well, the bottom line is, you're still mixing your HTML with your code. If you wanted to change that "p" tag to a "div", you'd have to wander through your code just to do it. Think about what your method offers:</p> <ul> <li>mixes code with HTML</li> <li>adds overhead to parse all the requests</li> <li>introduces a new "language" over HTML</li> </ul> <p>In essence, while the approach may be different, it has the same issues the template languages you are trying to get away from has.</p> <p>Wouldn't it be easier, if you're working alone (or in a group), to just let PHP be the template language?</p> <pre><code>$page = new Page('test.html'); $page-&gt;load($data); $page-&gt;render(); </code></pre> <p>and in your test.html "template"</p> <pre><code>&lt;html&gt; &lt;head&gt; &lt;title&gt;&lt;?php echo $title ?&gt;&lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;p&gt;&lt;?php echo $hello ?&gt;&lt;/p&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>What other template engines do really is formalize the above code. but if you stick to basics (echoing variables, basic conditionals, looping), you essentially have all the power of a template language, but in familiar PHP, and with no performance overhead.</p> <p>Plus, unlike your example, you can alter the HTML (i know you didn't want to touch it, but changing a "p" to a "div" in code really isn't that different from change <code>&lt;p&gt;</code> to <code>&lt;div&gt;</code>), without having to delve into the code.</p>
<p>Nobody else is doing it because it's quite a bit more work than just escaping in and out of PHP mode for a template file, not to mention it just adds overhead purely to satisfy your preference for code aesthetics.</p> <p>This doesn't mean you can separate logic from display, such as a simple system like Owen suggested. But to shy away from the convention of php mixed with HTML just because you don't like it is a little silly - it's how the language was made to be used.</p>
32,884
<p>How can you check if a string is a valid GUID in vbscript? Has anyone written an IsGuid method?</p>
<p>This is similar to the <a href="https://stackoverflow.com/questions/104850/c-test-if-string-is-a-guid-without-throwing-exceptions#104932">same question in c#</a>. Here is the regex you will need...</p> <p>^[A-Fa-f0-9]{32}$|^({|()?[A-Fa-f0-9]{8}-([A-Fa-f0-9]{4}-){3}[A-Fa-f0-9]{12}(}|))?$|^({)?[0xA-Fa-f0-9]{3,10}(, {0,1}[0xA-Fa-f0-9]{3,6}){2}, {0,1}({)([0xA-Fa-f0-9]{3,4}, {0,1}){7}[0xA-Fa-f0-9]{3,4}(}})$</p> <p>But that is just for starters. You will also have to verify that the various parts such as the date/time are within acceptable ranges. To get an idea of just how complex it is to test for a valid GUID, look at the source code for one of the Guid constructors.</p>
<p>there is another solution:</p> <pre><code>try { Guid g = new Guid(stringGuid); safeUseGuid(stringGuid); //this statement will execute only if guid is correct }catch(Exception){} </code></pre>
16,159
<p>I have a column containing the strings 'Operator (1)' and so on until 'Operator (600)' so far.</p> <p>I want to get them numerically ordered and I've come up with</p> <pre><code>select colname from table order by cast(replace(replace(colname,'Operator (',''),')','') as int) </code></pre> <p>which is very very ugly.</p> <p>Better suggestions?</p>
<p>It's that, InStr()/SubString(), changing Operator(1) to Operator(001), storing the n in Operator(n) separately, or creating a computed column that hides the ugly string manipulation. What you have seems fine.</p>
<p>My answer would be to change the problem. I would add an operatorNumber field to the table if that is possible. Change the update/insert routines to extract the number and store it. That way the string conversion hit is only once per record.</p> <p>The ordering logic would require the string conversion every time the query is run.</p>
10,099
<p>I'm wondering if there is any way to create a User Account on a Windows XP machine that can be done through scripting from an ActiveX control on a webpage. Specifically, I'd like to know if there's any way to deploy an ActiveX control with computers (that I preconfigure and ship) that will allow use of my webpage from that computer to detect that the ActiveX control is present, and allow for automated creation of local (Windows XP) user accounts on the computer. Essentially, consider this to be a question of preinstalling an ActiveX control (if necessary) and providing a link on the desktop; the user receives the machine and logs on (with admin rights) and goes to a web site, where my server determine what the appropriate user accounts are, sends them back as HTML, and the ActiveX control creates the user accounts I specify.</p> <p>This sort of thing seems like it should be possible, but at the same time, there are obvious security flaws that are potentially involved. Access to these machines will be very limited, so the security issues are less of a concern.</p> <p>Does anyone know if this is possible? Do any of the built in WMI components do anything like this? Is this even allowed by the security model of XP? Or is this just opening up a huge security hole that should be avoided entirely?</p>
<p>There is a semicolon after <code>eval</code>.</p>
<p>There is a semicolon after <code>eval</code>.</p>
39,042
<p>I want to stitch 2 pieces of png side by side. In Cocoa, I would use [NSImage initWithSize], and then just drawInRect. </p> <p>But UIImage don't have initWithSize class, how would I do this now?</p>
<p>Use <code>UIGraphicsBeginImageContext()</code>, draw in it, then use <code>UIGraphicsGetImageFromCurrentImageContext()</code>. Remember to pop the context with <code>UIGraphicsEndImageContext()</code> afterwards.</p> <p>You should avoid creating an extra image if you simply want to display the two images onscreen, due to the limited memory available on the device. Instead, display them using appropriate <code>drawInRect:</code> calls to avoid copying.</p>
<p>Apple's TheElements demo (AtomicElementViewController) has a great example on how to do this. And also how to create a reflection and bevelled look.</p>
26,867
<p>I'm developing a web app for an Apache shared hosting server. I have already written some code in Perl but I recently found out, to my surprise, the shared hosting provider does not provided mod_perl or a way to install it.</p> <p>I have been a bit worried that running a Perl web app through CGI without mod_perl would make it very slow? Should I switch all of my code to PHP instead, would that be faster?</p> <p>The reason I chose Perl in the first place is, I'm very familiar with Perl more than PHP. Also I wanted to be able to use my Perl libraries outside the realm of web development.</p> <p>So if any of you are experienced with Apache web development, can you shed some light as to which direction should I take.</p> <p>For the sake of this question, lets say the web application will get 500+ hits a day.</p> <p>Which would be faster PHP or Perl without mod_perl?</p> <p>Thanks in advance for the help.</p>
<p>PHP would be faster.</p> <p>However, with only 500 hits per day, using cgi would not be a problem. Not even with 500 hits an hour.</p>
<p>It depends mostly on how complex your code is and how it's put together; if you run it as CGI, perl will compile your script and modules on each invocation, and will have to reconnect to your database for each request. If your code is complex enough, this may take a few seconds per pageview, which may hamper user experience.</p> <p>If your codebase and used modules isn't huge though, there should be no problem at all.</p> <p>You can do a perl -c on your code to get a feel for how long perl startup and your compilation time is.</p>
40,356
<p>I have a SelectList that I first check for a selected value != null and then want to use this selectedvalue in a where clause for a filter. Like so:</p> <pre><code>if(searchBag.Qualities.SelectedValue != null){ ListItem selected = (ListItem)searchBag.Qualities.SelectedValue; } </code></pre> <p>I made the cast in a seperate useless line to pinpoint the problem. This gives me a </p> <blockquote> <p>Unable to cast object of type 'WhereListIterator`1[System.Web.Mvc.ListItem]' to type 'System.Web.Mvc.ListItem'.</p> </blockquote> <p>Weuh?</p> <p><strong>--EDIT--</strong><br> It was indeed because multiple selections were made. This was because on creation I set the selected value to theItems.Where(i=>i.someCriterea) and I forgot to put .FirstOrDefault() at the end. Ending up in the possibility of multiple answers. Since it was an IEnumerable, it was a lazy list and hence the WhereListIterator I guess. I solved it by simple putting FirstOrDefault at the end.</p>
<p>It's never a good idea to use <code>DoCmd.RunSQL</code> as it generates a prompt (which you have to turn off if you don't want it), and it completes the updates even if errors occur, and doesn't report the errors. Much better is to replace it with a function that executes the same SQL:</p> <pre><code>Public Function SQLRun(strSQL As String) As Boolean On Error GoTo errHandler CurrentDB.Execute strSQL, dbFailOnError SQLRun= True exitRoutine: Exit Function errHandler: MsgBox err.Number &amp; ": " &amp; err.Description, vbExclamation, "Error in SQLRun()" Resume exitRoutine End Function </code></pre> <p>Once you've placed this in a public module, you can easily do a global search and replace for <code>DoCmd.RunSQL</code> to replace it with <code>SQLRun</code>.</p> <p>EDIT: Another version of this function that returns the number of records affected is <a href="https://stackoverflow.com/questions/343396/acess-vba-to-get-value-from-update-query-prompt/348453#348453">here</a>.</p>
<p>I don't see any way at this time to get the information after the update query has run unless you have another distinguishing field (maybe an updated date field). Why not run a select query for it and run a report off of that data, THEN run the update query to change the values for 'bonus'.</p> <p>Let me know if this helps! JFV</p>
43,283
<p>Many, if not all, of my old VC++ 6.0 MFC apps don't work in Vista and Server 2008. I had that migration was a problem, but now it's my problem :(</p> <p>How do I go about making these things work? Is that possible? I've searched, but is there some repository of knowledge on this subject?</p> <p>edit: Compatibility mode seems to work.</p>
<p>There should be specific reasons why they don't work, and of course, what exactly does not work. Maybe you should break each issue into a separate question (maybe here at SO) and tell us exactly what kind of problems you have when you try to run them, and what is the code that makes those errors show up.</p> <p>Without the details, it's too vague. There is no magic you can apply to make applications simply work just like that.</p>
<p>There should be specific reasons why they don't work, and of course, what exactly does not work. Maybe you should break each issue into a separate question (maybe here at SO) and tell us exactly what kind of problems you have when you try to run them, and what is the code that makes those errors show up.</p> <p>Without the details, it's too vague. There is no magic you can apply to make applications simply work just like that.</p>
18,041
<p>What is the difference between a deep copy and a shallow copy?</p>
<p>Shallow copies duplicate as little as possible. A shallow copy of a collection is a copy of the collection structure, not the elements. With a shallow copy, two collections now share the individual elements.</p> <p>Deep copies duplicate everything. A deep copy of a collection is two collections with all of the elements in the original collection duplicated. </p>
<p>Adding to all the above definitions, one more and most commonly used deep copy, is in the copy constructor (or overloading assignment oprator) of the class.</p> <p>Shallow copy --> is when you are not providing copy constructor. Here, only the object gets copied but not all the members of the class are copied.</p> <p>Deep copy --> is when you have decided to implement copy constructor or overload assignment in your class and allows copying all the members of the class.</p> <pre><code>MyClass&amp; MyClass(const MyClass&amp; obj) // copy constructor for MyClass { // write your code, to copy all the members and return the new object } MyClass&amp; operator=(const MyClass&amp; obj) // overloading assignment operator, { // write your code, to copy all the members and return the new object } </code></pre>
22,341
<p>Here's the sit:</p> <ul> <li>I have a JSF component which is basically a list of 'documents'</li> <li>I have any number of document viewer components on the same page.</li> <li>None of these components "know" about each other. In other words, they cannot be configured at design time to link to each other or anything like that.</li> </ul> <p>When the user clicks a document link I wish each one of the document viewer components to be notified.</p> <p>Basically the idea would be to have the document viewers publish the fact that they listen for a certain type of event ("DocumentSelectedEvent" say) which the doc list component would fire.</p> <p>I can think of ways of doing this that are not JSF specific, but I'm wondering if the JSF event model can handle that sort of thing.</p> <p>Anyone have any ideas?</p>
<p>I don't think there's a way of doing that with the standard JSF event model. </p> <p>Is there any way you can bind the components to a backing bean? That way when an event happens you can just go through your list of components and notify each of them.</p>
<p>ValueChangeEvent</p> <p>I do not know how you implemented your document list but if it were say a dropdown or any other multi item list component you can do an Value Change Event and force a submit on change for the component. Then in the page code backing bean you can call the methods for your viewers to load whatever you like.</p> <p>In your jsf you just specify the value change handler you wrote in the backing bean.</p> <pre><code> /** * Handle document click value change. * * @param valueChangedEvent the value changed event */ public void handleDocumentSelect(ValueChangeEvent valueChangedEvent) { String selectedDocument = valueChangedEvent.getNewValue(); doDocViewer1DisplayMethod(selectedDocument); doDocViewe2DisplayMethod(selectedDocument); } </code></pre> <p>Modify your jsf tag to use your new value change event handler and force the submit.</p> <pre><code> &lt;f:componentTag attr=xxx attr=xxx valueChangeListener="#{pc_BackingBean.handleDocumentSelect}" onChange=submit();&gt; </code></pre>
32,189
<p>I'm embedding a JRE in an existing C application using the invocation API, and I'd like to be able to use JDBC to work with the database in that code. This application is a transaction processing application, and the database transaction is managed by code in the C portion of the application, and the java code must run within that transaction. This means that I can't open a <em>new</em> connection, I must re-use the existing one.</p> <p>So, is there a way to provide JDBC access to an existing ODBC connection handle when setting up the JRE? Some JDBC-ODBC bridge, perhaps, but unlike the existing driver by that name, one that can be set up to use an existing connection and transaction.</p> <p>My other options, as I see them, are as follows:</p> <ul> <li><p>Provide java equivalents for every C operation that is possible in the application (this is not desirable for a great many reasons -- we have a great many methods and duplicating them is a pain in the ass.</p></li> <li><p>Write my own JDBC driver that wraps the ODBC connection with JNI. Sure, it'd be a fun weekend (month) project, but I expect to need something done faster than that.</p></li> </ul> <p>Help me, Stack-Overflow, you're my only hope!</p>
<p>Don't know whether this'll work, but... I had a quick look at the decompiled source code of Sun's JDBC-ODBC bridge. Seems like you could subclass the JdbcOdbcConnection so that it initializes itself with a known connection handle and an already-opened state. This assumes that the connection handles on the Java side are actual ODBC connection handles or pointers to connection objects, and that ODBC libraries used by the JDBC-ODBC bridge and your code are compatible in the sense that they can share connection handles.</p> <p>You need to check whether Sun's license allows developers to perform such trickery though.</p>
<p>Sun provides a <a href="http://java.sun.com/j2se/1.5.0/docs/guide/jdbc/bridge.html" rel="nofollow noreferrer">JDBC-ODBC bridge</a> in the JDK.</p> <p>EDIT: Rereading sounds like you already know about it and don't want to use it.</p>
21,734
<p>I am trying to debug a web application through IIS that has a virtual directory other than localhost. It compiles fine but gets the above message anytime that I try to start debugging. I have compilation debug="true".</p>
<p>Right click your 'web' project and select 'property pages'. Then change 'Start Options' to 'Don't open a page. Wait for a request from an external application.' and for server, select 'Use custom server' with Base URL: '<a href="http://localhost/your_virtual_dir/" rel="nofollow noreferrer">http://localhost/your_virtual_dir/</a>'</p> <p>Then with a web browser opened pointing to the IIS location (and virtual dir) you setup, the two should work in tandem with each other.</p> <p>Hope that helped.</p>
<p><a href="http://msdn.microsoft.com/en-us/library/dwesw3ee.aspx" rel="nofollow noreferrer">Error: Unable to Start Debugging on the Web Server</a></p> <p>Check the points in the MSDN article above. IME, its normally one of these things:</p> <ol> <li><p>Has the application directory been created as an application in IIS? On the Directory tab, under Application Settings, next to the application name you will see the create button. Click this!</p></li> <li><p>On the ASP.NET tab in IIS, has the correct version of the framework been selected?</p></li> <li><p>Re-register ASP.NET: From a command prompt window, run the following command: systemroot\Microsoft.NET\Framework\ versionNumber \aspnet_regiis -i</p></li> </ol>
32,352
<p>I am looking to have 4 Virtual servers(various linux flavors) running on a Windows server 2003 R2 64 bit edition server located at a datacenter. I can also purchase a 2008 server or 32 bit 2k3 if needed. They would each have their own ip address for networking so that they could be publicly accessed. I do not know much about VPS software but have worked with it before.</p>
<p><a href="http://technet.microsoft.com/en-gb/bb738033.aspx" rel="nofollow noreferrer">Virtual Server 2005 R2 SP1</a> is free (registration required) and supports x64 hosts. It does not support x64 guests.</p> <p>Windows Server 2008 includes Hyper-V, Microsoft's new virtualization technology, which supports x64 guests and multiple virtual processors. There are editions without Hyper-V as well, for marginally less money, to satisfy the anti-trust authorities. The Hyper-V <a href="http://support.microsoft.com/?kbid=950050" rel="nofollow noreferrer">update</a> has to be downloaded as it was completed after the rest of Windows Server 2008 was released.</p> <p><a href="http://www.vmware.com/products/server/" rel="nofollow noreferrer">VMware Server</a> is also free. It supports (experimentally) up to 2 virtual CPUs.</p> <p>To get best performance you need drivers and patches in the virtual machine which work well with the virtualization environment. In Virtual Server these are called Additions, in Hyper-V they are Integration Components, and for VMware, VMware Tools. Because of the nature of kernel binary compatibility (there are no guarantees), only specific distributions are generally supported.</p> <ul> <li><a href="http://technet.microsoft.com/en-us/virtualserver/bb676671.aspx" rel="nofollow noreferrer">Download Virtual Server Additions for Linux</a></li> <li><a href="https://connect.microsoft.com/SelfNomination.aspx?ProgramID=1863&amp;pageType=1&amp;SiteID=495" rel="nofollow noreferrer">Download Hyper-V Linux Integration Components</a></li> </ul>
<p>Unfortunately, the only way you are going to get decent performance is by using Linux as the host and Windows as the guest. The signed driver requirement on x64 essentially prevents any open source implementation from having reasonable performance.</p>
10,468
<p>Is there a tool, method or setting in the standard VBA Editor to warn about variables that have been <code>Dim</code>'med, but aren't being used?</p>
<p><a href="http://www.mztools.com/index.aspx" rel="noreferrer">MZ-Tools</a> will search through your code and tell you what is not being used. The version for VBA can be found <a href="http://www.mztools.com/v3/mztools3.aspx" rel="noreferrer">here</a>.</p> <p>The specific feature in MZ-Tools that performs what you asking about is <a href="http://www.mztools.com/v3/onlinehelp/index.html?html_review_source_code.htm" rel="noreferrer">Review Source Code</a>:</p> <blockquote> <p>The Review Source Code feature allows you to review the source code to detect some unused declarations (constants, variables, parameters, procedures, etc.).</p> </blockquote>
<p>Another method (because I don't have admin privileges to install that software), is to put <code>Option Explicit</code> at the top of your module. Then comment out all the <code>Dim</code>'med variables, and debug through your code with <kbd>F8</kbd> or recompile with <kbd>Alt</kbd>+<kbd>d</kbd>+<kbd>l</kbd></p> <p>Uncomment the <code>Dim</code>s one by one until <code>Option Explicit</code> returns no compiler errors, at which point any variables still commented out can be ignored, as they are not used in your code</p> <hr /> <p>Similar to MZ-Tools, <a href="https://github.com/rubberduck-vba/Rubberduck/releases/latest" rel="nofollow noreferrer">RubberDuck</a> has a <a href="https://rubberduckvba.com/Inspections/Details/VariableNotUsed" rel="nofollow noreferrer">VariableNotUsed Inspection</a> (amongst many other things) that should show precisely what you're after. It's free and, as of v2.2.0.3086, it supports non-admin installation.</p>
22,914
<p>Is there a NAnt task that will echo out all property names and values that are currently set during a build? Something equivalent to the Ant <a href="http://ant.apache.org/manual/Tasks/echoproperties.html" rel="noreferrer">echoproperties</a> task maybe?</p>
<p>Try this snippet:</p> <pre><code>&lt;project&gt; &lt;property name="foo" value="bar"/&gt; &lt;property name="fiz" value="buz"/&gt; &lt;script language="C#" prefix="util" &gt; &lt;code&gt; &lt;![CDATA[ public static void ScriptMain(Project project) { foreach (DictionaryEntry entry in project.Properties) { Console.WriteLine("{0}={1}", entry.Key, entry.Value); } } ]]&gt; &lt;/code&gt; &lt;/script&gt; &lt;/project&gt; </code></pre> <p>You can just save and run with nant.</p> <p>And no, there isn't a task or function to do this for you already.</p>
<p>You can't prove a negative, but I can't find one and haven't seen one. I've traditionally rolled my own property echoes.</p>
16,998
<p>Could you guys recommend me a good db modeling tool? Mainly for SQL Server...</p> <p>thanks!</p>
<p>If it is for SQL Server I like the DB Diagram from SQL Server Management Studio.</p>
<p>I used pencil and paper quite successfully to get the initial entities and relationships down. Especially good if designing with other people, you don't get distracted by the GUI interface, mousing around, getting the background gradients right, etc. Then you can translate it into Visio or Dia or a UML tool that generates both the SQL Schema and your object model...</p> <p>Usually after this time constraints mean you end up in TOAD or your DB tool of choice getting the tables, indexes, foreign keys and stuff implemented in straight SQL or with their table designer tool. Changes will inevitably come up downstream so don't spend too long getting things exactly, just get the structure right.</p>
20,120
<p>I am new to git. I am wondering whether the following scenario is supported, and if so how (i.e. git commands for setup and update).</p> <p>A repository is available from three different places: 'local', 'mirror' and 'github'. 'mirror' mirrors 'local' completely and 'github' mirrors 'local' except for a 'copyrighted' directory.</p> <p>Thanks.</p>
<p>A submodule can work, but if you try to clone something that contains submodules for which one of the remotes is unavailable, you'll have aggravating errors.</p> <p>My alternative would be to use the 'filter-branch' command to maintain a public branch that would omit the copyrighted files for public consumption on GitHub.</p>
<p>I think it is not possible. What you can try is to put "copyrighted" directory in a separate branch which is not mirrored, but it will just make more hassle.</p>
35,134
<p>Using ASP.net 2.0, how do I present the information to the user similar to the Questions list on SO where each question has some child items (like the tags).</p> <p>I would probably be making two separate queries, one to first find the list of questions, then another query to find all tags which belonged to the list of questions.</p> <p><em>Approach 1:</em></p> <p>Then I would probably be using nested repeaters and doing a select statement in the code-behind on each nested repeater "OnItemDataBind"...</p> <p><em>Approach 2:</em></p> <p>Or with the two datasets, I would use C# code to create a business entity of each of the "Questions" and have a property called "Tags". I would then loop through my tags dataset and assign the property.</p> <p>What's more efficient? Are there any other alternatives?</p>
<p>I would definitely avoid the second approach - you don't want to hit the database everytime you databind a parent item. As DOK says, try and architect your system properly. For me that would mean populating a collection of business objects and binding to it. I do something similar with a custom menu control (note this nests three datalists, but you could use repeaters):</p> <p>In the aspx page:</p> <pre><code>&lt;asp:DataList ID="dlMenuOne" runat="server" onitemdatabound="dlMenu_ItemDataBound" &gt; &lt;ItemTemplate&gt; //your object &lt;asp:DataList ID="dlMenuTwo" runat="server" onitemdatabound="dlMenuTwo_ItemDataBound"&gt; &lt;ItemTemplate&gt; //your object's child items &lt;asp:DataList ID="dlMenuThree" runat="server"&gt; &lt;ItemTemplate&gt; //child item's child items &lt;/ItemTemplate&gt; &lt;/asp:DataList&gt; &lt;/ItemTemplate&gt; &lt;/asp:DataList&gt; &lt;/ItemTemplate&gt; &lt;/asp:DataList&gt; </code></pre> <p>then in the code behind:</p> <pre><code>protected void dlMenu_ItemDataBound(object sender, DataListItemEventArgs e) { DataListItem parentList = e.Item; DataList dlMenuTwo = (DataList)parentList.FindControl("dlMenuTwo"); MenuItem item = (MenuItem)parentList.DataItem; dlMenuTwo.DataSource = _menu.GetChildItems(item); dlMenuTwo.DataBind(); } </code></pre> <p>this method basically gets a reference to the object being bound (parentList.DataItem) and then binds the nested DataList to the child items (_menu.GetChildItems(item))</p>
<p>If you do two separate queries, you can still make them in one call to the database, and get back two resultsets.</p> <p>Instead of DataSets, you could use the more efficient DataReader (with two resultsets). Loop through the resultsets and populate Question objects with associated Tag objects or properties. Put those objects in an ArrayList or a generic List, and you can bind it to your Repeater.</p> <p>Instead of doing anything in code-behind, you should consider moving that code to at least a data access layer (class) if you don't need a business logic layer (another class).</p> <p>All of these suggestions only apply if your app is non-trivial. Using OO methods does add to the code, but if you are doing anything beyond displaying the information, it would be better to start off with a good OO architecture (DAL and BLL, if not MVC).</p>
34,814
<p>I am using the Entity Framework and Linq to Entities. I have created a small database pattern &amp; framework to implement versioning as well as localization. Every entity now consists of two or three tables, (ie Product, ProductBase &amp; ProductLocal). </p> <p>My linq always includes the following boilerplate code:</p> <pre><code>from o in DB.Product from b in o.Base from l in o.Local WHERE o.VersionStatus == (int)VersionStatus.Active &amp;&amp; b.VersionStatus == (int)VersionStatus.Active &amp;&amp; l.VersionStatus == (int)VersionStatus.Active &amp;&amp; l.VersionLanguage == Context.CurrentLanguage select new ProductInstance { Instance = o, Base = b, Local = l } </code></pre> <p>What I would like to accomplish is to turn the above into:</p> <pre><code>(from o in DB.Product from b in o.Base from l in o.Local select new ProductInstance { Instance = o, Base = b, Local = l }).IsActive() </code></pre> <p>Or at worst, something like:</p> <pre><code>from o in DB.Product.Active() from b in o.Base.Active() from l in o.Local.Active() select new ProductInstance { Instance = o, Base = b, Local = l } </code></pre> <p>I have extended the base classes the EDM generates to implement some interfaces that enforce the properties ( IVersionStatus and/or IVersionLanguage ). Is there some way I can walk the expression tree, check if the type in the expression implements that interface, then set the VersionStatus accordingly?</p> <p>I woud love it to be as simple as the first option, just less to write and/or forget. I have seen examples that do it after the fact, after its IEnumerable, but I would rather not pull more from the database than I need to. </p> <p>Thanks for any tips! </p>
<p>Yes.</p> <p>You can do this by defining an extension method named IsActive on IQueryable. There is a property on IQueryable called "Expression" that returns an expression tree representing the chain of LINQ method calls that was generated from your query.</p> <p>In your case that will look something like this:</p> <pre><code>DB.Product.SelectMany(o=&gt;o.base, (o, b)=&gt;new{o.b}).SelectMany(item=&gt;o.local, (item, local)=&gt;new {item.o, item.b, item.local}).Select(item=&gt;new ProductInstance { Instance = item.o, Base = item.b, Local=item.Local}); </code></pre> <p>The "DB.Product" is the item from the first From clause. Each remaining "SelectMany" call is an additional from clause. </p> <p>You can then dig into the expression trees to gather all the from clause elements. look at their types, and then finally generate an expression tree for a where clause.</p> <p>Your extension method would then return .Where off of it's IQueryable argument using the where clause that you generated.</p> <p>The resulting Where clause would then be executed on the server with the rest of the query when you try to "foreach" over the results.</p> <p><strong>EDIT:</strong></p> <p>Please note that if you want this to work with explicit "Join" clauses then you will also need to add support for the "Join" method in addition to "SelectMany".</p>
<p>You need to use the DataLoadOptions class so that it automatically loads the foreign key relationships you specify on that object. That will make it so that it will automatically get the linked tables that you specify which is really what you're doing.</p> <p>This page details how to do that and tells more about what I think you're looking for. </p> <p><a href="http://www.crazysalsadancer.com/2008/08/efficient-data-loading-with-linq-using.html" rel="nofollow noreferrer">http://www.crazysalsadancer.com/2008/08/efficient-data-loading-with-linq-using.html</a></p>
26,697
<p>What is the purpose of the <code>strdup()</code> function in C?</p>
<p>Exactly what it sounds like, assuming you're used to the abbreviated way in which C and UNIX assigns words, it <em><strong>duplicates strings</strong></em> :-)</p> <p>Keeping in mind it's actually not part of the current (C17) ISO C standard itself<sup>(a)</sup> (it's a POSIX thing), it's effectively doing the same as the following code:</p> <pre><code>char *strdup(const char *src) { char *dst = malloc(strlen (src) + 1); // Space for length plus nul if (dst == NULL) return NULL; // No memory strcpy(dst, src); // Copy the characters return dst; // Return the new string } </code></pre> <p>In other words:</p> <ol> <li><p>It tries to allocate enough memory to hold the old string (plus a '\0' character to mark the end of the string).</p> </li> <li><p>If the allocation failed, it sets <code>errno</code> to <code>ENOMEM</code> and returns <code>NULL</code> immediately. Setting of <code>errno</code> to <code>ENOMEM</code> is something <code>malloc</code> does in POSIX so we don't need to explicitly do it in our <code>strdup</code>. If you're <em>not</em> POSIX compliant, ISO C doesn't actually mandate the existence of <code>ENOMEM</code> so I haven't included that here<sup>(b)</sup>.</p> </li> <li><p>Otherwise the allocation worked so we copy the old string to the new string<sup>(c)</sup> and return the new address (which the caller is responsible for freeing at some point).</p> </li> </ol> <p>Keep in mind that's the conceptual definition. Any library writer worth their salary may have provided heavily optimised code targeting the particular processor being used.</p> <p>One other thing to keep in mind, it looks like this <em>is</em> currently slated to be in the C2x iteration of the standard, along with <code>strndup</code>, as per draft <code>N2912</code> of the document.</p> <hr /> <p><sup>(a)</sup> However, functions starting with <code>str</code> and a lower case letter are reserved by the standard for future directions. From <code>C11 7.1.3 Reserved identifiers</code>:</p> <blockquote> <p>Each header declares or defines all identifiers listed in its associated sub-clause, and <em>optionally declares or defines identifiers listed in its associated future library directions sub-clause.</em>*</p> </blockquote> <p>The future directions for <code>string.h</code> can be found in <code>C11 7.31.13 String handling &lt;string.h&gt;</code>:</p> <blockquote> <p>Function names that begin with <code>str</code>, <code>mem</code>, or <code>wcs</code> and a lowercase letter may be added to the declarations in the <code>&lt;string.h&gt;</code> header.</p> </blockquote> <p>So you should probably call it something else if you want to be safe.</p> <hr /> <p><sup>(b)</sup> The change would basically be replacing <code>if (d == NULL) return NULL;</code> with:</p> <pre><code>if (d == NULL) { errno = ENOMEM; return NULL; } </code></pre> <hr /> <p><sup>(c)</sup> Note that I use <code>strcpy</code> for that since that clearly shows the intent. In some implementations, it may be faster (since you already know the length) to use <code>memcpy</code>, as they may allow for transferring the data in larger chunks, or in parallel. Or it may not :-) Optimisation mantra #1: &quot;measure, don't guess&quot;.</p> <p>In any case, should you decide to go that route, you would do something like:</p> <pre><code>char *strdup(const char *src) { size_t len = strlen(src) + 1; // String plus '\0' char *dst = malloc(len); // Allocate space if (dst == NULL) return NULL; // No memory memcpy (dst, src, len); // Copy the block return dst; // Return the new string } </code></pre>
<p>The strdup() function is a shorthand for string duplicate, it takes in a parameter as a string constant or a string literal and allocates just enough space for the string and writes the corresponding characters in the space allocated and finally returns the address of the allocated space to the calling routine.</p>
31,492
<p>Given the following HTML:</p> <pre><code>&lt;select name="my_dropdown" id="my_dropdown"&gt; &lt;option value="1"&gt;displayed text 1&lt;/option&gt; &lt;/select&gt; </code></pre> <p>How do I grab the string "displayed text 1" using Javascript/the DOM?</p>
<pre><code>var sel = document.getElementById("my_dropdown"); //get the selected option var selectedText = sel.options[sel.selectedIndex].text; //or get the first option var optionText = sel.options[0].text; //or get the option with value="1" for(var i=0; i&lt;sel.options.length; i++){ if(sel.options[i].value == "1"){ var valueIsOneText = sel.options[i].text; } } </code></pre>
<p>If you were using <a href="http://www.prototypejs.org" rel="nofollow noreferrer">Prototype</a>, you could get at it like this:</p> <pre><code>$$('#my_dropdown option[value=1]').each( function(elem){ alert(elem.text); }); </code></pre> <p>The above is using a CSS selector that says find all <strong>option</strong> tags with <strong>value="1"</strong> that are inside the element that has <strong>id="my_dropdown"</strong>.</p>
23,287
<p>Is it possible to send messages from a PHP script to the console in Eclipse? Has anyone attempted this already? I'm not very familiar with how the console works, so I'm not sure if there is a standardized method for communicating with it.</p>
<p>If you look at...</p> <p>Main Menu -> Run -> External Tools -> Open External Tools Dialog.</p> <p>In there I have set up PHP Codesniffer with the following...</p> <ul> <li>Name : Code Sniffer</li> <li>Location : /usr/bin/phpcs</li> <li>Working Directory : ${workspace_loc}</li> <li>Arguments : --standard=${resource_loc}</li> </ul> <p>That runs the codesniffer as an external tool and all the messages it returns appear in the console. Once you have set it up, click the down arrow and choose "Code Sniffer" and then anything the external program (in this case codesniffer) outputs will be in the Eclipse console.</p> <p>If you set it up like this...</p> <ul> <li>Name : PHP</li> <li>Location : /usr/bin/phpcs</li> <li>Working Directory : ${workspace_loc}</li> <li>Arguments : ${workspace_loc}${resource_path}</li> </ul> <p>It will just run php in CLI mode and if you run it with Wilco's code (above) you will get.</p> <pre><code>Hello World </code></pre> <p>In the terminal.</p> <p>Hope that helps.</p>
<p>All output from an Eclipse external tool launch goes to the console by default, so if you execute a PHP script using an external tool launcher any output from the script will go to the console.</p> <p>For example:</p> <pre><code>&lt;?php echo "Hello World\n"; ?&gt; </code></pre> <p>Will send "Hello World" to the console.</p>
48,816
<p>I want to use a specific foreign language font for a Blackberry application. How is such a font created and loaded onto the Blackberry device?</p> <p>For example: ਪੰਜਾਬੀ </p>
<p>A quick google search shows that the same thing has been asked at <a href="http://www.blackberryforums.com/developer-forum/100107-using-custom-fonts.html" rel="nofollow noreferrer">blackberry forums</a>.</p> <p>The solution they came up with is a class for loading the font from a <a href="http://www.fileinfo.net/extension/fnt" rel="nofollow noreferrer">fnt file</a>.</p> <p>There are <a href="http://www.google.com/search?hl=en&amp;q=free+.fnt+editor&amp;btnG=Search" rel="nofollow noreferrer">programs available</a> to import and edit fnt files.</p>
<p>A quick google search shows that the same thing has been asked at <a href="http://www.blackberryforums.com/developer-forum/100107-using-custom-fonts.html" rel="nofollow noreferrer">blackberry forums</a>.</p> <p>The solution they came up with is a class for loading the font from a <a href="http://www.fileinfo.net/extension/fnt" rel="nofollow noreferrer">fnt file</a>.</p> <p>There are <a href="http://www.google.com/search?hl=en&amp;q=free+.fnt+editor&amp;btnG=Search" rel="nofollow noreferrer">programs available</a> to import and edit fnt files.</p>
9,887
<p>I'm creating a plugin to a software that skins the form I created. However, the button are not skin based on them and a standard gray button is shown. Asking on the software forum pointed me that .NET forms control are owner-draw and therefor my button won't redraw with the correct style instead of creating a non ownerdraw button.</p> <p>All controls in the system.windows.forms namespace seem to be ownerdraw.</p> <p>So how can I create a standar C++ PUSHBUTTON in .NET?</p> <p>Currently codding in C# if that helps.</p> <p>Thx</p>
<p>The controls in Windows.Forms are not owner-drawn, but rather system-drawn. This is how Windows paints them by default, be it a Button, TextBox or what else. You can override the drawing either by specifying that the control should be owner-drawn (that is: you are responsible for drawing it) - some controls support that, a couple of them even with a finer granularity (see ListView), or you can override the painting completely in OnPaint event of any Control descendant.</p> <p>Your question is rather confusing - as I understand the buttons you create in your plug-in are not skinned. Obviously what you need is to tell this skinning framework to paint these buttons. There probably is or should be some component that you drop onto the plug-in form or method you call that will inject the skinning painting routines into your plug-in. </p>
<p>Have you tried setting the <code>FlatStyle</code> to another value, such as <code>Flat</code> or <code>Popup</code>, just to see if that stops it being skinned?</p> <p>also setting <code>Flaststyle = Standard</code> (as opposed to system) might solve your problem</p>
45,113
<p>Is there a way to find a node matched on part of a value.</p> <p>If I have the following:</p> <pre><code>&lt;competition id="100" name="Barclays Premier League"/&gt; &lt;competition id="101" name="CocaCola Championship" /&gt; &lt;competition id="102" name="CocaCola League 1" /&gt; </code></pre> <p>Given the string "Premier League" or even "Prem", how would I match the correct node and get id 100.</p> <p>I have managed this using for-each and contains, but this is very inefficient and does not work fast enough for our requirements.</p>
<p>String handling is not something XSLT is amazing at but there are a few options.</p> <p>In this case you might try:</p> <pre><code>//competition[contains(@name,'Prem')] </code></pre> <p>see <a href="http://www.w3schools.com/Xpath/xpath_functions.asp#string" rel="noreferrer">here</a> for more options and details</p>
<p>There is also a "matches" function, which uses regular expressions, but this is only available in XSL 2.0.</p>
42,825
<p>I'm trying to make a function that has a list of lists, it multiplies the sum of the inner list with the outer list. So far i can sum a list, i've made a function sumlist([1..n],X) that will return X = (result). But i cannot get another function to usefully work with that function, i've tried both is and = to no avail.</p>
<p>Is this what you mean?</p> <pre><code>prodsumlist([], 1). prodsumlist([Head | Tail], Result) :- sumlist(Head, Sum_Of_Head), prodsumlist(Tail, ProdSum_Of_Tail), Result is Sum_Of_Head * ProdSum_Of_Tail. </code></pre> <p>where <code>sumlist/2</code> is a SWI-Prolog built-in.</p> <p>Usage example:</p> <pre><code>?- prodsumlist([[1, 2], [3], [-4]], Result). Result = -36. </code></pre>
<p>Here is a rewrite of <a href="https://stackoverflow.com/questions/349896/passing-results-in-prolog/353572#353572">Kaarel's answer</a> (that's the intention anyway!) but <a href="http://www.cs.mu.oz.au/255/last_semester/last_semester/prolog_course/md5/md5_accumulators.html" rel="nofollow noreferrer">tail-recursive</a>.</p> <pre><code>prodsumlist(List, Result) :- xprodsumlist(List,1,Result). xprodsumlist([],R,R). xprodsumlist([Head|Rest],Sofar,Result) :- sumlist(Head, Sum_Of_Head), NewSofar is Sofar * Sum_Of_Head, xprodsumlist(Rest, NewSofar, Result). </code></pre>
45,532
<p>I have an Access database in which I drop the table and then create the table afresh. However, I need to be able to test for the table in case the table gets dropped but not created (i.e. when someone stops the DTS package just after it starts -roll-eyes- ). If I were doing this in the SQL database I would just do:</p> <pre><code>IF (EXISTS (SELECT * FROM sysobjects WHERE name = 'Table-Name-to-look-for')) BEGIN drop table 'Table-Name-to-look-for' END </code></pre> <p>But how do I do that for an Access database?</p> <p>Optional answer: is there a way to have the DTS package ignore the error and just go to the next step rather than checking to see if it exists?</p> <p>SQL Server 2000</p>
<blockquote> <p>I would reccomend sticking to what you know - PHP is more than capable.</p> </blockquote> <p>That's true of course, but:</p> <blockquote> <p>I don't mind, and I would even like to use this as an excuse, learning some new thing like Python or Ruby.</p> </blockquote> <p>Then writing a browser game is an excellent opportunity to do this. Learning something new is never wrong and learning an alternative to PHP can never hurt (<a href="http://www.codinghorror.com/blog/archives/001119.html" rel="nofollow noreferrer">eh, Jeff?</a>). While neither Ruby on Rails nor Django are especially useful for writing games, they're still great. We had to write a small browser game in a matter of weeks for a project once and Rails worked charms. On the other hand, all successful browser games have enormous work loads and if you want to scale well you either have to get good hardware and load balancing or you need a non-interpreted framework (sorry, guys!).</p>
<p>I would reccomend sticking to what you know - PHP is more than capable.</p> <p>I used to play a game called <a href="http://www.hyperiums.com/" rel="nofollow noreferrer">Hyperiums</a> - a text based browser game like yours - which is created using Java (it's web-based quivalent is JSP?) and servlets. It works fairly well (it has had downtime issues but those were more related to it's running on a pretty crap server).</p> <p>As for which framework to use - why not create your own? Spend a good amount of time pre-coding deciding how you're going to handle various things - such as langauge support: you could use a phrase system or seperate langauge-specific templates. Third party frameworks are probably better tested than one you make but they're not created for a specific purpose, they're created for a wide range of purposes.</p>
4,564
<p>Is it possible to change how <kbd>Ctrl</kbd> + <kbd>Tab</kbd> and <kbd>Shift</kbd> + <kbd>Ctrl</kbd> + <kbd>Tab</kbd> work in Visual Studio? I have disabled the popup navigator window, because I only want to switch between items in the tab control. My problem is the inconsistency of what switching to the next and previous document do.</p> <p>Every other program that uses a tab control for open document I have seen uses <kbd>Ctrl</kbd> + <kbd>Tab</kbd> to move from left to right and <kbd>Shift</kbd> + <kbd>Ctrl</kbd> + <kbd>Tab</kbd> to go right to left. Visual Studio breaks this with its jump to the last tab selected. You can never know what document you will end up on, and it is never the same way twice. </p> <p>It is very counterintuitive. Is this a subtle way to encourage everyone to only ever have two document open at once?</p> <hr> <p>Let's say I have a few files open. I am working in one, and I need to see what is in the next tab to the right. In every other single application on the face of the Earth, <kbd>Ctrl</kbd> + <kbd>Tab</kbd> will get me there. But in Visual Studio, I have no idea which of the other tabs it will take me to. If I only ever have two documents open, this works great. As soon as you go to three or more, all bets are off as to what tab Visual Studio has decided to send you to. </p> <p>The problem with this is that I shouldn't have to think about the tool, it should fade into the background, and I should be thinking about the task. The current tab behavior keeps pulling me out of the task and makes me have to pay attention to the tool.</p>
<p>In Visual Studio 2015 (as well as previous versions of VS, but you must install <a href="https://visualstudiogallery.msdn.microsoft.com/dbcb8670-889e-4a54-a226-a48a15e4cace">Productivity Power Tools</a> if you're using VS2013 or below), there are two new commands in Visual Studio:</p> <p><em>Window.NextTab</em> and <em>Window.PreviousTab</em> </p> <p>Just go remap them from <kbd>Ctrl</kbd>+<kbd>Alt</kbd>+<kbd>PageUp</kbd>/<kbd>Ctrl</kbd>+<kbd>Alt</kbd>+<kbd>PageDown</kbd> to <kbd>Ctrl</kbd>+<kbd>Tab</kbd>/<kbd>Ctrl</kbd>+<kbd>Shift</kbd>+<kbd>Tab</kbd> in:</p> <p>Menu <em>Tools</em> -> <em>Options</em> -> <em>Environment</em> -> <em>Keyboard</em></p> <p>Note: In earlier versions such as Visual Studio 2010, Window.NextTab and Window.PreviousTab were named <em>Window.NextDocumentWellTab</em> and <em>Window.PreviousDocumentWellTab</em>.</p>
<p>I don't use Visual Studio (<em>yes, really, I don't use it</em>), but <a href="http://en.wikipedia.org/wiki/AutoHotkey" rel="nofollow noreferrer">AutoHotkey</a> can remap any hotkey globally or in a particular application:</p> <pre><code>#IfWinActive Microsoft Excel (application specific remapping) ; Printing area in Excel (@ Ctrl+Alt+A) ^!a:: Send !ade return #IfWinActive $f4:: ; Closes the active window (make double tapping F4 works like ALT+F4) if f4_cnt &gt; 0 { f4_cnt += 1 return } f4_cnt = 1 SetTimer, f4_Handler, 250 return f4_Handler: SetTimer, f4_Handler, off if (f4_cnt &gt;= 2) ; Pressed more than two times { SendInput !{f4} } else { ; Resend f4 to the application Send {f4} } f4_cnt = 0 return </code></pre> <p>These are two remappings of my main AutoHotKey script. I think it's an excellent tool for this type of tasks.</p>
4,137
<p>As many of us know (and many, many more don't), C++ is currently undergoing final drafting for the next revision of the International Standard, expected to be published in about 2 years. Drafts and papers are currently available from the <a href="http://open-std.org/JTC1/SC22/WG21/" rel="noreferrer">committee website</a>. All sorts of new features are being added, the biggest being concepts and lambdas. There is a very comprehensive <a href="http://en.wikipedia.org/wiki/C++0x" rel="noreferrer">Wikipedia article</a> with many of the new features. GCC 4.3 and later implement <a href="http://gcc.gnu.org/projects/cxx0x.html" rel="noreferrer">some C++0x features</a>.</p> <p>As far as new features go, I really like type traits (and the appropriate concepts), but my definite leader is variadic templates. Until 0x, long template lists have involved Boost Preprocessor usually, and are very unpleasant to write. This makes things a lot easier and allows C++0x templates to be treated like a perfectly functional language using variadic templates. I've already written some very cool code with them already, and I can't wait to use them more often!</p> <p>So what features are you most eagerly anticipating?</p>
<p><strong>auto</strong> keyword for variable type inferencing</p>
<p>for the moment I have liked much of C++0x that I have played with:</p> <ul> <li>nullptr</li> <li>static_assert</li> <li>lambdas</li> <li>shared_ptr and weak_ptr </li> <li>unique_ptr</li> <li>decltype and auto</li> </ul> <p>I havent tried <code>&lt;regexp&gt;</code>... I thought it was a huge idea... but I didn't even take the time to look at it.</p>
16,669
<p>I've one plist file and I want to parse it and copy it's content into NSArray,and code that I am using for that is. </p> <pre><code>NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES); NSString *documentsPath = [paths objectAtIndex:0]; NSString *fooPath = [documentsPath stringByAppendingPathComponent:@"myfirstplist.plist"]; NSLog(fooPath); self.myArray = [[NSArray arrayWithContentsOfFile:fooPath] retain]; NSLog(@"%@",myArray); </code></pre> <p>Now problem is very weird, sometime when I print myArray content it prints file data, and sometime it doesn't.</p> <p>I am facing a same problem even when I use URL as my path.</p> <pre><code>self.myArray = [[NSArray arrayWithContentsOfURL:URlPath] retain]; </code></pre> <p>what would be the reason?</p> <p>Thanks in advance.</p>
<p>Depending on how you generated the .plist initially, you may run into problems if you try and read it back in as an array. The safest way to read a plist is using the NSPropertyListSerialization class: <a href="https://developer.apple.com/iphone/library/documentation/Cocoa/Reference/Foundation/Classes/NSPropertyListSerialization_Class/NSPropertyListSerialization_Class.pdf" rel="nofollow noreferrer">Apple Doc.</a></p>
<p>Are you generating the file with <a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSArray_Class/Reference/Reference.html#//apple_ref/occ/instm/NSArray/writeToFile:atomically:" rel="nofollow noreferrer">writeToFile:atomically</a>: ? do you check that this returns true?</p>
42,762
<p>What would be the best way to avoid SQL injection on the C#.net platform.</p> <p>Please post an C# implementation if you have any.</p>
<p>There's no algorithm needed - just don't use string concatenation to build SQL statements. Use the SqlCommand.Parameters collection instead. This does all the necessary escaping of values (such as replacing <code>'</code> with <code>''</code>) and ensures the command will be safe because somebody else (i.e. Microsoft) has done all the testing.</p> <p>e.g. calling a stored procedure:</p> <pre><code>using (var connection = new SqlConnection("...")) using (var command = new SqlCommand("MySprocName", connection)) { command.CommandType = CommandType.StoredProcedure; command.Parameters.AddWithValue("@Param1", param1Value); return command.ExecuteReader(); } </code></pre> <p>This technique also works for inline SQL statements, e.g.</p> <pre><code>var sql = "SELECT * FROM MyTable WHERE MyColumn = @Param1"; using (var connection = new SqlConnection("...")) using (var command = new SqlCommand(sql, connection)) { command.Parameters.AddWithValue("@Param1", param1Value); return command.ExecuteReader(); } </code></pre>
<p>There's no algorithm needed - just don't use string concatenation to build SQL statements. Use the SqlCommand.Parameters collection instead. This does all the necessary escaping of values (such as replacing <code>'</code> with <code>''</code>) and ensures the command will be safe because somebody else (i.e. Microsoft) has done all the testing.</p> <p>e.g. calling a stored procedure:</p> <pre><code>using (var connection = new SqlConnection("...")) using (var command = new SqlCommand("MySprocName", connection)) { command.CommandType = CommandType.StoredProcedure; command.Parameters.AddWithValue("@Param1", param1Value); return command.ExecuteReader(); } </code></pre> <p>This technique also works for inline SQL statements, e.g.</p> <pre><code>var sql = "SELECT * FROM MyTable WHERE MyColumn = @Param1"; using (var connection = new SqlConnection("...")) using (var command = new SqlCommand(sql, connection)) { command.Parameters.AddWithValue("@Param1", param1Value); return command.ExecuteReader(); } </code></pre>
31,029
<p>I normally in my projects use such these code:</p> <pre><code>If user.IsInRole("Admin") Then deleteButton.Visible = True else deleteButton.Visible = False </code></pre> <p>But I want to control roles, which can see this button in database.</p> <p>For this purpose how should database design be?</p> <p>Thanks.</p>
<p>Make the design whatever you want to be, but in ASP.NET side implement your own MembershipProvider. This will translate your DB design into users/roles that .NET can use. After that you can use it as usually - with <code>user.isInRole("Admin")</code> :)</p>
<p>Assuming you're using .NET, one way to do this is to implement your own Role and Membership Providers. Then, you could add functionality by implementing an interface that contained the items you wanted (I've just knocked this sample up off the top of my head, so I apologize if it seems a bit rough):</p> <pre><code>public interface ICustomRole { bool IsInRole(string userName, object[] params roles); } public class MyCustomRole : RoleProvider, ICustomRole { public IsInRole(MembershipUser user, object[] params roles) { if (roles == null || roles.Length == 0) throw new ArgumentException("roles"); // Put your logic here for accessing the roles } } </code></pre> <p>Then, in your code you would do this:</p> <pre><code>bool isValid = ((ICustomRole)Roles.Provider).IsInRole( User, new[] { "Admin", "Moderator", "Validator" }); </code></pre>
45,395
<p>I have a Winform with a BackgroundWorker. The BackgroundWorker, among other things, has to make an HTTP call to a page, fill out some data, submit the form, and retrieve the HTML that comes back after "clicking" the submit button. I've run into a number of roadblocks while doing this:</p> <ol> <li>Can't POST the data because the target webserver doesn't 405 support that method.</li> <li>Can't use a WebClient.UploadValues, again, because the webserver doesn't support POST.</li> <li>Can't use a WebBrowser control because BackgroundWorkers suck at COM Interop and an exception is thrown that says it must be in a STA thread (Single-Threaded Apartment)</li> <li>Can't run another seperate thread because the BW has to sit and wait for the result before it can continue (Can't, or at least I don't know a way to do this that won't crash)</li> <li>Can't change the ApartmentState of the thread because it's a BackgroundWorker and it throws if told to go to STA mode</li> </ol> <p>What should I do to resolve this?</p> <p>[Edit]: The app entrypoint is already tagged with the [STAThread] attribute.</p>
<p>Have you tried using <a href="http://msdn.microsoft.com/en-us/library/system.net.webclient.uploadvalues(VS.80).aspx" rel="nofollow noreferrer">WebClient.UploadValues</a> with the Method argument set to "GET" ?</p>
<p>Don't use a background worker?</p> <p>If you do that you can set the ApartmentState to what you want. Just remember to Invoke/BeginInvoke when pushing data back to any Form controls.</p>
45,647
<p>I have an Asp.Net 1.1 application that uses the following code to write out an image file to a pop up web page.</p> <pre><code> Response.ContentType="image/tiff" 'Only for Tif files Dim objStream As Object objStream = Server.CreateObject("ADODB.Stream") objStream.open() objStream.type = 1 objStream.loadfromfile(localfile) Response.BinaryWrite(objStream.read) </code></pre> <p>I'm testing this out with TIF files. The files are being displayed correctly in IE6 and Safari but in IE7 they are not displaying and nothing seems to be returning to the web page. Files with jpg, gif extensions are being displayed properly. What might be the problem here?</p>
<p>Well, it depends on your audience. But ideally, to support legacy browsers, you shouldn't assume they can handle a TIFF.</p> <p>At the very least, load the TIFF, select the first frame (page), do a DrawImage into a new bitmap, save the bitmap as JPG to a memory stream, and send that to Response.</p> <p>If you're not familiar with .NET's GDI+ image manipulation or that sounds hard, please see <a href="https://web.archive.org/web/20141230145656/http://bobpowell.net/faqmain.aspx" rel="nofollow noreferrer">https://web.archive.org/web/20141230145656/http://bobpowell.net/faqmain.aspx</a> for advice. Each one of these steps can be done with just a few lines of code. If you don't already know GDI+, it's worth learning for any web developer. That might make doing this 'the hard (but safe) way' worth it for the education alone. And if you already know how, it won't take but 1/2 hour.</p> <p>If you must display multipage TIFFs, and you want the user to control which pages to see, you'll have to create a user interface to set the page number. If you're trying to display multiple TIFFs per page, that might get non-trivial, so consider displaying all the tiff #1 pages on the first web page, or, allowing them to view subsequent tiff pages by linking to another web page with prev/next tiff page buttons. It should be a generic page that accepts the filename and current page numbers (prev/next buttons would point to itself with +/- one page number) as URL parameters.</p> <p>If you know you'll only be showing text documents instead of photographs, try sending single-frame GIFs instead of TIFFs to the browser for less Jpegginess on the text. But beforewarned - photos can look pretty bad a GIF.</p>
<p>Have you tried setting the <a href="http://www.ietf.org/rfc/rfc2183.txt" rel="nofollow noreferrer">Content-Disposition</a> to Inline?</p> <pre><code>Response.AppendHeader("Content-Disposition", "inline"); </code></pre>
36,794
<p>I am writing a Rails app that processes data into a graph (using Scruffy). I am wondering how can I render the graph to a blog/string and then send the blog/string directly to the the browser to be displayed (without saving it to a file)? Or do I need to render it, save it to a file, then display the saved image file in the browser? </p>
<p>I think you will be able to use <a href="http://www.railsbrain.com/api/rails-2.1.0/doc/index.html?a=M000271&amp;name=send_data" rel="nofollow noreferrer">send_data</a> for this purpose:</p> <pre><code>send_data data_string, :filename =&gt; 'icon.jpg', :type =&gt; 'image/jpeg', :disposition =&gt; 'inline' </code></pre> <p>If you put this in a controller action - say show on a picture controller, then all you need do is include the following in your view (assuming RESTful routes):</p> <pre><code>&lt;%= image_tag picture_path(@picture) %&gt; </code></pre>
<p>I wonder if sending direct to the browser is the best way? If there is the possibility that users will reload the page would this short circuit any cache possibilities? I ask because I really don't know.</p>
33,598
<p>I know of Rational Rose and we have got Rational Rose 6.</p> <p>But I am looking for some other tools which are more usable, which do not complain that they are not running in Windows 98/2000 (when installed and run in WinXP) and has got better features as compared to Rational Rose 6.</p>
<p>Check out <a href="http://www.sparxsystems.com.au/products/ea/index.html" rel="nofollow noreferrer">Enterprise Architect</a>. It's not expensive and does a lot of things well.</p>
<p>I did check out Enterprise Architect on SpareX's web site but could not find any reference stating that it handles reverse engineering or code generation for VB6.</p>
47,969
<p>On a Linux box, the common interface names look like eth0, eth1, etc. I know how to find at least one IP address using <code>gethostbyname</code> or similar functions, but I don't know any way to specify which named interface I want the IP address of. I could use ifconfig and parse the output, but shelling out for this information seems... inelegant.</p> <p>Is there a way to, say, enumerate all the interfaces and their IP addresses (and maybe MAC addresses) into a collection? Or at least something along the lines of <code>gethostbyinterface("eth0")</code>?</p>
<pre class="lang-c prettyprint-override"><code>// Originally from http://www.tlug.org.za/wiki/index.php/Obtaining_your_own_IP_address #include &lt;sys/types.h&gt; #include &lt;sys/socket.h&gt; #include &lt;sys/ioctl.h&gt; #include &lt;net/if.h&gt; #include &lt;netinet/in.h&gt; #include &lt;arpa/inet.h&gt; #include &lt;string.h&gt; #include &lt;stdio.h&gt; #include &lt;unistd.h&gt; /** * getIPv4() * * This function takes a network identifier such as "eth0" or "eth0:0" and * a pointer to a buffer of at least 16 bytes and then stores the IP of that * device gets stored in that buffer. * * it return 0 on success or -1 on failure. * * Author: Jaco Kroon &lt;jaco@kroon.co.za&gt; */ int getIPv4(const char * dev, char * ipv4) { struct ifreq ifc; int res; int sockfd = socket(AF_INET, SOCK_DGRAM, 0); if(sockfd &lt; 0) return -1; strcpy(ifc.ifr_name, dev); res = ioctl(sockfd, SIOCGIFADDR, &amp;ifc); close(sockfd); if(res &lt; 0) return -1; strcpy(ipv4, inet_ntoa(((struct sockaddr_in*)&amp;ifc.ifr_addr)-&gt;sin_addr)); return 0; } int main() { char ip[16]; if(getIPv4("eth0", ip) == 0) printf("IPv4: %s\n", ip); else printf("No IP\n"); return 0; } </code></pre> <p><strong>Update</strong>: Moved dead link to a comment (for posterity) (thanks @obayhan), and added syntax highlighting.</p>
<p><strong>edit:</strong> I saw you don't like shelling. Then you can look at how ifconfig does its job (it extracts at least some information from /proc).</p> <p>When you have interface name, you can do this (in your shell):</p> <pre><code>ifconfig eth0 | grep 'inet addr' | sed -e 's/:/ /' | awk '{print $3}' </code></pre> <p>To enumerate interfaces you can use this:</p> <pre><code>ifconfig | egrep '^[^ ]' | awk '{print $1}' </code></pre> <p>Combined:</p> <pre><code>for x in `ifconfig | egrep '^[^ ]' | awk '{print $1}'`; do echo -n "${x}" echo -n " " ifconfig "${x}" | grep 'inet addr' | sed -e 's/:/ /' | awk '{print $3}' done </code></pre>
32,404
<p>I have a table in a RDLC report which is utilized as a subreport, and the first column of this table is a static string. Does anyone know how I can determine if a row is the first in the table. I tried using "=First("My String")" but it didn't work.</p>
<p>Aggregate functions work with "Scope', referring to the paragraph scope in this MSDN article, might help...<br></p> <p><a href="http://msdn.microsoft.com/fr-fr/library/ms252112(VS.80).aspx" rel="nofollow noreferrer"><a href="http://msdn.microsoft.com/fr-fr/library/ms252112(VS.80).aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/fr-fr/library/ms252112(VS.80).aspx</a>"</a></p> <p>From what I understand you may have to define a scope or try =First("MyString", Nothing).</p>
<p>=IIF((RowNumber(Nothing) Mod &lt;>)=0)</p> <p>&lt;> Indicate No of Rows Which you want To Display</p>
12,880
<p>I'm printing a lot of draft parts so I don't care if they fall apart in my fingers, I just need the shape. I can scroll to the Tune menu on my Ender 3 Pro console and set the speed to 200% and it doubles the speed. But when I set the Print Speed setting to 100 instead of 50 mm/s in Cura, it doesn't save much time, even if I adjust the individual first layer speed, wall speed, top layer speed, etc. What is the difference?</p> <p>Ideally, I would like the first layer to print normally, and then print at 2x speed.</p>
<p>If you use a build surface such as PEI, acetone frosts your surface, leaving a white film appearance. If you have no additional surface on a glass or metal bed, it is incomplete cleaning. If incomplete cleaning, you could try isopropyl alcohol (IPA) immediately after acetone, followed immediately by a water based cleaner or DI/distilled water. (IPA dissolves acetone and water dissolves IPA. Once the film dries the next step may not work.)</p> <p>You can't clean off a frosted surface. The black surface of the hot bed in images of the CR-10S Pro appears to indicate that the steel bed has a build surface with a plastic material such as PEI. Reviews of the build surface being difficult to remove prints also implies a plastic build surface on the steel. Thus, it appears that the white film after cleaning with acetone is actually a frosted surface.</p> <p>If you use an Elmer's washable glue stick or one with PWP, it will form a barrier between your print and the build surface, that not only will protect your build surface, but will make it easier to clean your build surface with IPA or water based cleaners.</p>
<p>If you use a build surface such as PEI, acetone frosts your surface, leaving a white film appearance. If you have no additional surface on a glass or metal bed, it is incomplete cleaning. If incomplete cleaning, you could try isopropyl alcohol (IPA) immediately after acetone, followed immediately by a water based cleaner or DI/distilled water. (IPA dissolves acetone and water dissolves IPA. Once the film dries the next step may not work.)</p> <p>You can't clean off a frosted surface. The black surface of the hot bed in images of the CR-10S Pro appears to indicate that the steel bed has a build surface with a plastic material such as PEI. Reviews of the build surface being difficult to remove prints also implies a plastic build surface on the steel. Thus, it appears that the white film after cleaning with acetone is actually a frosted surface.</p> <p>If you use an Elmer's washable glue stick or one with PWP, it will form a barrier between your print and the build surface, that not only will protect your build surface, but will make it easier to clean your build surface with IPA or water based cleaners.</p>
1,872
<p>Is possible to insert a line break where the cursor is in Vim without entering into insert mode? Here's an example (<code>[x]</code> means cursor is on <code>x</code>):</p> <pre><code>if (some_condition) {[ ]return; } </code></pre> <p>Occasionally, I might want to enter some more code. So I'd press <kbd>i</kbd> to get into insert mode, press <kbd>Enter</kbd> to insert the line break and then delete the extra space. Next, I'd enter normal mode and position the cursor before the closing brace and then do the same thing to get it on its own line.</p> <p>I've been doing this a while, but there's surely a better way to do it?</p>
<p>For the example you've given, you could use <kbd>r</kbd><kbd>Enter</kbd> to replace a single character (the space) with Enter. Then, <kbd>f</kbd><kbd>space</kbd><kbd>.</kbd> to move forward to the next space and repeat the last command.</p> <p>Depending on your autoindent settings, the above may or may not indent the return statement properly. If not, then use <kbd>s</kbd><kbd>Enter</kbd><kbd>Tab</kbd><kbd>Esc</kbd> instead to replace the space with a newline, indent the line, and exit insert mode. You would have to replace the second space with a different command so you couldn't use '.' in this case.</p>
<p>This mapping will break up any one-line function you have. Simply put your cursor on the line and hit 'g' in normal mode:</p> <pre><code>:map g ^f{malr&lt;CR&gt;`a%hr&lt;CR&gt;`a </code></pre> <p>This assumes that you have a space after the opening brace and a space before the closing brace. See if that works for you.</p>
29,384
<p>I've got a function that runs a user generated Regex. However, if the user enters a regex that won't run then it stops and falls over. I've tried wrapping the line in a Try/Catch block but alas nothing happens.</p> <p>If it helps, I'm running jQuery but the code below does not have it as I'm guessing that it's a little more fundamental than that.</p> <p>Edit: Yes, I know that I am not escaping the "[", that's intentional and the point of the question. I'm accepting user input and I want to find a way to catch this sort of problem without the application falling flat on it's face.</p> <pre><code>&lt;!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"&gt; &lt;html&gt; &lt;head&gt; &lt;title&gt;Regex&lt;/title&gt; &lt;script type="text/javascript" charset="utf-8"&gt; var grep = new RegExp('gr['); try { var results = grep.exec('bob went to town'); } catch (e) { //Do nothing? } alert('If you can see this then the script kept going'); &lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;/body&gt; &lt;/html&gt; </code></pre>
<p>Try this the new RegExp is throwing the exception</p> <p> Regex</p> <pre><code> &lt;script type="text/javascript" charset="utf-8"&gt; var grep; try { grep = new RegExp("gr["); } catch(e) { alert(e); } try { var results = grep.exec('bob went to town'); } catch (e) { //Do nothing? } alert('If you can see this then the script kept going'); &lt;/script&gt; </code></pre> <p> </p> <p> </p>
<p>One option is to validate the user-generated expressions. That is; escape characters that you know will stall your script.</p>
14,677
<p>I want to show a large amount of data in a dataset, 100,000 records approx 10 columns, this consumes a large amount of ram 700MB. I have also tried using paging which reduces this by about 15-20% but I don't really like the Previous/Next buttons involved when using paging. I'm not writing the data to disk at present, should I be? If so what is the most common method? The data isn't to be stored forever just whilst it is being viewed, then a new query may be run and a nother 70,000 records could be viewed. What is the best way to proceed?</p> <p>Thanks for the advice.</p>
<p>The reality is that the end-user rarely needs to see the totality of their dataset, so I would use which method you like for presenting the data (listview) and build a custom pager so that the dataset is only fed with the results of the number of records desired. Otherwise, each page load would result in re-calling the dataset. </p> <p>The XML method to a temp file or utilizing a temp table created through a stored proc are alternatives but you still must sift and present the data.</p>
<p>I would suggest memory mapped files...not sure if .NET includes support for it yet.</p>
30,862
<p>I have a WCF service from which I want to return a DataTable. I know that this is often a highly-debated topic, as far as whether or not returning DataTables is a good practice. Let's put that aside for a moment.</p> <p>When I create a DataTable from scratch, as below, there are no problems whatsoever. The table is created, populated, and returned to the client, and all is well:</p> <pre><code>[DataContract] public DataTable GetTbl() { DataTable tbl = new DataTable("testTbl"); for(int i=0;i&lt;100;i++) { tbl.Columns.Add(i); tbl.Rows.Add(new string[]{"testValue"}); } return tbl; } </code></pre> <p>However, as soon as I go out and hit the database to create the table, as below, I get a CommunicationException "The underlying connection was closed: The connection was closed unexpectedly."</p> <pre><code>[DataContract] public DataTable GetTbl() { DataTable tbl = new DataTable("testTbl"); //Populate table with SQL query return tbl; } </code></pre> <p>The table is being populated correctly on the server side. It is significantly smaller than the test table that I looped through and returned, and the query is small and fast - there is no issue here with timeouts or large data transfer. The same exact functions and DataContracts/ServiceContracts/BehaviorContracts are being used.</p> <p>Why would the way that the table is being populated have any bearing on the table returning successfully?</p>
<p>For anyone having similar problems, I have solved my issue. It was several-fold.</p> <ul> <li>As Darren suggested and Paul backed up, the Max..Size properties in the configuration needed to be enlarged. The SvcTraceViewer utility helped in determining this, but it still does not always give the most helpful error messages. </li> <li>It also appears that when the Service Reference is updated on the client side, the configuration will sometimes not update properly (e.g. Changing config values on the server will not always properly update on the client. I had to go in and change the Max..Size properties multiple times on both the client and server sides in the course of my debugging)</li> <li><p>For a DataTable to be serializable, it needs to be given a name. The default constructor does not give the table a name, so:</p> <pre><code>return new DataTable(); </code></pre> <p>will not be serializable, while:</p> <pre><code>return new DataTable("someName"); </code></pre> <p>will name the table whatever is passed as the parameter. </p> <p>Note that a table can be given a name at any time by assigning a string to the <code>TableName</code> property of the DataTable.</p> <pre><code>var table = new DataTable(); table.TableName = "someName"; </code></pre></li> </ul> <p>Hopefully that will help someone.</p>
<p>I think Darren is most likely correct - the default values provided for WCF are laughably small and if you bump into them you end up with errors that can be difficult to track down. They seem to appear as soon as you attempt to do anything beyond a simple test case. I wasted more time than I'd like to admit debugging problems that turned out to be related to the various configuration (size) settings on both the client and server. I think I ended up modifying almost all of them, ex. MaxBufferPoolSize, MaxBufferSize, MaxConnections, MaxReceivedMessageSize, etc. </p> <p>Having said that, the SvcTraceViewer utility also mentioned is great. I did run into a few cases where it wasn't as helpful as I would have liked, but overall it's a nice tool for analyzing the communications flow and errors.</p>
3,380
<p>I've been reading a lot lately about the next release of Java possibly supporting <a href="http://en.wikipedia.org/wiki/Closure_%28computer_science%29" rel="noreferrer">closures</a>. I feel like I have a pretty firm grasp on what closures are, but I can't think of a solid example of how they would make an Object-Oriented language "better". Can anyone give me a specific use-case where a closure would be needed (or even preferred)?</p>
<p>As a Lisp programmer I would wish that the Java community understands the following difference: <strong>functions as objects vs. closures</strong>.</p> <p>a) <strong>functions can be named or anonymous</strong>. But they can also be objects of themselves. This allows functions to be passed around as arguments, returned from functions or stored in data structures. This means that functions are first class objects in a programming language.</p> <p>Anonymous functions don't add much to the language, they just allow you to write functions in a shorter way.</p> <p>b) <strong>A closure is a function plus a binding environment</strong>. Closures can be passed <em>downwards</em> (as parameters) or returned <em>upwards</em> (as return values). This allows the function to refer to variables of its environment, even if the surrounding code is no longer active.</p> <p>If you have <strong>a)</strong> in some language, then the question comes up what to do about <strong>b)</strong>? There are languages that have <strong>a)</strong>, but not <strong>b)</strong>. In the functional programming world <strong>a)</strong> (functions) and <strong>b</strong> (functions as closures) is nowadays the norm. Smalltalk had <strong>a)</strong> (<em>blocks</em> are anonymous functions) for a long time, but then some dialects of Smalltalk added support for <strong>b)</strong> (blocks as closures).</p> <p>You can imagine that you get a slightly different programming model, if you add functions and closures to the language. </p> <p>From a pragmatic view, the anonymous function adds some short notation, where you pass or invoke functions. That can be a good thing.</p> <p>The closure (function plus binding) allows you for example to create a function that has access to some variables (for example to a counter value). Now you can store that function in an object, access it and invoke it. The context for the function object is now not only the objects it has access to, but also the variables it has access to via bindings. This is also useful, but you can see that variable bindings vs. access to object variables now is an issue: when should be something a <em>lexical</em> variable (that can be accessed in a closure) and when should it be a variable of some object (a <em>slot</em>). When should something be a closure or an object? You can use both in the similar ways. A usual programming exercise for students learning Scheme (a Lisp dialect) is to write a simple object system using closures.</p> <p>The result is a more complicated programming language and a more complicated runtime model. Too complicated?</p>
<p>Not only that benjismith, but I love how you can just do...</p> <p>myArray.sort{ it.myProperty }</p> <p>You only need the more detailed comparator you've shown when the natural language comparison of the property doesn't suit your needs.</p> <p>I absolutely love this feature.</p>
7,299
<p>I am using a JSP bean and when I do an assignment to a new object, it gets over-written on a submit to the previous object.</p> <pre><code>&lt;jsp:useBean id="base" class="com.example.StandardBase" scope="session" /&gt; ... //base object id = 396 base = new Base() //base object id = 1000 </code></pre> <p>and on a resubmit of the page I get</p> <pre><code>&lt;jsp:useBean id="base" class="com.example.StandardBase" scope="session" /&gt; //base object id = 396 </code></pre> <p>Is there a way to tell JSP to do a new assignment?</p>
<p>I'm not completely sure, but I think <code>base = new Base()</code> does not update the reference stored in the session scope. Therefore, the bean you created with the initial <code>&lt;jsp:useBean/&gt;</code> is still around while the one you create manually, and then updated, isn't.</p> <p>Get rid of <code>base = new Base()</code> and you should be fine.</p> <p>If you insist upon updating it, you use <a href="http://java.sun.com/j2ee/1.4/docs/api/javax/servlet/http/HttpSession.html#setAttribute(java.lang.String,%20java.lang.Object)" rel="nofollow noreferrer"><code>HttpSession.setAttribute()</code></a>. Like so:</p> <pre><code>session.setAttribute("bean", bean); </code></pre> <p>I believe the variable <code>session</code> is automatically created and initialized for you by the JSP engine.</p>
<p>would changing scope from session to request fix this for you?</p>
38,384
<p>I've played with CVS a little bit and am not the most familiar with all of its capabilities, but a huge annoyance for me is trying to add new directories that contain more directories in them. Running "<code>cvs add</code>" only adds the contents of the current directory, and using "<code>cvs import</code>" didn't look like the right thing either since it's still all code I'm producing (this howto claimed import is for <a href="http://www.thathost.com/wincvs-howto/cvsdoc/cvs_16.html#SEC136" rel="noreferrer">3rd party sources</a>)</p> <p>Do you guys know any way to recursively add everything in a given directory to the current CVS project (or if SVN or git makes this notably easier)?</p>
<p>I found this worked pretty effectively:</p> <p>First, add all the directories, but not any named "CVS":</p> <pre><code>find . -type d \! -name CVS -exec cvs add '{}' \; </code></pre> <p>Then add all the files, excluding anything in a CVS directory:</p> <pre><code>find . \( -type d -name CVS -prune \) -o \( -type f -exec cvs add '{}' \; \) </code></pre> <p>Now, if anyone has a cure for the embarrassment of using CVS in this day and age...</p>
<p>SVN definitely makes this trivial task, using a GUI like Tortoise is even easier, however.</p> <p>This might be a good place to start: <a href="http://www-mrsrl.stanford.edu/~brian/cvstutorial/" rel="nofollow noreferrer">http://www-mrsrl.stanford.edu/~brian/cvstutorial/</a></p>
2,704
<p>I'm looking for a plugin-based application framework that is comparable to the Eclipse Plugin Framework, which to my simple mind consists of:</p> <ol> <li>a core <strong>plugin management framework</strong> (Equinox / OSGI), which provides the ability to declare extension endpoints and then discover and load plugins that service those endpoints. (this is different than Dependency Injection, but admittedly the difference is subtle - configuration is highly de-centralized, there are versioning concerns, it might involve an online plugin repository, and most importantly to me, it should be easy for the <strong>user</strong> to add plugins without needing to know anything about the underlying architecture / config files)</li> <li>many layers of plugins that provide a <strong>basic workbench shell</strong> with concurrency support, commands, preference sheets, menus, toolbars, key bindings, etc. </li> </ol> <p>That is just scratching the surface of the RCP, which itself is meant to serve as the foundation of your application, which you build by writing / assembling even <strong>more</strong> plugins.</p> <hr> <p>Here's what I've gleaned from the internet in the past couple of days...</p> <p>As far as I can tell, there is nothing in the .NET world that remotely approaches the robustness and maturity of the Eclipse RCP for Java but there are several contenders that do either #1 or #2 pretty well.</p> <p>(I should also mention that I have not made a final decision on WinForms vs WPF, so I'm also trying to understand the level of UI coupling in any candidate framework. I'm also wondering about platform coupling and source code licensing)</p> <p>I must say that the open-source stuff is generally less-documented but easier to understand, while the MS stuff typically has more documentation but is less accessible, so that with many of the MS technologies, I'm left wondering what they actually do, in a practical sense. </p> <p>These are the libraries I have found:</p> <h2>SharpDevelop</h2> <p>The first thing I looked at was SharpDevelop, which does both #1 and also #2 in a basic way (no insult to SharpDevelop, which is admirable - I just mean <em>more basic</em> than Eclipse RCP). However, SharpDevelop is an application more than a framework, and there are basic assumptions and limitations there (i.e. being somewhat coupled to WinForms). Still, there are some articles on CodeProject explaining how to use it as the foundation for an application. </p> <h2>System.Addins</h2> <p>It appears that System.Addins is meant to provide a robust add-in loading framework, with some sophisticated options for loading assemblies with varying levels of trusts and even running the out of process. It appears to be primarily code-based, and pretty code-heavy, with lots of assemblies that serve to insulate against versioning issues., using Guidance Automation to generate a good deal of code. </p> <p>So far I haven't found many System.AddIns articles that illustrate how it could be used to build something like an Eclipse RCP, and many people seem to be wringing their hands about its complexity.</p> <h2>Mono.Addins</h2> <p>It appears that Mono.Addins was influenced by System.Addins, SharpDevelop, and MonoDevelop. It seems to provide the basics from System.Addins, with less sophisticated options for plugin loading, but more simplicity, with attribute-based registration, XML manifests, and the infrastructure for online plugin repositories. </p> <p>It has a pretty good FAQ and documentation, as well as a fairly robust set of examples that really help paint a picture of how to develop an architecture like that of SharpDevelop or Eclipse. The examples use GTK for UI, but the framework itself is not coupled to GTK. So it appears to do #1 (add-in loading) pretty well and points the way to #2 (workbench framework). It appears that Mono.Addins was derived from MonoDevelop, but I haven't actually looked at whether MonoDevelop provides a good core workbench framework.</p> <h2>Managed Extensibility Framework</h2> <p>This is what everyone's talking about at the moment, and it's slowly getting clearer what it does, but I'm still pretty fuzzy, even after reading several posts on SO. The official word is that it "can live side-by-side" with System.Addins. However, it doesn't reference it and it appears to reproduce some of its functionality. It seems to me, then, that it is a simpler, more accessible alternative to System.Addins.</p> <p>It appears to be more like Mono.Addins in that it provides attribute-based wiring. It provides "catalogs" that can be attribute-based or directory-based. It does not seem to provide any XML or manifest-based wiring. So far I haven't found much documentation and the examples seem to be kind of "magical" and more reminiscent of attribute-based DI, despite the clarifications that MEF is not a DI container.</p> <p>Its license just got opened up, but it does reference WindowsBase -- not sure if that means it's coupled to Windows. </p> <h2>Acropolis</h2> <p>I'm not sure what this is. Is it MEF, or something that is still coming?</p> <h2>Composite Application Blocks</h2> <p>There are WPF and Winforms Composite Application blocks that seem to provide much more of a workbench framework. I have very little experience with these but they appear to rely on Guidance Automation quite a bit are obviously coupled with the UI layers. There are a few examples of combining MEF with these application blocks.</p> <hr> <p>I've done the best I could to answer my own question here, but I'm really only scratching the surface, and I don't have experience with any of these frameworks. Hopefully some of you can add more detail about the frameworks you have experience with. It would be great if we could end up with some sort of comparison matrix.</p>
<p>Can be considered...</p> <p><a href="http://www.codeplex.com/CompositeWPF" rel="nofollow noreferrer">Composite Application Guidance for WPF and Silverlight</a></p> <p><a href="http://msdn.microsoft.com/en-us/vstudio/bb510103.aspx" rel="nofollow noreferrer">Visual Studio 2008 Shell</a></p>
<p>While I'm not familiar with the specifics of RCP, I think <a href="http://www.devexpress.com/Products/Visual_Studio_Add-in/DXCore/" rel="nofollow noreferrer">DxCore</a> is probably going to be the most complete framework for extending Visual Studio with managed code. It uses a plug-in based architecture and gives you the ability to create anything from tool windows (hosting whatever code you want) to "Actions" (items which can be tied to keyboard shortcuts and context menus) and refactorings, with an extremely rich context system, and a language agnostic code generation engine. It provides a very nice abstraction layer on top of the rather scary underbelly of Visual Studio. It is also written to be version agnostic, so plugins written against DxCore will work for VS 2005 and VS 2008.</p> <p>While it is free it is not open source, and there is, sadly, very little documentation. You have the samples provided, which are a good start, but here are some other resources that could be useful:</p> <ul> <li><a href="http://community.devexpress.com/blogs/markmiller/" rel="nofollow noreferrer">Mark Miller</a> is the Architect for DxCore/CodeRush/Refactor Pro!, and has some postings on his blog (and <a href="http://dnrtv.com/default.aspx?showID=5" rel="nofollow noreferrer">DNR TV</a> episodes) about writing DxCore plugins.</li> <li>There is a <a href="http://community.devexpress.com/forums/" rel="nofollow noreferrer">community forum</a> where you can post questions. This is followed by Mark and some of the other DxCore developers, as well as some folks from the community</li> <li><a href="http://code.google.com/p/dxcorecommunityplugins/" rel="nofollow noreferrer">DxCore Plugins</a> on Google Code. An attempt to collect the plugins that have been created by the community into one place. This is a nice mixture of tools and refactorings, though some are out of date.</li> </ul> <p>Hopefully this will be useful to you. The only thing really bad I have to say about it, and the reason it is probably not more widely utilized is that it is such a large library, with almost no documentation, you have to be willing to dig to find out how to utilize some of the cooler features.</p> <p>Good Luck!</p>
28,756
<p>I am having trouble with visible attribute of an ASP.NET <code>Panel</code> control. I have a page that calls a database table and returns the results in a datagrid.</p> <h3>Requirements</h3> <p>If some of the returned values are <code>null</code> I need to hide the image that's next to it.</p> <p>I am using a <code>Panel</code> to determine whether to hide or show the image but am having trouble with the statement:</p> <pre><code>visible='&lt;%# Eval(&quot;addr1&quot;) &lt;&gt; DBNull.Value %&gt;' </code></pre> <p>I have tried these as well:</p> <pre><code>visible='&lt;%# Eval(&quot;addr1&quot;) &lt;&gt; DBNull.Value %&gt;' visible='&lt;%# IIf(Eval(&quot;addr1&quot;) Is DbNull.Value, &quot;False&quot;,&quot;True&quot;) %&gt;' </code></pre> <p>Code is below:</p> <pre><code>&lt;asp:TemplateField &gt; &lt;ItemTemplate&gt; &lt;%# Eval(&quot;Name&quot;)%&gt; &lt;p&gt; &lt;asp:Panel runat=&quot;server&quot; ID=&quot;Panel1&quot; visible='&lt;%# Eval(&quot;addr1&quot;) &lt;&gt; DBNull.Value %&gt;'&gt; &lt;asp:Image Id=&quot;imgHouse&quot; runat=&quot;server&quot; AlternateText=&quot;Address&quot; SkinId=&quot;imgHouse&quot;/&gt; &lt;/asp:Panel&gt; &lt;%# Eval(&quot;addr1&quot;) %&gt;&lt;p&gt; &lt;/ItemTemplate&gt; &lt;/asp:TemplateField&gt; </code></pre> <p>What am I doing wrong?</p> <p><strong>Edit</strong></p> <p>If I use <code>visible='&lt;%# IIf(Eval(&quot;addr1&quot;) Is DbNull.Value, &quot;False&quot;,&quot;True&quot;) %&gt;'</code></p> <p>I get the following error:</p> <pre><code>Compiler Error Message: CS1026: ) expected </code></pre>
<p>try:</p> <p><code>&lt;%# String.IsNullOrEmpty(DataBinder.Eval(Container.DataItem,"addr1").ToString()) #&gt;</code></p>
<p>try comparing the result of the eval to blank as opposed to null. </p>
49,650
<p>From my experience with <a href="http://en.wikipedia.org/wiki/OpenID" rel="nofollow noreferrer">OpenID</a>, I see a number of significant downsides:</p> <p><strong>Adds a <a href="http://en.wikipedia.org/wiki/Single_Point_of_Failure" rel="nofollow noreferrer">Single Point of Failure</a> to the site</strong><br> It is not a failure that can be fixed by the site even if detected. If the OpenID provider is down for three days, what recourse does the site have to allow its users to login and access the information they own?</p> <p><strong>Takes a user to another sites content and every time they logon to your site</strong><br> Even if the OpenID provider does not have an error, the user is re-directed to their site to login. The login page has content and links. So there is a chance a user will actually be drawn away from the site to go down the Internet rabbit hole.</p> <p>Why would I want to send my users to another company's website?<br/> [ Note: my provider no longer does this and seems to have fixed this problem (for now).]</p> <p><strong>Adds a non-trivial amount of time to the signup</strong><br> To sign up with the site a new user is forced to read a new standard, chose a provider, and signup. Standards are something that the technical people should agree to in order to make a user experience frictionless. They are not something that should be thrust on the users.</p> <p><strong>It is a Phisher's Dream</strong><br> OpenID is incredibly insecure and stealing the person's ID as they log in is trivially easy. [ taken from David Arno's <a href="https://stackoverflow.com/questions/60436/what-is-the-benefit-of-using-only-openid-authentication-on-a-site#173467">Answer</a> below ]</p> <hr> <p>For all of the downside, the one upside is to allow users to have fewer logins on the Internet. If a site has opt-in for OpenID then users who want that feature can use it.</p> <p><strong>What I would like to understand is:</strong><br> What benefit does a site get for making OpenID <b>mandatory</b>?</p>
<p>The benefit of making OpenID mandatory is simply that login code for the website does not need to be written (beyond the OpenID integration), and no precautions need to be taken around storing user passwords etc.</p> <p>Not having your own login code also means not having to deal with a lot of support issues like resetting of lost passwords etc.</p> <p>Certainly most of your downsides are valid, so I guess it becomes a trade off.</p> <p>What surprises me is that there are not more sites forming a close relationship with a particular OpenID provider to simply the account signup phase - i.e. some sort of 'You can use any OpenID you like, but you can also create one right now by entering a username and password etc' login page, which automatically creates a new account with the selected provider for you.</p>
<p>The main benefit of having an OpenID will be seen in the long term. Instead of having to apply to different sites for an identity, you do that once and then use it on all the sites that require a unique identity. Of course for secure sites like banking and trading it will need a different kind of thinking altogether. But for social networking sites and the like you can use it easily. </p> <p>Mom and Dad will find it easy too because now they have to remember only one username/password. A lot of times it gets hard for us to remember what login we have at which site, and end up using the correct username/password of Site A on Site B. OpenID will solve that. Plus it's a good revenue model for an OpenID provider and user. I can enter to one such provider all the details I am willing to give and every such detail I give I can earn money. </p> <p>Maybe the provider can coax me to tell it more about myself using that as an incentive, which it can then sell to the sites I register with. So Site A pays OpenID for my information. OpenID then passes a cut of that on to me. Site A doesn't have to manage users, OpenID gets money, user gets money, everybody is happy :)</p> <p>This way you won't have to make OpenID mandatory. People themselves will want it. OpenID providers will then compete amongst themselves to provide better services, and where there is competition there will be better value provided to all concerned. I think it's a fabulous idea.</p> <p><strong>Edit:</strong> Regarding downtimes at one particular provider; if OpenID provider A is not confident of providing 100% uptime, it can take the help of another provider B, and the user on Provider A can choose from the options provider A gives. The site which goes to provider A to authenticate a user will know which other providers to go to in case provider A is not working. This will be stored in its database on first login automatically. Anybody want to brainstorm the implementation details ? :) </p>
8,529
<p>Here's my situation.</p> <p>I have a button on my ASP.NET webform. This button creates a new browser window pointing to a page which has a lot of hidden fields (which are dynamically generated). This form submits itself to SQL Reporting Services on the bodies onload event. This works fine and the report is displayed in this new window.</p> <p>However, now I want to still POST a form to SQL Reporting services but I want to get back an excel spreadsheet. So I add another hidden input with a name of rs:Format and value of Excel. This works and the user gets the option to download the excel file.</p> <p>However they are now stuck with the extra window that was created. How do I get around this? I've tried creating the dynamic form and POST in the same window, but then they see the (empty) page with the form, and not the page they generated the report from. I've tried closing the window that I've created but I don't know where to put the javascript to do this. If I put it on the onload, then the window closes without the form being submitted.</p> <p>Any ideas for what to do here?</p> <p>Edit: What I was doing here wasn't the best way of getting the result I needed. I ended up using a WebRequest to get the excel report from Reporting Services instead posting a form, therefore I didn't need the second window afterall.</p>
<p><strong>Don't</strong> close the browser. It belongs to the user, even if you opened it. Closing it can make them mad.<br> <strong>Do</strong> redirect to a page the communicates to the user that you're done with the window. There you can provide a (javascript-based) link that make closing the browser a little easier if you want, though closing a browser window is generally pretty easy.</p>
<p>Generally it's ok to close any popup window that your app has created.</p> <p>This can be done with <strong>window.close()</strong> (which will pop up a confirmation if the window was not created by script).</p> <p>If you want to be sure that the download is successful before closing the window, you will need to perform some server-side magic - have your server keep track of the download in progress, and poll it via AJAX from the popup window until the download completes.</p> <p>Once the server tells you it's done, the window can be closed.</p>
21,813
<p>I'm wondering if people can suggest the best tutorial that will walk me through the best way to do Drag and Drop with control collision detection etc, using MS Silverlight V2.</p> <p>I've done the <a href="http://silverlight.net/learn/tutorials.aspx" rel="nofollow noreferrer">Jesse Liberty tutorials</a> at Silverlight.net, and they were a good introduction, but I'm looking for something a bit deeper.</p> <p>Suggestions?</p> <p>UPDATE: Here is the summary of the list of answers for convenience:</p> <ol> <li><a href="http://www.adefwebserver.com/DotNetNukeHELP/Misc/Silverlight/DragAndDropTest/" rel="nofollow noreferrer">http://www.adefwebserver.com/DotNetNukeHELP/Misc/Silverlight/DragAndDropTest/</a></li> <li><a href="http://leeontech.wordpress.com/2008/04/11/drag-and-drop-in-silverlight/" rel="nofollow noreferrer">Lee’s corner</a></li> <li><a href="http://simplesilverlight.wordpress.com/2008/08/13/drag-and-drop-silverlight-example/" rel="nofollow noreferrer">Corey Schuman</a></li> <li><a href="http://blogs.msdn.com/mgrayson/archive/2008/08/18/silverlight-2-samples-dragging-docking-expanding-panels-part-2.aspx" rel="nofollow noreferrer">MARTIN GRAYSON: ADVENTURES OF A 'DEVIGNER'</a></li> <li><a href="http://www.codeplex.com/silverlightdragdrop" rel="nofollow noreferrer">http://www.codeplex.com/silverlightdragdrop</a></li> <li><a href="http://nickssoftwareblog.com/2008/10/07/silverlight-20-in-examples-part-drag-and-drop-inside-out/" rel="nofollow noreferrer">Nick Polyak’s Software Blog</a></li> </ol>
<p>Here is a page that explained the solution for my use.</p> <p><a href="http://www.adefwebserver.com/DotNetNukeHELP/Misc/Silverlight/DragAndDropTest/" rel="nofollow noreferrer">Silverlight 2 Drag, Drop, and Import Content Example</a></p>
<p>A codeplex project for drag and drop <a href="http://www.codeplex.com/silverlightdragdrop" rel="nofollow noreferrer">http://www.codeplex.com/silverlightdragdrop</a></p>
9,563
<p>I just bought new eSUN PETg filament. When I started to extrude it, I heard popping sound same as moisture boiling out of it. I don't expect new eSUN vaccum sealed filament having moisture content. Is there any problem with my e3d v6? Is it possible that due to old filament, moisture is residing inside my extruder assembly and new filament is carrying it while extruding? My settings : </p> <ul> <li>print temperature: 250&nbsp;&deg;C, </li> <li>bed temperature: 80&nbsp;&deg;C, </li> <li>retraction length: 6.5&nbsp;mm, </li> <li>retraction speed: 25&nbsp;mm/s, </li> <li>print speed: 10&nbsp;mm/s, </li> <li>layer height: 25 micron</li> </ul> <p>What do I do in this case? Should I clean the extruder assembly? </p>
<p>The extruder can't hold much water and transport it to the melt zone. Filament can. The printer behaves like the filament is wet, so try drying it. </p> <p>Try putting the filament in your electric oven at the lowest temperature (often 170&nbsp;&deg;F to 180&nbsp;&deg;F) for an hour and see if the behavior improves. </p> <p>Keep the filament at a distance from (or shield it from) the heating elements. </p>
<p>eSun has had quality problems recently (mid 2020), when they switched from the screw together clear reels to the molded black reels. I got an unprintable roll of PLA that was wet and brittle, others reported similar issues. This is theorized to have coincided with them moving production to Vietnam.</p> <p>Try to dry it, but if that doesn’t help, try a different brand. As far as your settings, I’ve printed a couple reels of the eSun PETG successfully at 235 °C, with 75 °C bed (though bed would have nothing to do with moisture). Agree 10 mm/s print speed is excruciatingly slow. 50 mm/s is typical for a Bowden setup.</p>
1,565
<p>Using The loader class of Adobe Flex, I load an external SWF file. However, the loaded SWF file has a different frameRate than my application.</p> <p>Is it possible to have both the parent app and the loaded child app playing at different framerates? If so, how?</p>
<p><a href="http://livedocs.adobe.com/flash/9.0/ActionScriptLangRefV3/flash/display/LoaderInfo.html#frameRate" rel="nofollow noreferrer">It's not possible.</a></p> <blockquote> <p>Flash Player or Adobe AIR only uses a single frame rate for all loaded SWF files at any one time, and this frame rate is determined by the nominal frame rate of the main SWF file</p> </blockquote> <p>There are two ways around this, change the framerate of the main swf to match the loaded one (this can be done during runtime) or decouple the animation from actual frames and use events to step it forward.</p>
<p>If you decide to use events to drive your swf in order to approximate different frame rates I'd recommend using a tween engine like <a href="http://blog.greensock.com/tweenmaxas3/" rel="nofollow noreferrer">TweenLite/TweenMax</a>.</p> <p>It's free (as in beer) and I've used it very successfully for frame based tweening in the past.</p>
14,583
<p>I have read that it is possible to <a href="http://developer.imendio.com/projects/gtk-macosx/build-instructions" rel="nofollow noreferrer">build GTK+ on MacOS X</a>. I know that it's possible to create a <a href="http://developer.imendio.com/projects/gtk-macosx/creating-app-bundles" rel="nofollow noreferrer">bundle of a GTK+ application on MacOS</a>. I also know that it's possible to create widgets <a href="http://people.imendio.com/richard/archives/2008/02/native_mac_them_1.html" rel="nofollow noreferrer">that look sort of native</a>. However, searching around I am not really clear on how to create a bundle that includes the native theme stuff, and uses Python rather than its own C main-point. There are also rumors <a href="http://developer.imendio.com/node/175" rel="nofollow noreferrer">that it's possible to build PyGTK</a>, but it sounds like there might still be some wrinkles in that process.</p> <p>However, there is no step-by-step guide that explains how one can set up an environment where an application might be run from Python source, then built and deployed in an app bundle. How can I go about doing that?</p>
<p>Native looking widgets is quite complicated. There's a beginning of quartz engine (for theming) found here <a href="http://git.gnome.org/browse/gtk+/tree/gdk/quartz" rel="nofollow noreferrer">http://git.gnome.org/browse/gtk+/tree/gdk/quartz</a> For self-contained applications check out the newly released bundle on <a href="http://live.gnome.org/GTK%2B/OSX" rel="nofollow noreferrer">http://live.gnome.org/GTK%2B/OSX</a></p>
<p>I'm not sure if I'm grokking all the details of your question, but looking at your problem in general (how do I deploy a python app on mac), I'm inclined to say that the answer is <a href="http://undefined.org/python/py2app.html" rel="nofollow noreferrer">py2app</a>. Basically this will bundle a python interpreter and all relevant python files for you, and give you a scriptable system that you can use to add in whatever other resources/dependencies you need. </p>
14,380
<p>Is it possible to create a simple 3D model (for example in 3DS MAX) and then import it to Android?</p>
<p>That's where I got to:</p> <ul> <li>I've used Google's APIDemos as a starting point - there are rotating cubes in there, each specified by two arrays: vertices and indices.</li> <li>I've build my model using Blender and exported it as OFF file - it's a text file that lists all the vertices and then faces in terms of these vertices (indexed geometry)</li> <li>Then I've created a simple C++ app that takes that OFF and writes it as two XMLs containing arrays (one for vertices and one for indices)</li> <li>These XML files are then copied to res/values and this way I can assign the data they contain to arrays like this:<br/> <code>int vertices[] = context.getResources().getIntArray(R.array.vertices);</code></li> <li>I also need to manually change the number of faces to be drawn in here: <code>gl.glDrawElements(GL10.GL_TRIANGLES, 212*6, GL10.GL_UNSIGNED_SHORT, mIndexBuffer);</code> - you can find that number (212 in this case) on top of the OFF file</li> </ul> <p>Here you can find my project page, which uses this solution: <a href="https://github.com/maciejgryka/vsiogap3d" rel="noreferrer">Github project > vsiogap3d</a></p>
<p>Not sure about Android specifically, but generally speaking you need a script in 3DS Max that manually writes out the formatting you need from the model.</p> <p>As to whether one exists for Android or not, I do not know.</p>
25,008
<p>I am using C# 2.0 with Nunit Test. I have some object that needs to be serialized. These objects are quite complex (inheritance at different levels and contains a lot of objects, events and delegates).</p> <p>How can I create a Unit Test to be sure that my object is safely serializable?</p>
<p>Here is a generic way:</p> <pre><code>public static Stream Serialize(object source) { IFormatter formatter = new BinaryFormatter(); Stream stream = new MemoryStream(); formatter.Serialize(stream, source); return stream; } public static T Deserialize&lt;T&gt;(Stream stream) { IFormatter formatter = new BinaryFormatter(); stream.Position = 0; return (T)formatter.Deserialize(stream); } public static T Clone&lt;T&gt;(object source) { return Deserialize&lt;T&gt;(Serialize(source)); } </code></pre>
<p>Unfortunately, you can't really test for this. Imagine this case:</p> <pre><code>[Serializable] class Foo { public Bar MyBar { get; set; } } [Serializable] class Bar { int x; } class DerivedBar : Bar { } public void TestSerializeFoo() { Serialize(new Foo()); // OK Serialize(new Foo() { MyBar = new Bar() }; // OK Serialize(new Foo() { MyBar = new DerivedBar() }; // Boom } </code></pre>
29,278
<p>Why does it (apparently) make a difference whether I pass <code>null</code> as an argument directly, or pass an <code>Object</code> that I assigned the <em>value</em> <code>null</code>?</p> <pre><code>Object testVal = null; test.foo(testVal); // dispatched to foo(Object) // test.foo(null); // compilation problem -&gt; "The method foo(String) is ambiguous" public void foo(String arg) { // More-specific System.out.println("foo(String)"); } public void foo(Object arg) { // Generic System.out.println("foo(Object)"); } </code></pre> <p>In other words, why is the (commented-out) second call to <code>foo(...)</code> not dispatched to <code>foo(Object)</code>?</p> <p><strong>Update:</strong> I use Java 1.6. I could compile Hemal's code without problems, but mine still doesn't compile. The only difference I see is that Hemal's methods are static while mine are not. But I really don't see why this should make a difference...?</p> <p><strong>Update 2:</strong> Solved. I had another method foo(Runnable) in my class, so the dispatcher couldn't unambiguously select the single most specific method. (See my comment in Hemal's second answer.) Thanks everyone for your help.</p>
<p>Which version of Java are you using? With 1.6.0_11 the code (pasted below) compiles and runs.</p> <p>I am sure its obvious why <code>foo(testVal)</code> goes to <code>foo(Object)</code>.</p> <p>The reason why <code>foo(null)</code> goes to <code>foo(String)</code> is a little complex. The constant <code>null</code> is of type <code>nulltype</code>, which is a subtype of all types. So, this <code>nulltype</code> extends <code>String</code>, which extends <code>Object</code>.</p> <p>When you call <code>foo(null)</code> compiler looks for the overloaded method with most specific type. Since <code>String</code> is more specific then <code>Object</code> that is the method that gets called.</p> <p>If you had another overload that was as specific as String, say <code>foo(Integer)</code> then you would get a ambiguous overload error.</p> <pre><code>class NullType { public static final void main(final String[] args) { foo(); } static void foo() { Object testVal = null; foo(testVal); // dispatched to foo(Object) foo(null); // compilation problem -&gt; "The method foo(String) is ambiguous" } public static void foo(String arg) { // More-specific System.out.println("foo(String)"); } public static void foo(Object arg) { // Generic System.out.println("foo(Object)"); } } </code></pre>
<p>Has anyone tried the example ???</p> <p>With 1.6.0 foo(null) is dispatched to the most specific method applicable which is foo(String)...</p> <p>If you add a new method say foo(Integer) the compiler cannot choose the most specific applicable method and shows an error.</p> <p>-Patrick</p>
49,393
<p>Using C#, I need a class called <code>User</code> that has a username, password, active flag, first name, last name, full name, etc. </p> <p>There should be methods to <em>authenticate</em> and <em>save</em> a user. Do I just write a test for the methods? And do I even need to worry about testing the properties since they are .Net's getter and setters?</p>
<p>Many great responses to this are also on my question: "<a href="https://stackoverflow.com/questions/24965/beginning-tdd-challenges-solutions-recommendations">Beginning TDD - Challenges? Solutions? Recommendations?</a>"</p> <p>May I also recommend taking a look at my <a href="http://cantgrokwontgrok.blogspot.com/2008/09/tdd-getting-started-with-test-driven.html" rel="noreferrer">blog post</a> (which was partly inspired by my question), I have got some good feedback on that. Namely:</p> <blockquote> <p><strong>I Don’t Know Where to Start?</strong></p> <ul> <li>Start afresh. Only think about writing tests when you are writing new code. This can be re-working of old code, or a completely new feature.</li> <li>Start simple. Don’t go running off and trying to get your head round a testing framework as well as being TDD-esque. Debug.Assert works fine. Use it as a starting point. It doesn’t mess with your project or create dependencies.</li> <li>Start positive. You are trying to improve your craft, feel good about it. I have seen plenty of developers out there that are happy to stagnate and not try new things to better themselves. You are doing the right thing, remember this and it will help stop you from giving up.</li> <li>Start ready for a challenge. It is quite hard to start getting into testing. Expect a challenge, but remember – challenges can be overcome.</li> </ul> <p><strong>Only Test For What You Expect</strong></p> <p>I had real problems when I first started because I was constantly sat there trying to figure out every possible problem that could occur and then trying to test for it and fix. This is a quick way to a headache. Testing should be a real YAGNI process. If you know there is a problem, then write a test for it. Otherwise, don’t bother.</p> <p><strong>Only Test One Thing</strong></p> <p>Each test case should only ever test one thing. If you ever find yourself putting “and” in the test case name, you’re doing something wrong.</p> </blockquote> <p>I hope this means we can move on from "getters and setters" :)</p>
<p>I can't speak for C# specificly, but when I write unit tests I test EVERY input, even those the user does not do, that way I know how to prevent my own mistakes.</p>
8,812
<p>The CSS rules <code>visibility:hidden</code> and <code>display:none</code> both result in the element not being visible. Are these synonyms?</p>
<p><code>display:none</code> means that the tag in question will not appear on the page at all (although you can still interact with it through the dom). There will be no space allocated for it between the other tags. </p> <p><code>visibility:hidden</code> means that unlike <code>display:none</code>, the tag is not visible, but space is allocated for it on the page. The tag is rendered, it just isn't seen on the page.</p> <p>For example:</p> <pre><code>test | &lt;span style="[style-tag-value]"&gt;Appropriate style in this tag&lt;/span&gt; | test </code></pre> <p>Replacing <code>[style-tag-value]</code> with <code>display:none</code> results in:</p> <pre><code>test | | test </code></pre> <p>Replacing <code>[style-tag-value]</code> with <code>visibility:hidden</code> results in:</p> <pre><code>test |                        | test </code></pre>
<p><code>display:none;</code> will neither display the element nor will it allot space for the element on the page whereas <code>visibility:hidden;</code> will not display the element on the page but will allot space on the page. We can access the element in DOM in both cases. To understand it in a better way please look at the following code: <a href="https://jsfiddle.net/pritam1605/vp7uuukt/2/" rel="nofollow noreferrer">display:none vs visibility:hidden</a></p>
16,110
<p>I have a menu running off of a sitemap which one of the SiteMapNode looks like this: </p> <pre><code>&lt;siteMapNode title="Gear" description="" url=""&gt; &lt;siteMapNode title="Armor" description="" url="~/Armor.aspx" /&gt; &lt;siteMapNode title="Weapons" description="" url="~/Weapons.aspx" /&gt; &lt;/siteMapNode&gt; </code></pre> <p>I also have a Skin applied to the asp:menu which uses the following css definition:</p> <pre><code>.nav-bar { z-index: 2; margin-top: -5%; position: absolute; top: 281px; font-family: Jokewood; font-style: italic; } </code></pre> <p>When I run the website and mouseOver the Gear link, the Jokewood font is not applied to those items, how can I apply the css to the Armor and Weapons titles?</p> <p><strong>Update</strong><br> I should of mentioned that the font is displayed correctly on all non-nested siteMapNodes.</p>
<p>you can nest CSS commands by listing them in sequence</p> <p>siteMapNode siteMapNode { .... css code ... } would be applied to the inner node.</p> <p>for instance, </p> <p>#menu ul ul { ... }</p> <p>would be applied to <br> &lt;ul&gt; &lt;-- not here<br> &lt;li&gt;<br> &lt;/li&gt;<br> &lt;/ul&gt;<br> &lt;div id="menu"&gt;<br> &lt;ul&gt; &lt;-- not here<br> &lt;ul&gt; &lt;---- <b>here</b><br></p>
<p>The skin is applied through a .skin template.</p> <pre><code>&lt;asp:Menu runat="server" CssClass="nav-bar" /&gt; </code></pre>
15,270
<p>To do DataBinding of the <code>Document</code> in a WPF <code>RichtextBox</code>, I saw 2 solutions so far, which are to derive from the <code>RichtextBox</code> and add a <code>DependencyProperty</code>, and also the solution with a "proxy".</p> <p>Neither the first or the second are satisfactory. Does somebody know another solution, or instead, a commercial RTF control which is capable of <strong>DataBinding</strong>? The normal <code>TextBox</code> is not an alternative, since we need text formatting.</p> <p>Any idea?</p>
<p>There is a much easier way!</p> <p>You can easily create an attached <code>DocumentXaml</code> (or <code>DocumentRTF</code>) property which will allow you to bind the <code>RichTextBox</code>'s document. It is used like this, where <code>Autobiography</code> is a string property in your data model:</p> <pre><code>&lt;TextBox Text="{Binding FirstName}" /&gt; &lt;TextBox Text="{Binding LastName}" /&gt; &lt;RichTextBox local:RichTextBoxHelper.DocumentXaml="{Binding Autobiography}" /&gt; </code></pre> <p>Voila! Fully bindable <code>RichTextBox</code> data!</p> <p>The implementation of this property is quite simple: When the property is set, load the XAML (or RTF) into a new <code>FlowDocument</code>. When the <code>FlowDocument</code> changes, update the property value.</p> <p>This code should do the trick:</p> <pre><code>using System.IO; using System.Text; using System.Windows; using System.Windows.Controls; using System.Windows.Documents; public class RichTextBoxHelper : DependencyObject { public static string GetDocumentXaml(DependencyObject obj) { return (string)obj.GetValue(DocumentXamlProperty); } public static void SetDocumentXaml(DependencyObject obj, string value) { obj.SetValue(DocumentXamlProperty, value); } public static readonly DependencyProperty DocumentXamlProperty = DependencyProperty.RegisterAttached( "DocumentXaml", typeof(string), typeof(RichTextBoxHelper), new FrameworkPropertyMetadata { BindsTwoWayByDefault = true, PropertyChangedCallback = (obj, e) =&gt; { var richTextBox = (RichTextBox)obj; // Parse the XAML to a document (or use XamlReader.Parse()) var xaml = GetDocumentXaml(richTextBox); var doc = new FlowDocument(); var range = new TextRange(doc.ContentStart, doc.ContentEnd); range.Load(new MemoryStream(Encoding.UTF8.GetBytes(xaml)), DataFormats.Xaml); // Set the document richTextBox.Document = doc; // When the document changes update the source range.Changed += (obj2, e2) =&gt; { if (richTextBox.Document == doc) { MemoryStream buffer = new MemoryStream(); range.Save(buffer, DataFormats.Xaml); SetDocumentXaml(richTextBox, Encoding.UTF8.GetString(buffer.ToArray())); } }; } }); } </code></pre> <p>The same code could be used for TextFormats.RTF or TextFormats.XamlPackage. For XamlPackage you would have a property of type <code>byte[]</code> instead of <code>string</code>.</p> <p>The XamlPackage format has several advantages over plain XAML, especially the ability to include resources such as images, and it is more flexible and easier to work with than RTF.</p> <p>It is hard to believe this question sat for 15 months without anyone pointing out the easy way to do this.</p>
<p>This VB.Net version works for my situation. I removed thread collection semaphore, instead using RemoveHandler and AddHandler. Also, since a FlowDocument can only be bound to one RichTextBox at a time, I put in a check that the RichTextBox's IsLoaded=True. Let's begin with how I used the class in a MVVM app which uses ResourceDictionary instead of Window.</p> <pre class="lang-vb prettyprint-override"><code> ' Loaded and Unloaded events seems to be the only way to initialize a control created from a Resource Dictionary ' Loading document here because Loaded is the last available event to create a document Private Sub Rtb_Loaded(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) ' only good place to initialize RichTextBox.Document with DependencyProperty Dim rtb As RichTextBox = DirectCast(sender, RichTextBox) Try rtb.Document = RichTextBoxHelper.GetDocumentXaml(rtb) Catch ex As Exception Debug.WriteLine("Rtb_Loaded: Message:" &amp; ex.Message) End Try End Sub ' Loaded and Unloaded events seems to be the only way to initialize a control created from a Resource Dictionary ' Free document being held by RichTextBox.Document by assigning New FlowDocument to RichTextBox.Document. Otherwise we'll see an of "Document belongs to another RichTextBox" Private Sub Rtb_Unloaded(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Dim rtb As RichTextBox = DirectCast(sender, RichTextBox) Dim fd As New FlowDocument RichTextBoxHelper.SetDocumentXaml(rtb, fd) Try rtb.Document = fd Catch ex As Exception Debug.WriteLine("PoemDocument.PoemDocumentView.PoemRtb_Unloaded: Message:" &amp; ex.Message) End Try End Sub Public Class RichTextBoxHelper Inherits DependencyObject Public Shared Function GetDocumentXaml(ByVal depObj As DependencyObject) As FlowDocument Return depObj.GetValue(DocumentXamlProperty) End Function Public Shared Sub SetDocumentXaml(ByVal depObj As DependencyObject, ByVal value As FlowDocument) depObj.SetValue(DocumentXamlProperty, value) End Sub Public Shared ReadOnly DocumentXamlProperty As DependencyProperty = DependencyProperty.RegisterAttached("DocumentXaml", GetType(FlowDocument), GetType(RichTextBoxHelper), New FrameworkPropertyMetadata(Nothing, FrameworkPropertyMetadataOptions.AffectsRender Or FrameworkPropertyMetadataOptions.BindsTwoWayByDefault, Sub(depObj, e) RegisterIt(depObj, e) End Sub)) Private Shared Sub RegisterIt(ByVal depObj As System.Windows.DependencyObject, ByVal e As System.Windows.DependencyPropertyChangedEventArgs) Dim rtb As RichTextBox = DirectCast(depObj, RichTextBox) If rtb.IsLoaded Then RemoveHandler rtb.TextChanged, AddressOf TextChanged Try rtb.Document = GetDocumentXaml(rtb) Catch ex As Exception Debug.WriteLine("RichTextBoxHelper.RegisterIt: ex:" &amp; ex.Message) rtb.Document = New FlowDocument() End Try AddHandler rtb.TextChanged, AddressOf TextChanged Else Debug.WriteLine("RichTextBoxHelper: Unloaded control ignored:" &amp; rtb.Name) End If End Sub ' When a RichTextBox Document changes, update the DependencyProperty so they're in sync. Private Shared Sub TextChanged(ByVal sender As Object, ByVal e As TextChangedEventArgs) Dim rtb As RichTextBox = TryCast(sender, RichTextBox) If rtb IsNot Nothing Then SetDocumentXaml(sender, rtb.Document) End If End Sub End Class </code></pre>
44,665
<p>Unfortunately, the problem is not more specific than that. I've found a few examples of people reporting similar problems by doing <a href="http://www.google.com/search?source=ig&amp;hl=en&amp;rlz=&amp;=&amp;q=%22Unknown+object+in+backup+file%22&amp;btnG=Google+Search&amp;aq=f" rel="nofollow noreferrer">a Google search</a>, but I can't find the part of the restore that is actually causing the problem, which might help me track it down on my own.</p> <p>Suggestions for either resolving this problem or being able to track down the root cause would be appreciated.</p>
<p>There's one bug logged at bugs.mysql.com that references the error you describe:</p> <p>"<a href="http://bugs.mysql.com/bug.php?id=37253" rel="nofollow noreferrer">Bug #37253 Unable to restore backup file containing BLOBs</a>"</p> <p>The solution described in that bug is to increase the <code>max_allowed_packet</code> in the MySQL server configuration. The user confirmed that raising the value to 100M allowed him to restore his database.</p>
<p>I have had something similar in the past- it has something to do with how it was backed up. I think some applications put invalid comments in the backup files which cause errors. </p> <p>My suggestion- if you are stuck trying to restore those files- is to incrementally start backing up from sections of the backup file and find what is causing the problems- which from what I recall the case for me was that they were some text in the file that was inconsequential to remove.</p>
37,159
<p>We've got a page with a ton of jQuery (approximately 2000 lines) that we want to trim down b/c it is a maintenance nightmare, and it might be easier to maintain on the server. We've thought about using UpdatePanel for this. However, we don't like the fact that the UpdatePanel is sending the whole page back to the server. </p>
<p>Don't move to UpdatePanels. After coming from jQuery, <a href="http://encosia.com/2007/07/11/why-aspnet-ajax-updatepanels-are-dangerous/" rel="noreferrer">the drop in performance</a> would be untenable. Especially on a page as complex as yours sounds.</p> <p>If you have 2,000 lines of JavaScript code, the solution is to refactor that code. If you put 2,000 lines of C# code in one file, it would be difficult to maintain too. That would be difficult to manage effectively with <strong>any</strong> language or tool.</p> <p>If you're using 3.5 SP1, you can use the ScriptManager's new script combining to separate your JavaScript into multiple files with no penalty. That way, you can logically partition your code just as you would with server side code.</p>
<p>Using UpdatePanel force you to use ScriptManager that added tons of scripts in your webpages. UpdatePanel provides you partial postback and not real ajax. If your will run only on a LAN and not internet that's ok, but if your target is internet try refractoring your codes and compress them with some tools before publish on the website</p>
4,249
<p>I want to obtain the current number of window handles and the system-wide window handle limit in C#. How do I go about this?</p>
<p>If you read Raymond Chen's post, you'll probably find it as annoying as I did. You're only "probably doing something wrong" because you're doing something Windows isn't capable of. </p> <p>In my application, the first time a user visits a tab page, I create and lay out all the controls on that page. This takes a noticeable amount of time - there can easily be 50 controls on a page. So I don't discard the controls on a tab page after populating it, if it's at all possible, and leave closing sets of tab pages up to the user.</p> <p>As it happens, some users never want to close <em>any</em> sets of tab pages. Why should I be forcing them to? With my UI, they can navigate very quickly to any one of the 300+ sets of transactions that they're responsible for managing. Their machines are fast enough, and have enough memory, to make this all very responsive. The only problem is that Windows can't support it.</p> <p>Why am I using controls, and not some other UI technology? Because they <em>work</em>. I need to support focus events, tab order, validation events, dynamic layout, and data binding - the users are actually managing thousands of records, in dozens of tables, in an in-memory DataSet. The amount of development I'd have to do to - say - implement something using windowless controls is astronomical.</p> <p>I'm only "doing it wrong" because Windows has a hard limit on the number of window handles that it can support. That hard limit is based on a bunch of decade-old assumptions about how a computer's UI might be built. It's not me who's "doing something wrong."</p> <p>At any rate, my solution to this is in two parts. </p> <p>First, a class that can tell you how many window handles your process is using:</p> <pre><code>using System; using System.Runtime.InteropServices; namespace StreamWrite.Proceedings.Client { public class HWndCounter { [DllImport("kernel32.dll")] private static extern IntPtr GetCurrentProcess(); [DllImport("user32.dll")] private static extern uint GetGuiResources(IntPtr hProcess, uint uiFlags); private enum ResourceType { Gdi = 0, User = 1 } public static int GetWindowHandlesForCurrentProcess(IntPtr hWnd) { IntPtr processHandle = GetCurrentProcess(); uint gdiObjects = GetGuiResources(processHandle, (uint)ResourceType.Gdi); uint userObjects = GetGuiResources(processHandle, (uint)ResourceType.User); return Convert.ToInt32(gdiObjects + userObjects); } } } </code></pre> <p>Second, I maintain a least-recently-used cache of my tab page objects. The .NET framework doesn't provide a generic LRU cache class, so I built one, which you can get <a href="http://csharp-lru-cache.googlecode.com" rel="noreferrer">here</a> if you need one. Every time the user visits a tab page, I add it to the LRU Cache. Then I check to see if I'm running low on window handles. If I am, I throw away the controls on the least-recently-used tab page, and keep doing that until I have enough window handles again.</p>
<p>The full quote OregonGhost refers to is</p> <blockquote> <p>If you have to ask, you're probably doing something wrong.</p> </blockquote> <p>It's from <a href="https://devblogs.microsoft.com/oldnewthing/20070718-00/?p=25963" rel="nofollow noreferrer">Why is the limit of window handles per process 10,000?</a> You should read this.</p>
17,298
<p>I'm looking for articles related Hypernate in .net</p> <p>Can anyone recommend some?</p>
<p>It seems unlikely that you're <em>really</em> after <a href="http://sourceforge.net/projects/hypernate/" rel="nofollow noreferrer">hypernate</a> (which appears to be a solo project without a release in 3 years). Did you perhaps mean <a href="http://www.nhibernate.org" rel="nofollow noreferrer">NHibernate</a>? If so, you're likely to be able to find what you want just by searching when you use the right name :)</p>
<p>I guess you are looking for articles about NHibernate (check the spelling)? Search stackoverflow or google for NHibernate and you will find lots of articles.</p> <p>The website of the NHibernate project is at <a href="http://www.nhibernate.org/" rel="nofollow noreferrer">http://www.nhibernate.org/</a> (but it seems to be unavailable currently?).</p>
44,700