instruction
stringlengths
21
27.8k
chosen
stringlengths
18
28.2k
rejected
stringlengths
18
33.6k
__index_level_0__
int64
0
50k
<p>Is there someway to set the default file permission in Linux? That is, the file permission for a newly created file (regardless of the context for which it was created ). I know about putting umask in the shell startup but that only works for shell sessions. When I transfer files to a Linux box using <strong>pscp</strong>, the file is always created with permissions of 664 (rw-rw-r--). The has occurred across every flavor of Linux that I've used. This is especially annoying when I pscp a file to shared Linux machine (like my ISP). Until I can shell in and chmod the permission, the file is basically sitting there with read access for everyone, which is not exactly secure.</p>
<p>Put the umask in the non-interactive shell startup (<code>.bash_profile</code>, <code>.zshenv</code>, <code>.tcshrc</code> depending on your shell). Then it'll run for non-login sessions.</p>
<p>If you want to affect the whole system, you can also put it in /etc/profile</p>
28,278
<p>In Ruby on Rails Development (or MVC in general), what quick rule should I follow as to where to put logic.</p> <p>Please answer in the affirmative - With <em>Do put this here</em>, rather than <em>Don't put that there</em>.</p>
<p>MVC</p> <p><strong>Controller</strong>: Put code here that has to do with working out what a user wants, and deciding what to give them, working out whether they are logged in, whether they should see certain data, etc. In the end, the controller looks at requests and works out what data (Models) to show and what Views to render. If you are in doubt about whether code should go in the controller, then it probably shouldn't. Keep your controllers <a href="http://weblog.jamisbuck.org/2006/10/18/skinny-controller-fat-model" rel="noreferrer">skinny</a>.</p> <p><strong>View</strong>: The view should only contain the minimum code to display your data (Model), it shouldn't do lots of processing or calculating, it should be displaying data calculated (or summarized) by the Model, or generated from the Controller. If your View really needs to do processing that can't be done by the Model or Controller, put the code in a Helper. Lots of Ruby code in a View makes the pages markup hard to read.</p> <p><strong>Model</strong>: Your model should be where <strong>all</strong> your code that relates to your data (the entities that make up your site e.g. Users, Post, Accounts, Friends etc.) lives. If code needs to save, update or summarise data related to your entities, put it here. It will be re-usable across your Views and Controllers.</p>
<p>Testing, Testing ... Put as much logic as possible in the model and then you will be able to test it properly. Unit tests test the data and the way it is formed by testing the model, and functional tests test the way it is routed or controlled by testing the controllers, so it follows that you can't test the integrity of the data unless it is in the model.</p> <p>j</p>
8,562
<p>I just learned about <a href="http://ngrep.sourceforge.net/" rel="nofollow noreferrer">ngrep</a>, a cool program that lets you easily sniff packets that match a particular string.</p> <p>The only problem is that it can be hard to see the match in the big blob of output. I'd like to write a wrapper script to highlight these matches -- it could use ANSI escape sequences:</p> <pre><code>echo -e 'This is \e[31mRED\e[0m.' </code></pre> <p>I'm most familiar with Perl, but I'm perfectly happy with a solution in Python or any other language. The simplest approach would be something like:</p> <pre><code>while (&lt;STDIN&gt;) { s/$keyword/\e[31m$keyword\e[0m/g; print; } </code></pre> <p>However, this isn't a nice solution, because ngrep prints out hash marks without newlines whenever it receives a non-matching packet, and the code above will suppress the printing of these hashmarks until the script sees a newline.</p> <p>Is there any way to do the highlighting without inhibiting the instant appearance of the hashmarks?</p>
<p>Ah, forget it. This is too much of a pain. It was a lot easier to get the source to ngrep and make it print the hash marks to stderr:</p> <pre><code>--- ngrep.c 2006-11-28 05:38:43.000000000 -0800 +++ ngrep.c.new 2008-10-17 16:28:29.000000000 -0700 @@ -687,8 +687,7 @@ } if (quiet &lt; 1) { - printf("#"); - fflush(stdout); + fprintf (stderr, "#"); } switch (ip_proto) { </code></pre> <p>Then, filtering is a piece of cake:</p> <pre><code>while (&lt;CMD&gt;) { s/($keyword)/\e[93m$1\e[0m/g; print; } </code></pre>
<p>See the script at <a href="http://www.mail-archive.com/linux-il@cs.huji.ac.il/msg52876.html" rel="nofollow noreferrer">this post to Linux-IL where someone asked a similar question</a>. It's written in Perl and uses the CPAN Term::ANSIColor module.</p>
26,315
<p>I've seen some examples of C++ using template template parameters (that is templates which take templates as parameters) to do policy-based class design. What other uses does this technique have?</p>
<p>I think you need to use template template syntax to pass a parameter whose type is a template dependent on another template like this:</p> <pre><code>template &lt;template&lt;class&gt; class H, class S&gt; void f(const H&lt;S&gt; &amp;value) { } </code></pre> <p>Here, <code>H</code> is a template, but I wanted this function to deal with all specializations of <code>H</code>.</p> <p><strong>NOTE</strong>: I've been programming c++ for many years and have only needed this once. I find that it is a rarely needed feature (of course handy when you need it!).</p> <p>I've been trying to think of good examples, and to be honest, most of the time this isn't necessary, but let's contrive an example. Let's pretend that <code>std::vector</code> <em>doesn't</em> have a <code>typedef value_type</code>. </p> <p>So how would you write a function which can create variables of the right type for the vectors elements? This would work.</p> <pre><code>template &lt;template&lt;class, class&gt; class V, class T, class A&gt; void f(V&lt;T, A&gt; &amp;v) { // This can be "typename V&lt;T, A&gt;::value_type", // but we are pretending we don't have it T temp = v.back(); v.pop_back(); // Do some work on temp std::cout &lt;&lt; temp &lt;&lt; std::endl; } </code></pre> <p><strong>NOTE</strong>: <code>std::vector</code> has two template parameters, type, and allocator, so we had to accept both of them. Fortunately, because of type deduction, we won't need to write out the exact type explicitly.</p> <p>which you can use like this:</p> <pre><code>f&lt;std::vector, int&gt;(v); // v is of type std::vector&lt;int&gt; using any allocator </code></pre> <p>or better yet, we can just use:</p> <pre><code>f(v); // everything is deduced, f can deal with a vector of any type! </code></pre> <p><strong>UPDATE</strong>: Even this contrived example, while illustrative, is no longer an amazing example due to c++11 introducing <code>auto</code>. Now the same function can be written as:</p> <pre><code>template &lt;class Cont&gt; void f(Cont &amp;v) { auto temp = v.back(); v.pop_back(); // Do some work on temp std::cout &lt;&lt; temp &lt;&lt; std::endl; } </code></pre> <p>which is how I'd prefer to write this type of code.</p>
<p>In the solution with variadic templates provided by pfalcon, I found it difficult to actually specialize the ostream operator for std::map due to the greedy nature of the variadic specialization. Here's a slight revision which worked for me:</p> <pre><code>#include &lt;iostream&gt; #include &lt;vector&gt; #include &lt;deque&gt; #include &lt;list&gt; #include &lt;map&gt; namespace containerdisplay { template&lt;typename T, template&lt;class,class...&gt; class C, class... Args&gt; std::ostream&amp; operator &lt;&lt;(std::ostream&amp; os, const C&lt;T,Args...&gt;&amp; objs) { std::cout &lt;&lt; __PRETTY_FUNCTION__ &lt;&lt; '\n'; for (auto const&amp; obj : objs) os &lt;&lt; obj &lt;&lt; ' '; return os; } } template&lt; typename K, typename V&gt; std::ostream&amp; operator &lt;&lt; ( std::ostream&amp; os, const std::map&lt; K, V &gt; &amp; objs ) { std::cout &lt;&lt; __PRETTY_FUNCTION__ &lt;&lt; '\n'; for( auto&amp; obj : objs ) { os &lt;&lt; obj.first &lt;&lt; ": " &lt;&lt; obj.second &lt;&lt; std::endl; } return os; } int main() { { using namespace containerdisplay; std::vector&lt;float&gt; vf { 1.1, 2.2, 3.3, 4.4 }; std::cout &lt;&lt; vf &lt;&lt; '\n'; std::list&lt;char&gt; lc { 'a', 'b', 'c', 'd' }; std::cout &lt;&lt; lc &lt;&lt; '\n'; std::deque&lt;int&gt; di { 1, 2, 3, 4 }; std::cout &lt;&lt; di &lt;&lt; '\n'; } std::map&lt; std::string, std::string &gt; m1 { { "foo", "bar" }, { "baz", "boo" } }; std::cout &lt;&lt; m1 &lt;&lt; std::endl; return 0; } </code></pre>
26,277
<p>I'm building a photo gallery and what I would like to do is make it so that as the user rolls over an image (let's say for the purposes of this question it's a picture of an apple), all the other images of apples on the page also show their "over" state. </p> <p>Any and all help would be greatly appreciated, and thank you for your time in advance! </p>
<p>You could add the 'type' of the image as a class. For example an apple will be:</p> <pre><code>&lt;img src='' class='apple fruit red' /&gt; </code></pre> <p>You can have as many space separated classes as you want.</p> <p>Then add the following handler:</p> <pre><code>$(".apple").mouseover(function() { $(".apple").addClass("overState"); }); </code></pre> <p>You need to define in your CSS the overState. On mouseout you must remove the class.</p>
<p>If these are links (anchor tag) you don't need jQuery to do this. You can use :hover in CSS.</p> <pre><code>a.apple:hover img { /* whatever you want to change here */ } </code></pre> <p>EDIT: Ignore me. This won't change all apple elements on the page at the same time. That's what I get for perusing SO late at night when I'm sleepy.</p>
49,362
<p>I want to delete a folder that contains thousands of files and folders. If I use Windows Explorer to delete the folder it can take 10-15 minutes (not always, but often). Is there a faster way in Windows to delete folders? </p> <p>Other details:</p> <ul> <li>I don't care about the recycle bin.</li> <li>It's an NTFS drive.</li> </ul>
<h3>Using Windows Command Prompt:</h3> <pre><code>rmdir /s /q folder </code></pre> <h3>Using Powershell:</h3> <pre><code>powershell -Command &quot;Remove-Item -LiteralPath 'folder' -Force -Recurse&quot; </code></pre> <p>Note that in more cases <code>del</code> and <code>rmdir</code> wil leave you with leftover files, where Powershell manages to delete the files.</p>
<p>Try <kbd>Shift</kbd> + <kbd>Delete</kbd>. Did 24.000 files in 2 minutes for me.</p>
22,602
<p>Are there any tools to assist with the internationalization of Strings within JSP files?</p> <p>Most IDEs (for example, <a href="http://www.netbeans.org" rel="nofollow noreferrer">NetBeans</a>) offer such a feature for Java code. However, in the case of NetBeans, no such feature exists for JSP files.</p> <p>With <a href="http://www.gnu.org/software/gettext/" rel="nofollow noreferrer">gettext</a>, for example, there is are various tools out there that assist with extracting text Strings from code. Something similar for JSP would be great!</p>
<p>I hope no-one minds if I bump an old question...</p> <p>When faced with the same problem, I put together (a) a method for localising strings in JSPs in the Gettext style (keeping English in the source JSP) and (b) an Ant task which can find such strings in JSPs and generate a Gettext POT file.</p> <p>(a) is provided by WebGettext, which provides an EL resolver for expressions such as <code>${messages["Hello {0}"][username]}</code>. The resolver looks up a translation, for the requesting user's locale, and substitutes any parameters using MessageFormat.</p> <p>(b) is provided by Regex2PotTask, which is a bit like xgettext but for a configurable regex expression rather than C, Java, Perl, etc, function calls such as gettext("my string").</p> <p><a href="https://fedorahosted.org/tennera/" rel="nofollow noreferrer">Tennera's home page</a> is here.</p> <p><a href="https://fedorahosted.org/tennera/browser/trunk/webgettext-example" rel="nofollow noreferrer">Example JSP project</a> - see RUNNING.txt</p> <p>It's all a bit rough at present, but I think the basics are all there. If someone expresses interest, I might even be motivated to document it "properly"...</p>
<p>I found this as a <a href="http://www.eclipsezone.com/eclipse/forums/t84478.rhtml" rel="nofollow noreferrer">workaround solution</a> to this problem. Its far from ideal, but allows you to search all Strings with an IDE. Paraphrashing the solution:</p> <ol> <li>JSPs compile to servlets, so find the corresponding servlet class for each JSP on your file system. In the case of Tomcat this would be the 'work' directory.</li> <li>Import the associated servlet .java file into the IDE, and then use the IDE's regular internationalization tool: <em>Externalize strings...</em> (Eclipse) / <em>Internationalization wizard</em> (NetBeans).</li> </ol>
24,110
<p>We have a large collection of command-line utilities that we write ourselves and use frequently. At the moment, testing them is very cumbersome and consequently, we don't do as much testing as we aught to.</p> <p>I am wondering if anyone can suggest good techniques or tools for doing a good job of this kind of thing.</p> <p>This is UNIX.</p>
<p>I recommend structuring your command line tool's code so that the command line utility is a client to a library of functions and/or classes. </p> <p>Rather than simply using std::cout to print output, have the libraries function take an ostream reference that defaults to std::cout. When you are testing, provide a std::stringstream to collect the output. </p> <p>Finally, simply compare your utility's output with expected results using your favorite unit testing framework. </p> <p>(I apologize for the C++ specific example... I'm sure there are ways to do similar things in other languages too). </p>
<p>You can do this from a batch file oder windows scripting host.</p> <p>But i promise to use a task scheduler like (<a href="http://www.splinterware.com/products/wincron.htm" rel="nofollow noreferrer">http://www.splinterware.com/products/wincron.htm</a>) or other free/professional software.</p> <p>There you can easy copy/paste the commandline-parameters which you should vary on, when you wanna test your software for about many 100 times?!</p>
45,998
<p>I am considering writing a simple database application for my wife, but I'm hung up on good programming practice, and want to have a human readable source for storing the database schema. </p> <p>Only, I don't know of any tools for the job, and I can't believe that they don't exist---probably I just don't know what to ask google, but I'm not finding them.</p> <p>So, what libraries or other tools out there to support reading database schema from plain text files.</p> <hr> <p>To invenetix's question: I expect to generate the database creation code at build-time or to include the schema description in the release and build the database from the description at run-time. Draemon's suggestion would be fine, but I don't want to be locked into a predetermined RDBMS if I can help it.</p> <p>Perhaps I should say that I've used databases in programming projects before, but never been responsible for the creation code.</p> <p>Possible I'm over engineering the problem at this point.</p>
<p>Just use SQL. SQL is not only a query language but a DDL (data definition language). If, for example you are using mysql; you can design your schema however you want, run mysqldump which will create an SQL file with DDL statements. Tidy up the schema, then you can load the schema any time you like by sourcing the SQL file. Personally, I just write the SQL schema in a text editor and load it into mysql.</p> <p>This will work for mysql, postgresql, oracle, and probably any other DB.</p>
<p>I'm unable to give comments yet, but if I understand this right, you want an application or library to build a schema dependent on the data provided in the text file?</p> <p>Could you provide a sample work flow in which you're seeking to accomplish? Which step is the one you're having the issue with?</p>
45,169
<p>I have a simple SQL 'Select' query, and I'd like to dump the results into an Excel file. I'm only able to save as .csv and converting to .xls creates some super ugly output. In any case, as far as I can tell (using Google) this doesn't seem to be so straight forward. Any help would be greatly appreciated.</p>
<p>Use "External data" from Excel. It can use ODBC connection to fetch data from external source: Data/Get External Data/New Database Query</p> <p>That way, even if the data in the database changes, you can easily refresh.</p>
<p>you can right click on a grid of results in SQL server, and choose save as CSV. you can then you can import this into Excel. </p> <p>Excel gives you a import wizard, ensure you select comma delimited. it works fine for me when i needed to import 50k+ records into excel.</p>
11,330
<p>I need a Project management tool that works in Linux, and has Gantt charts.</p> <ol> <li>It doesn't have to be free, just not expensive.</li> <li>I don't care how it stores the information I give it, as long as I can access it.</li> <li>I must be able to <strong>print</strong> the Gantt charts.</li> <li>Must work in Linux.</li> </ol> <p>With those requirements, what can you recommend?</p> <p>TheObserver asked a windows specific version of this question <a href="https://stackoverflow.com/questions/151787/recommended-chartingreportingdashboard-tool">here</a>. </p> <p>Thanks for the help everyone.</p>
<p><a href="http://live.gnome.org/Planner" rel="noreferrer">Planner</a>, and <a href="http://opensched.sourceforge.net/" rel="noreferrer">OpenSched</a>, in that order. There are some decent online Gantt (this is the correct spelling) chart tools online as well, usually integrated within a project management or bug-tracking web app or software package.</p>
<p>The answers to <A href="https://stackoverflow.com/questions/171809/is-there-any-latex-package-for-drawing-gantt-diagrams"><a href="https://stackoverflow.com/questions/171809/is-there-any-latex-package-for-drawing-gantt-diagrams">Is there any LaTeX package for drawing Gantt diagrams?</a></A>. may be viable.</p>
23,328
<p>As the title suggests. I want to be able to change the label of a single field in the admin application. I'm aware of the Form.field attribute, but how do I get my Model or ModelAdmin to pass along that information?</p>
<p>the <a href="http://docs.djangoproject.com/en/dev/topics/db/models/#verbose-field-names" rel="noreferrer">verbose name</a> of the field is the (optional) first parameter at field construction.</p>
<p>Use <strong>&quot;verbose_name&quot;</strong> to change <strong>a field name</strong> as the example below.</p> <p><strong>&quot;models.py&quot;</strong>:</p> <pre class="lang-py prettyprint-override"><code>from django.db import models class MyModel(models.Model): # Here name = models.CharField(max_length=255, verbose_name=&quot;My Name&quot;) </code></pre>
47,660
<p>I have a web server that runs my web application.</p> <p>If I want to outsource my email to another provider, is it possible if they are on their on network/data center?</p>
<p>Yes. To do this, you will need access to the DNS records for your domain. The MX record allows you to set up a mail server that's separate from the web server.</p> <p>Google offers a service that will manage your domain's email through GMail, and the instructions on how to reconfigure your DNS for this service can be found <a href="http://www.google.com/support/a/bin/answer.py?answer=33352&amp;src=top5&amp;lev=index" rel="noreferrer">here</a>.</p>
<p>Google Apps does just that.</p>
32,921
<p>Like the title says: Can reflection give you the name of the currently executing method.</p> <p>I'm inclined to guess not, because of the Heisenberg problem. How do you call a method that will tell you the current method without changing what the current method is? But I'm hoping someone can prove me wrong there.</p> <p><strong>Update:</strong> </p> <ul> <li>Part 2: Could this be used to look inside code for a property as well? </li> <li>Part 3: What would the performance be like?</li> </ul> <p><strong>Final Result</strong><br> I learned about MethodBase.GetCurrentMethod(). I also learned that not only can I create a stack trace, I can create only the exact frame I need if I want. </p> <p>To use this inside a property, just take a .Substring(4) to remove the 'set_' or 'get_'.</p>
<p>For non-<code>async</code> methods one can use</p> <pre><code>System.Reflection.MethodBase.GetCurrentMethod().Name; </code></pre> <p><a href="https://learn.microsoft.com/en-us/dotnet/api/system.reflection.methodbase.getcurrentmethod" rel="noreferrer">https://learn.microsoft.com/en-us/dotnet/api/system.reflection.methodbase.getcurrentmethod</a></p> <p>Please remember that for <code>async</code> methods it will return "MoveNext".</p>
<pre><code>new StackTrace().ToString().Split("\r\n",StringSplitOptions.RemoveEmptyEntries)[0].Replace("at ","").Trim() </code></pre>
6,584
<p>I'm using php and I have the following code to convert an absolute path to a url.</p> <pre><code>function make_url($path, $secure = false){ return (!$secure ? 'http://' : 'https://').str_replace($_SERVER['DOCUMENT_ROOT'], $_SERVER['HTTP_HOST'], $path); } </code></pre> <p>My question is basically, is there a better way to do this in terms of security / reliability that is portable between locations and servers?</p>
<p>The <a href="http://shiflett.org/blog/2006/mar/server-name-versus-http-host" rel="nofollow noreferrer">HTTP_HOST variable is not a reliable or secure value</a> as it is also being sent by the client. So be sure to validate its value before using it.</p>
<p>I think this is the wrong approach.</p> <p>URLs in a HTML support relative locations. That is, you can do <code>&lt;A href="filename.php"&gt;link&lt;/a&gt;</code> to refer to a page that has the same path in its URL as the corrent page. You can also do <code>&lt;a href="/dir/filename.php"&gt;link&lt;/a&gt;</code> to provide a full path to the same website. These two tricks mean your website code doesn't really need to know where it is to provide working URLs.</p> <p>That said, you might need some tricks so you can have one website on <code>http://www.example.com/dev/site.php</code> and another on <code>http://www.example.com/testing/site.php</code>. You'll need some code to figure out which directory prefix is being used, but you can use a configuration value to do that. By which I mean a value that belongs to that (sub-)site's configuration, not the version-controlled code!</p>
48,872
<p>I could not find any pointers on how to create a menubar icon on OSX using wx. I originally thought that the wxTaskBarIcon class would do, but it actually creates an icon on the Dock. On Windows, wxTaskBarIcon creates a Systray icon and associated menu, and I would think that on mac osx it would create a menubar icon, I guess not.</p>
<p>You have to set <code>wxTaskBarIconType</code> to <code>STATUSITEM</code>, not <code>DOCK</code>. The Cocoa APIs for this are <code>NSStatusBar</code> and <code>NSStatusItem</code>; <a href="http://trac.wxwidgets.org/attachment/ticket/6860/taskbar.diff" rel="nofollow noreferrer">here's the code in wxWidgets that calls to them</a>.</p>
<p>As of wxPython 2.9.2.0 <code>wx.TaskBarIcon</code> will create a menubar icon now instead on OSX, so long as you call <code>SetIcon</code>.</p>
17,587
<p>I have an application for Tomcat which needs to offer/consume web services. Since Java web services are a nightmare (xml, code generation, etc.) compared with what is possible in Python, I would like to learn from your experience using jython instead of java for offerring/consuming web services.</p> <p>What I have done so far involves adapting <a href="http://pywebsvcs.sourceforge.net/" rel="noreferrer">http://pywebsvcs.sourceforge.net/</a> to <a href="http://www.jython.org" rel="noreferrer">Jython</a>. I still get errors (namespaces, types and so), although some of it is succesful for the simplest services.</p>
<p>I've put together more details on how to use webservices in jython using axis. Read about it here: <a href="http://www.fishandcross.com/blog/?p=503" rel="nofollow noreferrer">How To Script Webservices with Jython and Axis</a>.</p>
<p><a href="http://www.jython.org/docs/api/org/python/util/PyServlet.html" rel="nofollow noreferrer">PyServlet</a> helps you configure Tomcat to serve up Jython scripts from a URL. You could use this is a "REST-like" way to do some basic web services without much effort. (It is also described <a href="http://www.informit.com/articles/article.aspx?p=26865&amp;seqNum=6" rel="nofollow noreferrer">here</a>.) </p> <p>We used a similar home grown framework to provide a variety of data services in a large multiple web application very successfully.</p>
14,109
<p>Does anybody know if there is a built-in function in Mathematica for getting the lhs of downvalue rules (without any holding)? I know how to write the code to do it, but it seems basic enough for a built-in</p> <p>For example:</p> <pre><code>a[1]=2; a[2]=3; </code></pre> <p><code>BuiltInIDoNotKnowOf[a]</code> returns <code>{1,2}</code></p>
<p>This is like <code>keys()</code> in Perl and Python and other languages that have built in support for hashes (aka dictionaries). As your example illustrates, Mathematica supports hashes without any special syntax. Just say <code>a[1] = 2</code> and you have a hash. [1] To get the keys of a hash, I recommend adding this to your init.m or your personal utilities library:</p> <pre><code>keys[f_] := DownValues[f][[All,1,1,1]] (* Keys of a hash/dictionary. *) </code></pre> <p>(Or the following pure function version is supposedly slightly faster:</p> <pre><code>keys = DownValues[#][[All,1,1,1]]&amp;; (* Keys of a hash/dictionary. *) </code></pre> <p>)</p> <p>Either way, <code>keys[a]</code> now returns what you want. (You can get the values of the hash with <code>a /@ keys[a]</code>.) If you want to allow for higher arity hashes, like <code>a[1,2]=5; a[3,4]=6</code> then you can use this:</p> <pre><code>SetAttributes[removeHead, {HoldAll}]; removeHead[h_[args___]] := {args} keys[f_] := removeHead @@@ DownValues[f][[All,1]] </code></pre> <p>Which returns <code>{{1,2}, {3,4}}</code>. (In that case you can get the hash values with <code>a @@@ keys[a]</code>.)</p> <p>Note that <code>DownValues</code> by default sorts the keys, which is probably not a good idea since at best it takes extra time. If you want the keys sorted you can just do <code>Sort@keys[f]</code>. So I would actually recommend this version:</p> <pre><code>keys = DownValues[#,Sort-&gt;False][[All,1,1,1]]&amp;; </code></pre> <p>Interestingly, there is no mention of the <code>Sort</code> option in the <code>DownValues</code> documention. I found out about it from an old post from Daniel Lichtblau of Wolfram Research. (I confirmed that it still works in the current version (7.0) of Mathematica.)</p> <hr/> <p>Footnotes:</p> <p>[1] What's really handy is that you can mix and match that with function definitions. Like:</p> <pre><code>fib[0] = 1; fib[1] = 1; fib[n_] := fib[n-1] + fib[n-2] </code></pre> <p>You can then add memoization by changing that last line to</p> <pre><code>fib[n_] := fib[n] = fib[n-1] + fib[n-2] </code></pre> <p>which says to cache the answer for all subsequent calls.</p>
<p>This seems to work; not sure how useful it is, though:</p> <pre><code>a[1] = 2 a[2] = 3 a[3] = 5 a[6] = 8 Part[DownValues[a], All, 1, 1, 1] </code></pre>
16,392
<p>I have a Windows application (VS2005/C#) which comes in two versions, Enterprise and Pro. In the Pro version, some of the features and menus are disabled. Currently, I'm doing this by commenting out the disabling code to create the Enterprise version, then I copy each executable file to another location. Obviously this process is fraught with peril... :)</p> <p>I would like to have two folders for my two executable files, and visual studio should put the code to disable the features in the pro version, and put each in their correct folders. I have installer projects that would pick up the files from there and make the installers for the two versions. That part is already working, but I'm manually copying the two executables into the right folders before I build the installers. So it sucks...</p> <p>What I'd like to do is something like this:</p> <pre><code>#ifdef PROVERSION part1.disable(); part2.disable(); #endif </code></pre> <p>Is this possible with Visual studio???</p> <p>Note, my overall goal is to automate the process of creating the two installers.</p>
<p>from the BUILD menu, select configuration manager option</p> <p>on the active solution configuration dropdown select "new"</p> <p>create two new 'configurations' one for PRO and one for ENTERPRISE</p> <p>close the configuration manager.</p> <p>open the project properties (from the project context menu) select the build tab</p> <p>select the PRO configuration (from the CONFIGURATION dropdown) </p> <p>enter your compilation constant "PROVERSION" into the conditional compilation symbols textbox. </p> <p>now all you have to do is select the config you want to build from the config dropdown on the main toolbar and then do your build.</p> <p>when you build the PRO using the PRO configuration the compiler pragmas (#IF PROVERSION) scattered throughout your code will include the code limiting your feature set.</p> <p>you may also consider setting a ENTERPRISE constant for the ENTERPRISE configuration if you want to specifically include ENTERPRISE features in an ENTERPRISE build (versus disabling enterprise features in a PRO build)</p>
<p>Why not create a separate assembly that enables / disables the features as required? Then just include the appropriate assembly for a particular version...</p>
35,863
<p>We had a bad day yesterday. One of our Domain Admins deleted an OU containing 700+ users and the same amount of computers as well as assorted other useful things like groups etc.</p> <p>We restored from a backup, but it wasn't pretty.</p> <p>I know that ADUC asks you if you're sure etc... but I'd like it if it was not possible to delete this particular OU without going into something like ADSIEdit to set it "allowable" for deletion - thereby not allowing people to delete without actually opening a new app and specifically indicating that "YES - I know what I'm doing". This would have the added benefit of stopping accidental miscoding from deleting critical AD objects.</p> <p>Any such attribute or method that you folks could think of?</p>
<p>There is a feature in AD for Win2k3 and higher to mark an object to prevent accidental deletion. This check box on the object actually changes the underlying permissions for you to remove delete permissions. Therefore it is not tool specific and must be respected by other tools (like powershell and vbscript).</p>
<p>You could deny the Delete privalge from Administrators through Delegation at the root level and then you would need to be an enterprise admin to perform deletions. Ensure that no admins are in the Enterprise Admins group for day-to-day usage.</p>
31,362
<p>I have multiple Network Interface Cards on my computer, each with its own IP address.</p> <p>When I use <code>gethostbyname(gethostname())</code> from Python's (built-in) <code>socket</code> module, it will only return one of them. How do I get the others?</p>
<p>Use the <a href="https://pypi.org/project/netifaces/" rel="noreferrer"><code>netifaces</code></a> module. Because networking is complex, using netifaces can be a little tricky, but here's how to do what you want:</p> <pre><code>&gt;&gt;&gt; import netifaces &gt;&gt;&gt; netifaces.interfaces() ['lo', 'eth0'] &gt;&gt;&gt; netifaces.ifaddresses('eth0') {17: [{'broadcast': 'ff:ff:ff:ff:ff:ff', 'addr': '00:11:2f:32:63:45'}], 2: [{'broadcast': '10.0.0.255', 'netmask': '255.255.255.0', 'addr': '10.0.0.2'}], 10: [{'netmask': 'ffff:ffff:ffff:ffff::', 'addr': 'fe80::211:2fff:fe32:6345%eth0'}]} &gt;&gt;&gt; for interface in netifaces.interfaces(): ... print netifaces.ifaddresses(interface)[netifaces.AF_INET] ... [{'peer': '127.0.0.1', 'netmask': '255.0.0.0', 'addr': '127.0.0.1'}] [{'broadcast': '10.0.0.255', 'netmask': '255.255.255.0', 'addr': '10.0.0.2'}] &gt;&gt;&gt; for interface in netifaces.interfaces(): ... for link in netifaces.ifaddresses(interface)[netifaces.AF_INET]: ... print link['addr'] ... 127.0.0.1 10.0.0.2 </code></pre> <p>This can be made a little more readable like this:</p> <pre><code>from netifaces import interfaces, ifaddresses, AF_INET def ip4_addresses(): ip_list = [] for interface in interfaces(): for link in ifaddresses(interface)[AF_INET]: ip_list.append(link['addr']) return ip_list </code></pre> <p>If you want IPv6 addresses, use <code>AF_INET6</code> instead of <code>AF_INET</code>. If you're wondering why <code>netifaces</code> uses lists and dictionaries all over the place, it's because a single computer can have multiple NICs, and each NIC can have multiple addresses, and each address has its own set of options.</p>
<p>You should directly obtain all IP configured IP addresses, e.g. by running ifconfig and parsing its output (it's also possible to do what <a href="http://pypi.python.org/pypi/netifaces/0.3" rel="nofollow noreferrer">ifconfig does directly in Python</a>, <a href="https://stackoverflow.com/questions/259389/finding-an-ip-from-an-interface-name">see how it is done in C</a>). If you want host names, use gethostbyaddr.</p>
34,037
<p>I'm trying to build a hoverable Jquery tooltip. This tooltip should appear when I hover over some element, and stay put if I choose to hover over the tooltip itself too. The tooltip should disappear only if I hover away from the original element or from the tooltip body.</p> <p>Based on an example I found, I managed to create this behavior, but since I'm new to Jquery, I'd be glad to hear your comments about improving the function.</p> <h2>The code:</h2> <pre><code>&lt;!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"&gt; &lt;html xmlns="http://www.w3.org/1999/xhtml"&gt; &lt;head&gt; &lt;script src="jquery-1.2.6.min.js"&gt;&lt;/script&gt; &lt;style&gt; #tooltip{ position:absolute; border:1px solid #333; background:#f7f5d1; padding:2px 5px; color:#333; display:none; text-align: left; } &lt;/style&gt; &lt;/head&gt; &lt;body&gt; &lt;script type="text/javascript"&gt; jQuery.fn.extend({ 'tooltip': function(text){ xOffset = 10; yOffset = 20; var that = this; $(this).mouseover(function(e){ this.t = text; $("body").append("&lt;div id='tooltip'&gt;"+ this.t +"&lt;/div&gt;"); $("#tooltip") .css('position', 'absolute') .css("top",(e.pageY - xOffset) + "px") .css("left",(e.pageX + yOffset) + "px") .fadeIn("fast"); }); $(this).mouseout(function(){ that.hide_ff = setTimeout('$("#tooltip").hidetooltip()', 1000); $("#tooltip").hover(function(){ clearTimeout (that.hide_ff); }, function(){ $("#tooltip").hidetooltip() }); //$("#tooltip").hidetooltip() }); $(this).mousemove(function(e){ $("#tooltip") .css("top",(e.pageY - xOffset) + "px") .css("left",(e.pageX + yOffset) + "px"); }); }, 'hidetooltip': function() { var that = this; $(this).remove(); if (that.hide_ff) { clearTimeout (that.hide_ff); } } }); &lt;/script&gt; &lt;a id="fff"&gt;ToolTip&lt;/a&gt; &lt;div id="tooltip_share_text" style="display:none"&gt; &lt;div style="width: 100px;"&gt; This is a Tooltip. &lt;br/&gt; &lt;a href="javascript:void(0)" onclick="alert('boo')"&gt; Click Me&lt;/a&gt; &lt;/div&gt; &lt;/div&gt; &lt;script type="text/javascript"&gt; $(document).ready(function() { $("#fff").tooltip($('#tooltip_share_text').html()); }); &lt;/script&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <hr> <p>Two things bother me most:</p> <ol> <li>I needed to extend Jquery with 2 function (tooltip and hidetooltip), i would like to achieve the same behavior with only one extension but I didn't succeed in accomplishing this.</li> <li>The use I made of "that.hide_ff" just doesn't seem right. Once again, I think this variable should belong to a "tooltip" object, but if I am not mistaken it is attached to the Jquery object itself.</li> </ol> <p>In addition, I would be happy to hear any other improvements...</p> <p>Thanks in advance, Gordi</p>
<p>There is a <a href="http://bassistance.de/jquery-plugins/jquery-plugin-tooltip/" rel="nofollow noreferrer">tooltip plugin</a> for JQuery. If you'd rather roll your own, I'm sure you can get ideas by looking at what they have done.</p>
<p>I'm not sure if you're still interested in this... it's been almost a year o.O</p> <p>But I modified your code a little:</p> <ul> <li>I got rid of the hidetooltip (the extra extension)</li> <li>Using the that.hide_ff is fine, so I didn't change it</li> <li>The tooltip pops up at the end of the link and doesn't move with the mouse - it looks cleaner I think.</li> <li>Switched the xOffset and yOffset</li> <li>Commented out the original mousemove code so you can change it back if you don't like it.</li> </ul> <pre> jQuery.fn.extend({ 'tooltip': function(text){ xOffset = 10; yOffset = 20; var that = this; $(this).mouseover(function(e){ this.t = text; $("body").append(""+ this.t +""); $("#tooltip") .css('position', 'absolute') .css("top",(this.offsetTop + yOffset) + "px") /* .css("top",(e.pageY - xOffset) + "px") */ .css("left",(this.offsetLeft + this.offsetWidth) + "px") /* .css("left",(e.pageX + yOffset) + "px") */ .fadeIn("fast"); }); $(this).mouseout(function(){ that.hide_ff = setTimeout('$("#tooltip").remove()', 500); $("#tooltip").hover(function(){ clearTimeout (that.hide_ff); }, function(){ $("#tooltip").remove(); } ); }); /* $(this).mousemove(function(e){ $("#tooltip") .css("top",(e.pageY - xOffset) + "px") .css("left",(e.pageX + yOffset) + "px"); }); */ } }); </pre>
31,759
<p>I've got an open-source app that is hosted at code.google.com. It is cross platform ( Linux / Windows / Mac ). I uploaded the code initially from a WinXP machine using TortoiseSVN and it seems that none of the "configure" batch files that are used for the linux build have their "execute" bits set. </p> <p>What would be the easiest way to set these for the files that need them? Using TortoiseSVN would be easier, I suppose, but if that can't be used, then I could also use the command line SVN on my linux machine.</p>
<p>Here's how to do it on the command line:</p> <pre><code>for file in `find . -name configure`; do svn ps svn:executable yes ${file} done </code></pre> <p>Or for just one file (<code>configure</code> is the filename here):</p> <pre><code>svn ps svn:executable yes configure </code></pre>
<p>Method for restoring executable permissions that are lost during svn import:</p> <p>copy permissions from your original source that you used during svn import (current dir to version1):</p> <pre><code>find . -type f | xargs -I {} chmod --reference {} ../version1/{} </code></pre> <p>then set svn:executable for all executables using the following shell script:</p> <pre><code>for file in `find . -executable -type f`; do svn ps svn:executable yes ${file} done </code></pre>
12,894
<p>Just wondering</p>
<p>I made them work as I wanted once ! That was cool!</p>
<p>Ian P, Mind to elaborate? AFAIK you don't need to use threading to solve a maze, unless, of course the maze is so complicated that the wait time becomes so unbearable that you have to add in status bar so that the users would not get bored and thought that your program hangs.</p>
13,629
<p>How do I get the latest version of my solution recursively like its done in the solution explorer context menu of Visual Studio? I want to do this from the command line or via a macro. I'm trying to automate a part of my daily routine by using a set of batch files. I am sure a lot of developers would love to have something like this.</p> <p><code>tf get</code> only gets contents of a folder recursively (not solution). It does not look at project dependencies and so on. That won't work.</p>
<p>TFS has a <a href="http://msdn.microsoft.com/en-us/library/bb130146(VS.80).aspx" rel="nofollow noreferrer">.Net SDK</a> that allows you to create your own custom programs that interact with a TFS Server. You could write a small program that performs the task you need:</p> <pre><code>TeamFoundationServer tfs = TeamFoundationServerFactory.GetServer("MyServer"); VersionControlServer vcs = (VersionControlServer)tfs.GetService(typeof(VersionControlServer)); WorkSpace[] myWorkSpaces = vcs.QueryWorkSpaces("MyWorkSpaceName", "MyLoginName", "MyComputer"); myWorkSpaces[0].Get(VersionSpec.Latest, GetOptions.GetAll); </code></pre>
<p>I know you mentioned batch files, but let me throw something else out for you.</p> <p>I'm going to guess that you are using the 2005 version of TFS. 2008 has all of the scheduling stuff built in. </p> <p>However, you could also use <a href="http://confluence.public.thoughtworks.org/display/CCNET/Welcome+to+CruiseControl.NET" rel="nofollow noreferrer">CruiseControl.net</a> to do scheduled builds for you. I've used both TFS 2008 and CruiseControl and they both seem to work just fine.</p>
5,439
<p>I am getting an vba error 3271; Invalid property value. This happens when trying to append a memo field in a querydef. Any ideas on how to get around this?</p> <p>Example:</p> <pre><code>public sub TestMemoField Dim qdf As QueryDef Set qdf = CurrentDb.QueryDefs("AppendRecord") qdf.Parameters("@SomeBigText").value = string(1000,"A") qdf.Execute end sub </code></pre> <p>Thanks in advance.</p>
<p>Apparently you cannot have a parameter longer than 255 characters ( <a href="http://support.microsoft.com/kb/275116" rel="nofollow noreferrer">http://support.microsoft.com/kb/275116</a> ). </p> <p>It is possible to use a recordset, or to use:</p> <pre><code>qdf.SQL="INSERT INTO Sometable (SomeField) Values('" &amp; String(1000, "A") &amp; "')" </code></pre>
<p>Um, what are you trying to do? Why are you using parameters? Why not just execute SQL in code, like this:</p> <pre><code>Public Sub TestMemoField Dim strSQL As String strSQL = "UPDATE MyTable SET MyField='" &amp; String(1000,"A") &amp; "'" CurrentDb.Execute strSQL, dbFailOnError End Sub </code></pre> <p>I don't use parameters in saved queries <em>except</em> when I need to pull a value from a control on a form to be used in a saved query.</p> <p>Now, my answer might not be good if your back end is not Jet or if there's something about the actual criteria and structure of your saved query that makes it important to use a saved query instead of simply using on-the-fly SQL. But you've provided virtually no information (including omitting the SQL of the querydef you're executing), so it's rather difficult to supply any kind of helpful answer.</p>
40,541
<p>I would like to avoid using native libaries if at all possible. Surely there is a better way to solve this issue for Linux, Windows and Mac OS X.</p>
<p>Sorry, you're out of luck. You'll need JNI, and it'll be obnoxiously different for different platforms. The base java libraries cover tasks and hardware that are pretty much universal. CD drives weren't and aren't considered so.</p>
<p>You can use the Java Sound API. I believe this is part of java 5. This may allow you to do what you want to do.</p> <p><a href="http://java.sun.com/products/java-media/sound/" rel="nofollow noreferrer">http://java.sun.com/products/java-media/sound/</a> </p> <p>here are some examples:</p> <p><a href="http://www.jsresources.org/examples/" rel="nofollow noreferrer">http://www.jsresources.org/examples/</a></p>
10,036
<p>I have several Google calendars that I'd like to merge and place on my windows desktop using <a href="http://www.samurize.com/" rel="nofollow noreferrer">Samurize</a>. I've tried using Samurize's Page Scraper plugin, but it doesn't appear to be up to the task.</p> <p>I can get Samurize to run a script and place it's output on the desktop, but I'm not sure what the best tools are to do this.</p> <p>All the URLs I have are of the form:</p> <pre><code>http://www.google.com/calendar/feeds/example%40gmail.com/private-REMOVED/basic?futureevents=true&amp;orderby=starttime&amp;sortorder=ascending&amp;singleevents=true </code></pre> <p>So I could fetch them using curl, but then I need to filter them.</p> <p>I want something that looks like:</p> <pre><code>2009 12 02 Event from calendar 1's description 2009 12 03 Event from calendar 2's description 2009 12 04 Event from calendar 1's description 2009 12 05 Event from calendar 3's description 2009 12 06 Event from calendar 1's description </code></pre> <p>However the dates in the calendar feeds are formatted like this:</p> <pre><code>&lt;title type='html'&gt;Event from calendar 1's description&lt;/title&gt;&lt;summary type='html'&gt;When: Fri 5 Dec 2008&amp;lt;br&amp;gt; </code></pre> <p><strong>So how do I filter out the dates and descriptions, and convert the dates?</strong> </p> <p>(I have cygwin installed so something using perl or sed/awk would be perfect as I'm familiar enough with them that I'd be confident about altering them in future, but I'm open to suggestions.)</p>
<p>There is no built-in way to do this. The best way you will be able to get this result is to run a custom tool on the input. This will require a lot of leg work on your part because it will involve parsing the file yourself but you should be able to get this scenario working.</p> <p>Example site for creating a custom generator</p> <p><a href="http://www.drewnoakes.com/snippets/WritingACustomCodeGeneratorToolForVisualStudio/" rel="nofollow noreferrer">http://www.drewnoakes.com/snippets/WritingACustomCodeGeneratorToolForVisualStudio/</a></p>
<p>Sorry, the XAML language service can’t be extended this way either. The best way to do this today is to author a build task. I think you can hook it into the MarkupCompilePass1DependsOn target and it will be invoked automatically when the user saves or changes a XAML file. You still have to scan the file redundantly from us, but you don’t have to wait for an actual build to make this work. This is a direct quote from one of the Microsoft architects who currently is working on the WPF designers.</p>
43,542
<p>I produce server software and have been fine with all Linux environments so far, both for production and as deployment target. However, I want to provide a broader choice of target environments in the future and I'm also planning features that would consume and produce Office documents.</p> <p>As a first step, I am looking for a good way to get a number of MS software products (XP, Vista, Server 2003 &amp; 2008, Office 2000, 2003 &amp; 2007 ...) to put on some VMs in my testing setup, so I can start to play around.</p> <p>So far, I get quite a good impression from what I read about MS's partner program (aka Action Pack). The only thing I'm missing from what the website tells me is older software versions. As I want to mimick possible customers' setups and there's always a lot of people that run older versions, that would be quite important for the testing scenario.</p> <p>Eventually, I'm going to face similar questions with Apple OS X, so if anybody has some hints on that, I'd be glad, too.</p>
<p><code>$#arrayname</code> gives you the index of the last element, so if array <code>@ret</code> has 2 elements then <code>$#ret</code> is 1. </p> <p>And, as noted by Barry Brown, an empty array gives -1.</p> <p>To get the length you can use the array in scalar context:</p> <pre><code>print scalar @ret; </code></pre>
<p>To summarize everyone else, that code is much more legible if written like this:</p> <pre><code>my @ret = someMethod(); return if $DB_ERROR; return unless @ret; </code></pre>
29,879
<p>I have a gdi+ bitmap, and I want to convert bitmap into HBitmap. I write the following code.</p> <pre><code> HBITMAP temp; Color color; img-&gt;GetHBITMAP(color, &amp;temp); </code></pre> <p>But It do not work, How can I get a HBitmap?</p>
<p>I like the <a href="http://developer.yahoo.com/yui/autocomplete/" rel="nofollow noreferrer">Yahoo UI Autocomplete widget</a>. It does not provide the dropdown natively, but a dropdown button can be added with <a href="http://tech.groups.yahoo.com/group/ydn-javascript/message/30178" rel="nofollow noreferrer">a few lines of code</a>.</p>
<p>Surely autocomplete and combo boxes serve two similar, but different purposes:</p> <ul> <li>Autocomplete; select one from a very long list (i.e. too long to scroll through)</li> <li>ComboBox; select one from a relatively short list (i.e. one that is easy to scroll through</li> </ul> <p>How many items do you have in your list?</p>
41,816
<p>I have a <a href="http://www.samurize.com/modules/news/" rel="noreferrer">Samurize</a> config that shows a CPU usage graph similar to Task manager. </p> <p>How do I also display the name of the process with the current highest CPU usage percentage? </p> <p>I would like this to be updated, at most, once per second. Samurize can call a command line tool and display it's output on screen, so this could also be an option.</p> <hr> <p>Further clarification: </p> <p>I have investigated writing my own command line c# .NET application to enumerate the array returned from System.Diagnostics.Process.GetProcesses(), but the Process instance class does not seem to include a CPU percentage property. </p> <p>Can I calculate this in some way?</p>
<p>What you want to get its the instant CPU usage (kind of)...</p> <p>Actually, the instant CPU usage for a process does not exists. Instead you have to make two measurements and calculate the average CPU usage, the formula is quite simple:</p> <blockquote> <p>AvgCpuUsed = [TotalCPUTime(process,time2) - TotalCPUTime(process,time1)] / [time2-time1]</p> </blockquote> <p>The lower Time2 and Time1 difference is, the more "instant" your measurement will be. Windows Task Manager calculate the CPU use with an interval of one second. I've found that is more than enough and you might even consider doing it in 5 seconds intervals cause the act of measuring itself takes up CPU cycles...</p> <p>So, first, to get the average CPU time</p> <pre><code> using System.Diagnostics; float GetAverageCPULoad(int procID, DateTme from, DateTime, to) { // For the current process //Process proc = Process.GetCurrentProcess(); // Or for any other process given its id Process proc = Process.GetProcessById(procID); System.TimeSpan lifeInterval = (to - from); // Get the CPU use float CPULoad = (proc.TotalProcessorTime.TotalMilliseconds / lifeInterval.TotalMilliseconds) * 100; // You need to take the number of present cores into account return CPULoad / System.Environment.ProcessorCount; } </code></pre> <p>now, for the "instant" CPU load you'll need an specialized class:</p> <pre><code> class ProcLoad { // Last time you checked for a process public Dictionary&lt;int, DateTime&gt; lastCheckedDict = new Dictionary&lt;int, DateTime&gt;(); public float GetCPULoad(int procID) { if (lastCheckedDict.ContainsKey(procID)) { DateTime last = lastCheckedDict[procID]; lastCheckedDict[procID] = DateTime.Now; return GetAverageCPULoad(procID, last, lastCheckedDict[procID]); } else { lastCheckedDict.Add(procID, DateTime.Now); return 0; } } } </code></pre> <p>You should call that class from a timer (or whatever interval method you like) for <strong>each process you want to monitor</strong>, if you want all the processes just use the <a href="http://msdn.microsoft.com/en-us/library/1f3ys1f9.aspx" rel="nofollow noreferrer">Process.GetProcesses</a> static method</p>
<p>With PowerShell:</p> <pre><code>Get-Process | Sort-Object CPU -desc | Select-Object -first 3 | Format-Table CPU,ProcessName -hidetableheader </code></pre> <p>returns somewhat like:</p> <pre><code> 16.8641632 System 12.548072 csrss 11.9892168 powershell </code></pre>
7,488
<p>Say I have the following XML...</p> <pre><code>&lt;root&gt; &lt;base&gt; &lt;tent key="1" color="red"/&gt; &lt;tent key="2" color="yellow"/&gt; &lt;tent key="3" color="blue"/&gt; &lt;/base&gt; &lt;bucket&gt; &lt;tent key="1"/&gt; &lt;tent key="3"/&gt; &lt;/bucket&gt; &lt;/root&gt; </code></pre> <p>...what would the XPath be that returns that the "bucket" contains "red" and "blue"?</p>
<p>If you're using XSLT, I'd recommend setting up a key:</p> <pre><code>&lt;xsl:key name="tents" match="base/tent" use="@key" /&gt; </code></pre> <p>You can then get the <code>&lt;tent&gt;</code> within <code>&lt;base&gt;</code> with a particular <code>key</code> using</p> <pre><code>key('tents', $id) </code></pre> <p>Then you can do</p> <pre><code>key('tents', /root/bucket/tent/@key)/@color </code></pre> <p>or, if <code>$bucket</code> is a particular <code>&lt;bucket&gt;</code> element,</p> <pre><code>key('tents', $bucket/tent/@key)/@color </code></pre>
<p>JeniT has the appropriate response / code listed here. You need to create the key before you walk the XML Document, then perform matches against that key.</p>
17,169
<p>The one that ships with IDEA is nothing more than a GWT project creation tool. Is there a better plugin? Is there a standalone GUI editor for GWT?</p>
<p>To answer your question directly, there is no such thing as a Intellij IDEA GUI WYSIWYG editor for GWT for the moment. </p> <p>The most popular/feature complete WYSIWYG editor for GWT is <a href="http://www.instantiations.com/windowbuilder/" rel="noreferrer">Instantiations GWT Designer</a>. It is available only for Eclipse though.</p> <p>The GWT team also provide a <a href="http://code.google.com/intl/nn/webtoolkit/tools.html" rel="noreferrer">list of tools and libraries.</a>. It seem rather incomplete though as it does not list Ext-GWT and GWT-Ext libraries (the most popular widget libraries).</p> <p>Be warned however that most WYSIWYG editor only support the basic widgets of GWT. If you have custom widget, you may not be able to use them in the editor.</p> <hr> <p>[Edit] As of August 2010, Instanciation has been acquired Google</p>
<p>Unfortunately, there really isn't one yet. We're going to have to wait until 2016 when Google takes over the world; everything will be so much easier then! ;)</p>
46,668
<p>we have DotNet webservice which is being called by two clients , one a dotnet client and other a javaclient</p> <p>The problem is java client is taking longer time in processing the results when compared to dotnet client and affecting the performance greatly , i'm using axis in java</p> <p>Is there any know issue with axis regarding my situation here.</p> <p>also the same java client when run on linux platform still longer time to process.</p> <p>please provide me some pointer here</p>
<p>The root cause could be almost anything:--</p> <ul> <li>Slower hardware.</li> <li>Badly written client</li> <li>Long running windows client versus java client started on every invocation.</li> <li>Differences in configuration<ul> <li>XSD validation turned on for java client.</li> <li>JVM memory allocation too small (java -mx 20m --default are generally very small)</li> <li>Full security turned on vs security turned off</li> </li></ul> <li>Differnet network routing -- is javacleint coming through scanning firewall.</li> </ul> <p>Basically you need to get some monitoring tools and measure where the time is going!</p>
<p>Does the Java/Axis client re-use it's connection(s) to the web service/server, or is it initiating a new connection with each request?</p>
42,857
<p>Is there a more efficient way to convert an HTMLCollection to an Array, other than iterating through the contents of said collection and manually pushing each item into an array?</p>
<pre><code>var arr = Array.prototype.slice.call( htmlCollection ) </code></pre> <p>will have the same effect using "native" code.</p> <p><strong>Edit</strong></p> <p>Since this gets a lot of views, note (per @oriol's comment) that the following more concise expression is <em>effectively</em> equivalent:</p> <pre><code>var arr = [].slice.call(htmlCollection); </code></pre> <p>But note per @JussiR's comment, that unlike the "verbose" form, it does create an empty, unused, and indeed unusable array instance in the process. What compilers do about this is outside the programmer's ken.</p> <p><strong>Edit</strong></p> <p>Since ECMAScript 2015 (ES 6) there is also <a href="http://ecma-international.org/ecma-262/8.0/#sec-array.from" rel="noreferrer"><em>Array.from</em></a>:</p> <pre><code>var arr = Array.from(htmlCollection); </code></pre> <p><strong>Edit</strong></p> <p>ECMAScript 2015 also provides the <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax" rel="noreferrer">spread operator</a>, which is functionally equivalent to <code>Array.from</code> (although note that <code>Array.from</code> supports a mapping function as the second argument).</p> <pre><code>var arr = [...htmlCollection]; </code></pre> <p>I've confirmed that both of the above work on <code>NodeList</code>.</p> <p>A performance comparison for the mentioned methods: <a href="http://jsben.ch/h2IFA" rel="noreferrer">http://jsben.ch/h2IFA</a></p>
<p>This is my personal solution, based on the information here (this thread):</p> <pre><code>var Divs = new Array(); var Elemns = document.getElementsByClassName("divisao"); try { Divs = Elemns.prototype.slice.call(Elemns); } catch(e) { Divs = $A(Elemns); } </code></pre> <p>Where $A was described by Gareth Davis in his post:</p> <pre><code>function $A(iterable) { if (!iterable) return []; if ('toArray' in Object(iterable)) return iterable.toArray(); var length = iterable.length || 0, results = new Array(length); while (length--) results[length] = iterable[length]; return results; } </code></pre> <p>If browser supports the best way, ok, otherwise will use the cross browser.</p>
27,503
<p>I have a C# application that is a client to a web service. One of my requirements is to allow capturing the SOAP that I send, so that if there is a problem, I can either fix the bug, or demonstrate that the problem is in the service I am calling.</p> <p>My WebReference proxy service class derives from <code>System.Web.Services.Protocols.SoapHttpClientProtocol</code> as usual. If I had a magic wand, I would make this base class implement an event <code>OnPost</code> that I could handle to write the SOAP into my logs and continue.</p> <p>Short of running a packet sniffer like WireShark, is there an easy way to get this level of logging?</p>
<p>I think what you are looking for is addressed in this question: </p> <p><a href="https://stackoverflow.com/questions/300674/getting-raw-soap-data-from-a-web-reference-client-running-in-aspnet">Getting RAW Soap Data from a Web Reference Client running in ASP.net</a> </p> <p>It looks like a lot of code though.</p>
<p>For some reason Fiddler was not showing my local service calls when using the ASP.NET Development Server that comes with Visual Studio. To get around this I changed the web service Url at runtime to be the Fiddler port, just to capture the SOAP message.</p> <p>You can do this from the Immediate window, for example:</p> <p>myservice.Url = "localhost:8888" (or whatever port you have Fiddler on)</p> <p>I used the SoapUI client to test responses.</p>
39,472
<p>I need to ensure that an application I am developing is accessable and also works with JavaScript turned off. I just need a pointer to assist with the following.</p> <p>I had 3 'chained' select boxes and I wanted JavaScript enabled clients to have a nice Ajax experience. I can easily write the required functionality to populate the chained boxes on the change event of the preceeding select using jQuery and JSON with a WCF service. However what about the non JavaScript client?</p> <p>Would I wrap a submit next to the select and place these inside their own form to post back with a certain action or different querstring parameter? Can the same controller give me a partial JSON response as well as feeding the full HTML response. Can anyone point me to a good demo that utilises both JSON and normal HTTP posts to produce the same result in ASP.NET MVC. All ASP.NET MVC demo/examples I see forget about the non JavaScript enabled client.</p> <p><strong>Update</strong></p> <p>But isn't that true for Ajax calls using the Microsoft Ajax client library if I read it corectly - which I am wanting to avoid and use only jQuery - apologies should have mentioned that.</p> <p>Also I would prefer not to put that noise everywhere in the controllers (reminds me of ispostback from webforms...shudder).</p> <p>It's a shame there is no attribute that I can use on a controller like with [AcceptVerbs(HttpVerbs.Post)] but for content types e.g [AcceptType(httpTypes.Json)].</p> <p>There must be a better way than using that if statement everywhere.....</p>
<p>You can check the IsMvcAjaxRequest property and use it inside your controller and then return a partial view (user control) or JSON result if true, or the full View if it's false.</p> <p>Something like this:</p> <pre><code>public ActionResult List() { if (!Request.IsMvcAjaxRequest()) { // Non AJAX requests see the entire ViewPage. return View(); } else { // AJAX requests just get a trimmed down UserControl. return Json(...); } } </code></pre> <p>More info here: <a href="http://www.singingeels.com/Articles/MVC_AJAX_Sites_That_Gracefully_Degrade.aspx" rel="nofollow noreferrer">MVC AJAX Sites That Gracefully Degrade</a></p>
<p>(ref. your previous answer): You could pass a value in your Request.Form to signal that this is a browser with or without javascript enabled, and then create a controller factory that will instantiate the appropriated controller according to what you get in Request.Form; a default controller for regular requests (browsers with javascript enabled) and a "Fallback controller" that only returns full views instead. I am not sure if having twice the number of controllers is better than those if-else statements around a single controller, but I guess it's a question of personal preference.</p> <p>I <em>bet</em> there are simpler solutions, though..I wish this question had more exposure.</p>
41,404
<p>I'm looking for a way to query the ink level for my Epson DX 4050 on Mac OS X. There is some UI called EPSON StatusMonitor to display cartridges levels graphically, but I'd like to get it from the command-line so it can feed a robot.</p> <p>Any idea ?</p>
<p>This is going to be an undertaking. Either reverse engineer the StatusMonitor application to find out how it queries the drivers to find the ink level or look for some documentation for it. It may be possible to poke into the StatusMonitor application to find out internal values for its widgets (such a thing is possible with Windows, though hacky), but the entire process is likely to be a sinkhole for time :(</p>
<p>If the printer supports SNMP you might be lucky to query with any SNMP command-line tool. There are standard definitions for printers and they contain APIs to query the current and max ink levels.</p> <p>Here's how I do it with simple unix shell commands (requires net-snmp installed). This is not strictly Mac but you should get an idea.</p> <pre><code>#!/bin/sh me="${0##*/}" host="${1:-wp4535}" base=1.3.6.1.2.1.43.11.1.1 name="WP-4535" type=$(snmpget -v1 -c public ${host} SNMPv2-MIB::sysDescr.0) case "$type" in "SNMPv2-MIB::sysDescr.0 = STRING: EPSON"*) type=epson ofs=1 ;; *) echo "! unknown printer type" 1&gt;&amp;2 exit 1 ;; esac echo "# $host $type $name" # get current ink levels eval $(snmpwalk -v1 -Ov -OQ -c public ${host} ${base}.6.${ofs} | perl -ne 'print "c[",++$c,"]=$1\n" if(m!"(\w+) ink!i);') # get max ink level per cartridge eval $(snmpwalk -v1 -Ov -OQ -c public ${host} ${base}.8.${ofs} | perl -ne 'print "max[",++$c,"]=$1\n" if(m!(\d+)!i);') snmpwalk -v1 -Ov -OQ -c public ${host} ${base}.9.${ofs} | perl -ne ' my @c=("","'${c[1]}'","'${c[2]}'","'${c[3]}'","'${c[4]}'"); my @max=("","'${max[1]}'","'${max[2]}'","'${max[3]}'","'${max[4]}'"); my $v=$c[++$c]; printf"# $v=$1 (%.0f)\n",$1/$max[$c]*100 if(m!(\d+)!i);' </code></pre>
40,503
<p>For a long time ago, I have thought that, in java, reversing the domain you own for package naming is silly and awkward.</p> <p>Which do you use for package naming in your projects?</p>
<p>Once you understand why the convention exists, it shouldn't feel silly or awkward in the least.</p> <p>This scheme does two important things:</p> <ul> <li><p>All of your code is contained in packages that no one else will collide with. You own your domain name, so it's isolated. If we didn't have this convention, many companies would have a &quot;utilities&quot; package, containing classes like &quot;StringUtil&quot;, &quot;MessageUtil&quot; etc. These would quickly collide if you tried to use anyone else's code.</p> </li> <li><p>The &quot;reverse&quot; nature of it makes class-directory layout very narrow at the top level. If you expand a jar, you'll see &quot;com&quot;, &quot;org&quot;, &quot;net&quot;, etc dirs, then under each of those the organization/company name.</p> </li> </ul> <p>(added in 2021) This is even more important nowadays when this type of package naming is used for third-party libraries which are pulled in transitively during builds and could easily conflict if the names were not unique. If everyone adheres to the same convention, there will be no accidental collisions.</p> <p>(added in 2021) The same naming convention can be used for application ids on an app store to ensure uniqueness as well.</p> <p>We usually don't expand jars, but in early java development, this was important because people used expanded dir structures for applets.</p> <p>However, this is nice now as source code dir structures have a very &quot;top-down&quot; feel. You go from the most general (com, org, net...) to less general (company name) to more specific (project/product/lib name).</p>
<p>Yes, I use the reverse domain for the the start of the package, followed by the other administrative information (projects, departments, etc). The use of the domain minimizes the chance of collisions between vendors/companies/FOSS projects. My "data" package will not collide with another company's data package thanks to the domain.</p> <p>I have also used the convention of dropping the tld for internal work or classes that are not meant for outside use (maybe undocumented support libraries, etc). This usually makes it clear to other developers that different rules or policies may apply to a block of code.</p> <p>Using the reverse domain is a lot less chaotic than arbitrary namespaces that don't follow any rules or established pattern.</p>
22,944
<p>I'm trying to send an email in html format using JavaMail but it always seems to only display as a text email in Outlook. </p> <p>Here is my code:</p> <pre><code>try { Properties props = System.getProperties(); props.put("mail.smtp.host", mailserver); props.put("mail.smtp.from", fromEmail); props.put("mail.smtp.auth", authentication); props.put("mail.smtp.port", port); Session session = Session.getDefaultInstance(props, null); // -- Create a new message -- MimeMessage message = new MimeMessage(session); // -- Set the FROM and TO fields -- message.setFrom(new InternetAddress(fromEmail, displayName)); message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to, false)); MimeMultipart content = new MimeMultipart(); MimeBodyPart text = new MimeBodyPart(); MimeBodyPart html = new MimeBodyPart(); text.setText(textBody); text.setHeader("MIME-Version" , "1.0" ); text.setHeader("Content-Type" , text.getContentType() ); html.setContent(htmlBody, "text/html"); html.setHeader("MIME-Version" , "1.0" ); html.setHeader("Content-Type" , html.getContentType() ); content.addBodyPart(text); content.addBodyPart(html); message.setContent( content ); message.setHeader("MIME-Version" , "1.0" ); message.setHeader("Content-Type" , content.getContentType() ); message.setHeader("X-Mailer", "My own custom mailer"); // -- Set the subject -- message.setSubject(subject); // -- Set some other header information -- message.setSentDate(new Date()); // INFO: only SMTP protocol is supported for now... Transport transport = session.getTransport("smtp"); transport.connect(mailserver, username, password); message.saveChanges(); // -- Send the message -- transport.sendMessage(message, message.getAllRecipients()); transport.close(); return true; } catch (Exception e) { LOGGER.error(e.getMessage(), e); throw e; } </code></pre> <p>Any ideas why the html version of the email won't display in Outlook? </p>
<p>After a lot of investigation, I've been able to make some significant progress.</p> <p>Firstly, instead of using JavaMail directly, I recommend using the <a href="http://commons.apache.org/email/" rel="noreferrer">Jakarta Commons Email</a> library. This really simplifies the issue a lot!</p> <p>The code is now:</p> <pre><code>HtmlEmail email = new HtmlEmail(); email.setHostName(mailserver); email.setAuthentication(username, password); email.setSmtpPort(port); email.setFrom(fromEmail); email.addTo(to); email.setSubject(subject); email.setTextMsg(textBody); email.setHtmlMsg(htmlBody); email.setDebug(true); email.send(); </code></pre> <p>Talk about simple. </p> <p>However, there is still an issue. The html version of the email works great in Gmail, Hotmail, etc. But it still won't correctly display in Outlook. It always wants to display the text version and I'm not sure why. I suspect it's a setting in Outlook, but I can't find it...</p>
<p>workaroung solution solved outlook 2003: This message uses a character set that is not supported by the Internet Service. doesn't display correctly.</p> <p>It could be due to the encoding. Most html pages use iso-8859-1 not cp-1252 try changing</p> <p>For example, your code is:</p> <pre><code>message.setContent(sBuffer.toString(), "text/html"); </code></pre> <p>Change this to:</p> <pre><code>message.setContent(new String(sBuffer.toString().getBytes(), "iso-8859-1"), "text/html; charset=\"iso-8859-1\""); </code></pre> <p>This throws a new checked exception : java.io.UnsupportedEncodingException so you need to declare it to be thrown or catch it. iso-8859-1 is supported so, the exception will never be thrown unless something gets corrupted with your rt.jar. </p> <p>Regards, Javeed javeed.mca@gmail.com</p>
41,723
<p>In ASP.NET (not MVC), what is the best approach to programmatically setting styles on an unordered list used for navigation so the appropriate menu item is styled as the active item if that page is being viewed? </p> <p>This would most likely be used in conjunction with a MasterPage.</p>
<p>The answer to your question depends a lot on how you have your list implemented {User control or not, etc}. How I would do it, is implement the list to be generated by a user control. </p> <p>I'd have the UserControl tag each element with something like:</p> <pre><code>&lt;{...} class="GeneratedMenuItem"&gt; {...} </code></pre> <p>And I'd have the appropriate styles in the Style Sheet; of course if it was in a user control then you might be able to use Themes (but that depends on which version of ASP.net you are using. </p>
<p>The way I took this approach was to create ASP.NET Hyperlink Controls for each of my navigation items in my master page.</p> <p>Within the master page, I then created a public method that would assign the appropriate "selected" CSS style to the control I specify:</p> <pre><code>Public Sub SetNavigationPage(ByVal MenuName As String) DirectCast(Me.FindControl(MenuName), HyperLink).CssClass = "MenuCurrent" End Sub </code></pre> <p>Then in my content pages, I simply had to reference the master page accordingly.</p> <pre><code>Dim myMaster As EAF = DirectCast(Me.Master, EAF) myMaster.SetNavigationPage("hypSearchRequest") </code></pre> <p>This gave me the flexibility to add/remove navigation items on various pages and also be able to assign multiple pages to the administrator navigation option when necessary.</p> <p>It is also interesting to note that referencing the hyperlink control and setting the Visibility attribute (for hiding administrative pages) didn't work. This is due to the order in which the master and the content pages load. Instead, I created another CSS class that simply set the visibility property and used the same approach as above.</p>
40,000
<p>I'm a Java head mainly, and I want a way to generate a pseudo-random number between 0 and 74. In Java I would use the method:</p> <pre><code>Random.nextInt(74) </code></pre> <p>I'm not interested in a discussion about seeds or true randomness, just how you accomplish the same task in Objective-C. I've scoured Google, and there just seems to be lots of different and conflicting bits of information.</p>
<p>You should use the <code>arc4random_uniform()</code> function. It uses a superior algorithm to <code>rand</code>. You don't even need to set a seed.</p> <pre><code>#include &lt;stdlib.h&gt; // ... // ... int r = arc4random_uniform(74); </code></pre> <p>The <code>arc4random</code> man page:</p> <blockquote> <pre><code>NAME arc4random, arc4random_stir, arc4random_addrandom -- arc4 random number generator LIBRARY Standard C Library (libc, -lc) SYNOPSIS #include &lt;stdlib.h&gt; u_int32_t arc4random(void); void arc4random_stir(void); void arc4random_addrandom(unsigned char *dat, int datlen); DESCRIPTION The arc4random() function uses the key stream generator employed by the arc4 cipher, which uses 8*8 8 bit S-Boxes. The S-Boxes can be in about (2**1700) states. The arc4random() function returns pseudo- random numbers in the range of 0 to (2**32)-1, and therefore has twice the range of rand(3) and random(3). The arc4random_stir() function reads data from /dev/urandom and uses it to permute the S-Boxes via arc4random_addrandom(). There is no need to call arc4random_stir() before using arc4random(), since arc4random() automatically initializes itself. EXAMPLES The following produces a drop-in replacement for the traditional rand() and random() functions using arc4random(): #define foo4random() (arc4random() % ((unsigned)RAND_MAX + 1)) </code></pre> </blockquote>
<p>For game dev use random() to generate randoms. Probably at least 5x faster than using arc4random(). Modulo bias is not an issue, especially for games, when generating randoms using the full range of random(). Be sure to seed first. Call srandomdev() in AppDelegate. Here's some helper functions:</p> <pre><code>static inline int random_range(int low, int high){ return (random()%(high-low+1))+low;} static inline CGFloat frandom(){ return (CGFloat)random()/UINT32_C(0x7FFFFFFF);} static inline CGFloat frandom_range(CGFloat low, CGFloat high){ return (high-low)*frandom()+low;} </code></pre>
19,442
<p>I frequently come across Windows programs that bundle in MSVCRT (or their more current equivalents) with the program executables. On a typical PC, I would find many copies of the same .DLL's. My understanding is that MSVCRT is the C runtime library, somewhat analogous to glibc/libc.so under *nix.</p> <p>Why do Windows programs have to bring along their C libraries with them, instead of just sharing the system-wide libc?</p> <hr /> <p>Update: thanks to Shog9, I started to read about SxS, which has further opened up my eyes to the DLL linkage issues (DLL Hell) - <a href="https://web.archive.org/web/20160305220537/http://blogs.msdn.com/b/martynl/archive/2005/10/13/480880.aspx" rel="nofollow noreferrer">Link</a> is one useful intro to the issue...</p>
<p>[I'm the current maintainer of the Native SxS technology at Microsoft]</p> <p>New versions of MSVCRT are released with new versions of Visual Studio, and reflect changes to the C++ toolset. So that programs compiled with versions of VS released after a particular version of Windows continue can work downlevel (such as VS 2008 projects on Windows XP), the MSVCRT is redistributable, so it can be installed there.</p> <p>CRT installation drops the libraries into %windir%\winsxs\, which is a global system location, requiring administrator privileges to do so.</p> <p>Since some programs do not want to ship with an installer, or do not want the user to need administrator privileges on the machine to run their installer, they bundle the CRT directly in the same directory as the application, for private use. So on a typical machine, you'll find many programs that have opted for this solution.</p>
<p>Programs are linked against a specific version of the runtime, and that required version is <em>not</em> guaranteed to exist on the target machine. Also, matching up versions used to be problematic.</p> <p>In the Windows world, it's very bad manners to expect your users to go out and find and install a separate library to use your application. You make sure any dependencies not part of the host system are included with your app.</p> <p>In the linux world this isn't always as simple, since there's a much larger variation for how the host system might look. </p>
16,386
<p>We are starting a new SOA project with a lot of shared .net assemblies. The code for these assemblies will be stored in SVN.</p> <p>In development phase, we would like to be able to code these assemblies as an entire solution with as little SVN 'friction' as possible. </p> <p>When the project enters more of a maintenance mode, the assemblies will be maintained on an individual level.</p> <p>Without making Branching, Tagging, and Automated Builds a maintenance nightmare, what's the best way to organize these libraries in SVN that also works well with the VS 2008 IDE?</p> <p>Do you setup Trunk/Branches/Tags at each library level and try to spaghetti it all together somehow at compile time, or is it better to keep it all as one big project with code replicated here and there for simplicity? Is there a solution using externs?</p>
<p>What we did at our company was to set up a <strong>tools</strong> repository, and then a <strong>project</strong> repository. The <strong>tools</strong> repository is a Subversion repository, organized as follows:</p> <pre><code>/svn/tools/ vendor1/ too11/ 1.0/ 1.1/ latest = a copy of vendor1/tool1/1.1 tool2/ 1.0/ 1.5/ latest = a copy of vendor1/tool2/1.5 vendor2/ foo/ 1.0.0/ 1.1.0/ 1.2.0/ latest = a copy of vendor2/foo/1.2.0 </code></pre> <p>Every time we get a new version of a tool from a vendor, it is added under its vendor, name, and version number, and the 'latest' tag is updated. </p> <p><strong>[Clarification:</strong> this is NOT a typical source respository -- it's intended to store specific versions of 'installed' images. Thus /svn/tools/nunit/nunit2/2.4 would be the top of a directory tree containing the results of installing NUnit 2.4 to a directory and importing it into the tools repository. Source and examples may be present, but the primary focus is on executables and libraries that are necessary to use the tool. If we needed to modify a vendor tool, we'd do that in a separate repository, and release the result to this repository.<strong>]</strong></p> <p>One of the vendors is my company, and has a separate section for each tool, assembly, whatever that we release internally.</p> <hr> <p>The <strong>projects</strong> repository is a standard Subversion repository, with trunks, tags, and branches as you normally expect. Any given project will look like:</p> <pre><code>/svn/ branches/ tags/ trunk/ foo/ source/ tools/ publish/ foo-build.xml (for NAnt) foo.build (for MSBuild) </code></pre> <p>The tools directory has a Subversion <strong>svn:externals</strong> property set, that links in the appropriate version (either a specific version or 'latest') of each tool or assembly that is needed by that project. When the 'foo' project is built by CruiseControl.NET, the publish task will populate the 'publish' directory as the 'foo' assembly is intended to be deployed, and then executes the following subversion commands:</p> <pre><code>svn import publish /svn/tools/vendor2/foo/1.2.3 svn delete /svn/tools/vendor2/foo/latest svn copy /svn/tools/vendor2/foo/1.2.3 /svn/tools/vendor2/foo/latest </code></pre> <p>Developers work on their projects as normal, and let the build automation take care of the details. A normal subversion update will pull the latest versions of external tools as well as as project updates.</p> <p>If you've got a lot of tool interdependency, you can configure CruiseControl.NET (by hand) to trigger builds for subordinate projects when their dependencies change, but we haven't needed to go that far yet.</p> <blockquote> <p>Note: All of the Subversion repository paths have been shortened for clarity. We actually use Apache+SVN, and two separate servers, but you should adapt this as you see fit.</p> </blockquote>
<p>What we did with shared assemblies during development phase (in a project which had loads of these), is that we put them on a network share (N Drive) type of a place, and every developer referenced them from there.</p> <p>Our build process would always update this share with the latest versions. This way the actual assemblies never had to be kept in source control. Only the code.</p>
13,281
<p>I currently use <a href="http://subversion.tigris.org/" rel="nofollow noreferrer">subversion</a> for my version control via <a href="http://ankhsvn.open.collab.net/" rel="nofollow noreferrer">AhnkSVN</a> and Visual Studio. I recently started using <a href="http://www.codeplex.com/treesurgeon" rel="nofollow noreferrer">Tree Surgeon</a> to set up my projects. It creates a build script automatically using <a href="http://nant.sourceforge.net/" rel="nofollow noreferrer">NAnt</a>. I would like to be able to automate builds regularly projects within SVN. I like the idea of doing a build on every check in but nightly builds would work as well. I would give more information or more of my thoughts but figured I would leave it open and see what the SO community has to say.</p>
<p>You could use <a href="http://confluence.public.thoughtworks.org/display/CCNET/Welcome+to+CruiseControl.NET" rel="nofollow noreferrer">CruiseControl.Net</a>, which can do a build on every check in, nightly builds, or however you want to do it. A quick google search suggests CC.Net has some <a href="http://ccnet.sourceforge.net/CCNET/NAnt%20Task.html" rel="nofollow noreferrer">integration with NAnt</a> already.</p>
<p>You might want to consider CI-Factory. It's a continuous integration environment builder that uses CruiseControl.NET and a dozen other tools. There's an excellent screencast here: <a href="http://www.dnrtv.com/default.aspx?showID=64" rel="nofollow noreferrer">http://www.dnrtv.com/default.aspx?showID=64</a></p>
5,718
<p>We are using a WCF service layer to return images from a repository. Some of the images are color, multi-page, nearly all are TIFF format. We experience slowness - one of many issues.</p> <p>1.) What experiences have you had with returning images via WCF 2.) Do you have any suggestions tips for returning large images? 3.) All messages are serialized via SOAP correct?<br> 4.) Does wcf do a poor job of compressing the large tiff files?</p> <p>Thanks all!</p>
<p>Okay Just to second the responses by ZombieSheep and Seba Gomez, you should definitely look at streaming your data. By doing so you could seamlessly integrate the GZipStream into the process. On the client side you can reverse the compression process and convert the stream back to your desired image.</p> <p>By using streaming there is a select number of classes that can be used as parameters/return types and you do need to modify your bindings throughout.</p> <p>Here is the <a href="http://msdn.microsoft.com/en-us/library/ms789010.aspx" rel="nofollow noreferrer">MSDN site</a> on enabling streaming. <a href="http://msdn.microsoft.com/en-us/library/ms731913.aspx" rel="nofollow noreferrer">This</a> is the MSDN page that describes the restrictions on streaming contracts.</p> <p>I assume you are also controlling the client side code, this might be really hard if you aren't. I have only used streaming when I had control of both the server and client.</p> <p>Good luck.</p>
<p>In a previous project I worked we had a similar issue. We had a Web Service in C# that received requests for medias. A media can range from files to images and was stored in a database using BLOB columns. Initially the web method that handled media retrieval requests read the chunk from the BLOB and returned in to the caller. This was one round trip to the server. The problem with this approach is that the client has no feedback of the progress of the operation.</p> <blockquote> <p>There is no problem in computer science that cannot be solved by an extra level of indirection.</p> </blockquote> <p>We started by refactoring the method in three methods.</p> <p><strong>Method1</strong> setup the conversation between caller and the web service. This includes information about the request (like media Id) and capabilities exchange. The web service responded with a ticked Id which is used for the caller for future requests. This initial call is used for resource allocation.</p> <p><strong>Method2</strong> is called consecutively until there is more that to be retrieved for the media. The call includes information about the current offset and the ticked Id that was provided when <strong>Method1</strong> was called. The return updates the current position.</p> <p><strong>Method3</strong> is called to finish request when <strong>Method2</strong> reports that the reading of the request media has completed. This frees allocated resources.</p> <p>This approach is practical because you can give immediate feedback to the user about the progress of the operation. You have a bonus that is to split the requests to <strong>Method2</strong> in different threads. The progress than can be reported by chunk as some BitTorrent clients do.</p> <hr> <p>Depending on the size of the BLOB you can choose to load it from the database on one go or <a href="http://www.akadia.com/services/dotnet_read_write_blob.html" rel="nofollow noreferrer">reading it also by chunks</a>. This means that you could use a balanced mechanism that based on a given watermark (BLOB size) chooses to load it in one go or by chunks.</p> <hr> <p>If there is still a performance issue consider packaging the results using <a href="http://msdn.microsoft.com/en-us/library/system.io.compression.gzipstream.aspx" rel="nofollow noreferrer">GZipStream</a> or read about <a href="http://msdn.microsoft.com/en-us/library/aa751889.aspx" rel="nofollow noreferrer">message encoders</a> and specifically pay attention to the binary and Message Transmission Optimization Mechanism (MTOM).</p>
23,300
<p>I have a web application (.war) that contains some static files (e.g. MS word documents). When I try to download these files, JBoss automatically sets some HTTP-headers in the response. Is there a way to configure JBoss (version 3.2.7) to set these headers to specific values (or omit them)? I'm especially interested in the </p> <pre><code>Cache-Control: no cache </code></pre> <p>header, because this leads to some problems when downloading files over https with Internet Explorer (IE will refuse to save the file to disk).</p> <p>Btw. this behaviour can be changed by adding an entry to the windows registry:</p> <pre><code>[HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Internet Settings] "BypassSSLNoCacheCheck"=dword:00000001 </code></pre> <p>but obviously I'm not going to ask customers to fiddle with their registry just to donwload a file.</p> <p>Any suggestions are greatly appreciated.</p>
<p><a href="http://www.jboss.org/community/docs/DOC-9578" rel="nofollow noreferrer">Here</a> is a description on the JBoss community wiki on how to disable the Cache-Control behaviour.</p> <p>I wasn't aware of this IE6 feature until now. Does this also apply to IE7?</p>
<p>An option that comes to mind is to wrap a servlet (or similar) around it - so that the URL that gets called calls your servlet, which then sets the headers you want and then delivers the underlying document.</p>
39,723
<p>I have a few sites on a shared host that is running Apache 2. I would like to compress the HTML, CSS and Javascript that is delivered to the browser. The host has disabled mod_deflate and mod_gzip, so these options are out. I do have PHP 5 at my disposal, though, so I could use the gzip component of that.</p> <p>I am currently placing the following in my .htaccess file:</p> <blockquote> <p>php_value output_handler ob_gzhandler</p> </blockquote> <p>However, this only compresses the HTML and leaves out the CSS and JS.</p> <p>Is there a reliable way of transparently compressing the output of the CSS and JS without having to change every page? I have searched Google and a number of solutions are presented, but I've yet to get one to work. If anyone could suggest a solution that they know to work, that would be very gratefully received.</p> <p>Note, <strong>Method 2</strong> in <strong><a href="http://www.fiftyfoureleven.com/weblog/web-development/css/the-definitive-css-gzip-method" rel="noreferrer">The Definitive Post on Gzipping your CSS</a></strong> looks like a good solution, but I couldn't get it working. Has anyone else succeeded using this method?</p>
<p>Sorry about the delay - it's a busy week for me.</p> <p>Assumptions:</p> <ul> <li><code>.htaccess</code> is in the same file as <code>compress.php</code></li> <li>static files to be compressed are in <code>static</code> subdirectory</li> </ul> <p>I started my solution from setting the following directives in .htaccess:</p> <pre><code>RewriteEngine on RewriteRule ^static/.+\.(js|ico|gif|jpg|jpeg|png|css|swf)$ compress.php [NC] </code></pre> <p>It's required that your provider allows you to override <code>mod_rewrite</code> options in <code>.htaccess</code> files. Then the compress.php file itself can look like this:</p> <pre><code>&lt;?php $basedir = realpath( dirname($_SERVER['SCRIPT_FILENAME']) ); $file = realpath( $basedir . $_SERVER["REQUEST_URI"] ); if( !file_exists($file) &amp;&amp; strpos($file, $basedir) === 0 ) { header("HTTP/1.0 404 Not Found"); print "File does not exist."; exit(); } $components = split('\.', basename($file)); $extension = strtolower( array_pop($components) ); switch($extension) { case 'css': $mime = "text/css"; break; default: $mime = "text/plain"; } header( "Content-Type: " . $mime ); readfile($file); </code></pre> <p>You should of course add more mime types to the switch statement. I didn't want to make the solution dependant on the pecl <code>fileinfo</code> extension or any other magical mime type detecting libraries - this is the simplest approach.</p> <p>As for securing the script - I do a translation to a real path in the file system so no hacked '../../../etc/passwd' or other shellscript file paths don't go through.</p> <p>That's the</p> <pre><code>$basedir = realpath( dirname($_SERVER['SCRIPT_FILENAME']) ); $file = realpath( $basedir . $_SERVER["REQUEST_URI"] ); </code></pre> <p>snippet. Although I'm pretty sure most of the paths that are in other hierarchy than $basedir will get handled by the Apache before they even reach the script.</p> <p>Also I check if the resulting path is inside the script's directory tree. Add the headers for cache control as pilif suggested and you should have a working solution to your problem.</p>
<p>You can try your luck with <a href="http://httpd.apache.org/docs/2.2/mod/mod_rewrite.html" rel="nofollow noreferrer">mod_rewrite</a>.</p> <p>Create a script that takes a local static file name as input, through e.g. <code>$_SERVER['QUERY_STRING']</code> and outputs it in compressed form. Many providers don't allow configuring <code>mod_rewrite</code> with <code>.htaccess</code> files or have it completely disabled though.</p> <p>If you haven't used <em>rewrite</em> before, I recommend a good beginner's guide, like probably <a href="http://www.workingwith.me.uk/articles/scripting/mod_rewrite" rel="nofollow noreferrer">this one</a>. This way you can make the apache redirect all requests for a static file to a php script. style.css will be redirected to <em>compress.php?style.css</em> for instance.</p> <p>As always be <strong>extremely</strong> cautious on the input you accept or you have an <code>XSS</code> exploit on your hands!</p>
7,102
<p>I have a string to tokenize. It's form is <code>HHmmssff</code> where <code>H</code>, <code>m</code>, <code>s</code>, <code>f</code> are digits. </p> <p>It's supposed to be tokenized into four 2-digit numbers, but I need it to also accept short-hand forms, like <code>sff</code> so it interprets it as <code>00000sff</code>. I wanted to use <code>boost::tokenizer</code>'s <code>offset_separator</code> but it seems to work only with positive offsets and I'd like to have it work sort of backwards.</p> <p>Ok, one idea is to pad the string with zeroes from the left, but maybe the community comes up with something <em>uber</em>-smart. ;)</p> <p><strong>Edit:</strong> <em>Additional requirements have just come into play.</em></p> <p>The basic need for a smarter solution was to handle all cases, like <code>f</code>, <code>ssff</code>, <code>mssff</code>, etc. but also accept a more complete time notation, like <code>HH:mm:ss:ff</code> with its short-hand forms, e.g. <code>s:ff</code> or even <code>s:</code> (this one's supposed to be interpreted as <code>s:00</code>).</p> <p>In the case where the string ends with <code>:</code> I can obviously pad it with two zeroes as well, then strip out all separators leaving just the digits and parse the resulting string with spirit.</p> <p>But it seems like it would be a bit simpler if there was a way to make the offset tokenizer going back from the end of string (offsets -2, -4, -6, -8) and lexically cast the numbers to <code>int</code>s.</p>
<p>I keep preaching BNF notation. If you can write down the grammar that defines your problem, you can easily convert it into a Boost.Spirit parser, which will do it for you.</p> <pre><code>TimeString := LongNotation | ShortNotation LongNotation := Hours Minutes Seconds Fractions Hours := digit digit Minutes := digit digit Seconds := digit digit Fraction := digit digit ShortNotation := ShortSeconds Fraction ShortSeconds := digit </code></pre> <p>Edit: additional constraint</p> <pre><code>VerboseNotation = [ [ [ Hours ':' ] Minutes ':' ] Seconds ':' ] Fraction </code></pre>
<p>Regular Expressions come to mind. Something like <code>"^0*?(\\d?\\d?)(\\d?\\d?)(\\d?\\d?)(\\d?\\d?)$"</code> with <code>boost::regex</code>. Submatches will provide you with the digit values. Shouldn't be difficult to adopt to your other format with colons between numbers (see sep61.myopenid.com's answer). <code>boost::regex</code> is among the fastest regex parsers out there.</p>
36,478
<p>If you look at the following link: <a href="http://www.enewhope.org/index2.php" rel="nofollow noreferrer">What's new at New Hope</a> </p> <p>Look at the widget on the page entitled "What's new at New Hope" which contains the Web2.0 equivalent of a MARQUEE (I guess that's what you'd call it) complete with fading images and "Read More" links.</p> <p><strong>Question:</strong> Can you identify the exact specific JQuery plugins used to generate this specific widget? The other stuff on the page is not relevant. I'm having a dog of a time discerning which plugins were used to create it and it alone.</p>
<p>Why not just look at the code? <a href="http://www.enewhope.org/assets/js/turnstile.js" rel="nofollow noreferrer">http://www.enewhope.org/assets/js/turnstile.js</a></p> <p>It appears to be mostly standard jQuery effects animate calls.</p> <p><a href="http://docs.jquery.com/Effects/animate" rel="nofollow noreferrer">http://docs.jquery.com/Effects/animate</a></p>
<p><a href="http://malsup.com/jquery/cycle/" rel="nofollow noreferrer">JQuery Cycle Plugin</a> can do the image part, I don't know about the text stuff.</p>
47,218
<p>Let's say I'm creating a program in C that needs to use a tempfile. Creating an ad hoc tempfile in /tmp is probably not a good idea. Is there a function or OS call to supply me with a tempfile name so that I can begin to write and read from it?</p>
<p>You can use the <a href="http://www.linuxmanpages.com/man3/mkstemp.3.php" rel="noreferrer"><code>mkstemp(3)</code></a> function for this purpose. Another alternative is the <a href="http://www.linuxmanpages.com/man3/tmpfile.3.php" rel="noreferrer"><code>tmpfile(3)</code></a> function. Which one of them you choose depends on whether you want the file to be opened as a C library file stream (which <code>tmpfile</code> does), or a direct file descriptor (<code>mkstemp</code>). The <code>tmpfile</code> function also deletes the file automatically when you program finishes.</p> <p>The advantage of using these functions is that they avoid race conditions between determining the unique filename and creating the file -- so that two programs won't try to create the same file at the same time, for example.</p> <p>See the man pages for both functions for more details.</p>
<p>You should use the mkstemp() as this is the recommended function, but it returns a file descriptor, so once you have the descriptor get it's name:</p> <pre><code>int fd; fd = mkstemp("hdrXXXXXX); /* Read out the link to our file descriptor. */ sprintf(path, "/proc/self/fd/%d", fd); memset(result, 0, sizeof(result)); readlink(path, result, sizeof(result)-1); /* Print the result. */ printf("%s\n", result); </code></pre>
4,932
<p>I'm teaching Java EE at the university, and this was a question a student asked. I said "no", but I wasn't really sure, so I thought I might ask you mighty developers. :)</p> <p>Basically, what I'd like to do is to use entities if they were in my context: cat getters, setters, etc, so like normal POJOs. if I use an EJB using its remote inferface, the entities gets decoupled from the core infrastructure, so that's a no-go.</p> <p>I thought about writing a layer such as this in my MSc thesis. If it's a dead idea, feel free to tell me. If it's not, tell me if you'd like one.</p> <p>Or if there is such a tool out there, let me know!</p>
<p>In a basic modern world Java EE application, it is broken into various layers, where you have 4 basic layers </p> <pre><code>+--------------------+ | Presentation | +--------------------+ | Controller/Actions | +--------------------+ | Business Delegate | | (Service) | +--------------------+ | Data Access Layer | +--------------------+ | Database | +--------------------+ </code></pre> <p>Your applications should be split into these layer right from the beginning, such that you can at any given point of time replace any layer without effecting any of it's sibling layer.</p> <p>Example if you used JDBC for the Data Access layer, you should be able to replace it with Hibernate without affecting the business delegate or Database layer. The benefit of using such an architecture is to allow collaboration with multiple technologies. You business delegate (service layer) should be able to talk to a web service and handle the application processing without even going to a browser!</p> <p>Regarding using JSP as the presentation layer, there are other technologies available like, <a href="http://velocity.apache.org/" rel="nofollow noreferrer">velocity</a>, <a href="http://freemarker.sourceforge.net/" rel="nofollow noreferrer">freemarker</a>, as iberck mentioned above, tapestry also has it's own rendering engine. You can use XML + XSLT also to render the UI. There are UI managing apps also available like <a href="http://tiles.apache.org/" rel="nofollow noreferrer">Tiles</a> and <a href="http://www.opensymphony.com/sitemesh/" rel="nofollow noreferrer">sitemesh</a>, that help you integrate various techs as different components of the page and show them as one.</p> <p>You can also use light weight swing components clubbed with <a href="http://java.sun.com/javase/technologies/desktop/javawebstart/1.2/docs/developersguide.html" rel="nofollow noreferrer">JNLP</a> and develop a desktop style enterprise application. All we need is a little imagination and client requirement and we can use literally anything as the presentation layer. </p>
<p>One alternative is <a href="http://www.springframework.org/" rel="nofollow noreferrer">the Spring Framework</a>. Spring provides its own support for binding entity objects to the view and handles the getting/setting for you once it is wired up. There are many Spring modules to pick and choose from. Spring MVC and Spring Webflow are both worth checking out. Spring MVC (IMO) is simpler to get started with, but Sring Webflow allows for more complex navigation and more scope options (ex: flow scope). If you're looking for a book <a href="https://rads.stackoverflow.com/amzn/click/com/1933988134" rel="nofollow noreferrer" rel="nofollow noreferrer">Spring In Action</a> is descent. There are some concepts you will need to tackle (such as dependency injection) in order to use Spring but it is well worth the time.</p>
37,894
<p>I am trying to coordinate the move of a site from its current server to a new one. My original plan was to migrate the data to the new machine, which is already in place and the migration scripts tested successfully. I was planning to configure the original machine to proxy all requests to the new one, in order to ensure that anyone hitting the original machine before the DNS change fully propagates will still get proper response.</p> <p>Someone made an alternative suggestion that I add the records for the new machine, without it actually serving any content. I was told that, under these circumstances, traffic would all hit the original IP. When the new records propagate, I am told I can turn off the old server and bring up the new server. I'm skeptical of trying this and having my migration in a half-way mode. Should I even attempt it or just stick to my original plan?</p>
<p>There is nothing wrong with your original plan.</p> <p>It's also a good plan when you don't control the DNS server(s) that you use.</p> <p>[Edit] Also, since this sounds like a production environment, it is never a good idea to try something you are not familiar and comfortable with in a production environment.</p> <p>The second idea does not sound at all bad, but just not optimal in this case. Go with what you know works.</p>
<p>You cannot control how long before the records propagate, only how long before you are sure they have propagated.</p> <p>The DNS records' TTL is the <em>maximum</em> time they can be cached; however, even before that time, people will already be hitting the site at the new address (for instance, if their DNS server did not have the record on their caches).</p> <p>This means that any solution will have a window of time where some people are hitting the old addresses and other people are hitting the new addresses. Any migration solution must consider that scenario.</p> <p>Your original plan is the best one, as long as you remember to proxy to the IP address (since you cannot know what the domain name is pointing to until the TTL has elapsed). An alternate plan (if you can have your site offline for some time) would be to simply take the old server offline, do the migration, bring the new server online, change the DNS records, and wait for the TTL to elapse; people will gradually start using the new server as the DNS records on their nameservers and browser DNS caches expire, and before that they only see an offline website.</p> <p>The suggestion to add the records for the new machine without it serving any content is suspicious, since as soon as the record is added some people will start using it.</p>
37,623
<p>I have to pass parameters between two rails apps. In one side (sender) I have an array of hashes. I have a code like the following to send the data:</p> <pre><code> http = Net::HTTP.new('localhost', '3030') result = http.post('/processar_lotes', my_array_of_hashes) </code></pre> <p>Some questions</p> <ul> <li>Is there any (kind of) serialize or something like this that I can pass to the other app?</li> <li>At the other side, how can I de-serialize the information?</li> <li>Is there a limit to the size of what I pass as a parameter?</li> </ul>
<p>Considering that these objects can vary per file size, and your computer's specs (bus speed, HD speed) affect this, the only way to be sure is to write your own benchmark. Just create a simple for loop, count from 1 to 1000, and read the file inside the loop over and over (but do not create and destroy the objects inside the loop, just focus on the reading part).</p> <p>Of course this whole exercise reeks of pre-optimization, which can lead to bad coding habit. Just write your code in the most readable, simple fashion, and if there is a speed problem, refactor as needed.</p> <p>But since it's a small amount of data, I would say it won't matter.</p>
<p>Considering that these objects can vary per file size, and your computer's specs (bus speed, HD speed) affect this, the only way to be sure is to write your own benchmark. Just create a simple for loop, count from 1 to 1000, and read the file inside the loop over and over (but do not create and destroy the objects inside the loop, just focus on the reading part).</p> <p>Of course this whole exercise reeks of pre-optimization, which can lead to bad coding habit. Just write your code in the most readable, simple fashion, and if there is a speed problem, refactor as needed.</p> <p>But since it's a small amount of data, I would say it won't matter.</p>
33,947
<p>If I've got a time_t value from <code>gettimeofday()</code> or compatible in a Unix environment (e.g., Linux, BSD), is there a compact algorithm available that would be able to tell me the corresponding week number within the month?</p> <p>Ideally the return value would work in similar to the way <code>%W</code> behaves in <code>strftime()</code> , except giving the week within the month rather than the week within the year.</p> <p>I think Java has a <code>W</code> formatting token that does something more or less like what I'm asking.</p> <hr> <p>[Everything below written after answers were posted by David Nehme, Branan, and Sparr.]</p> <p>I realized that to return this result in a similar way to <code>%W</code>, we want to count the number of Mondays that have occurred in the month so far. If that number is zero, then 0 should be returned.</p> <p>Thanks to David Nehme and Branan in particular for their solutions which started things on the right track. The bit of code returning [using Branan's variable names] <code>((ts-&gt;mday - 1) / 7)</code> tells the number of complete weeks that have occurred before the current day.</p> <p>However, if we're counting the number of Mondays that have occurred so far, then we want to count the number of integral weeks, including today, then consider if the fractional week left over also contains any Mondays.</p> <p>To figure out whether the fractional week left after taking out the whole weeks contains a Monday, we need to consider <code>ts-&gt;mday % 7</code> and compare it to the day of the week, <code>ts-&gt;wday</code>. This is easy to see if you write out the combinations, but if we insure the day is not Sunday (<code>wday &gt; 0</code>), then anytime <code>ts-&gt;wday &lt;= (ts-&gt;mday % 7)</code> we need to increment the count of Mondays by 1. This comes from considering the number of days since the start of the month, and whether, based on the current day of the week within the the first fractional week, the fractional week contains a Monday.</p> <p>So I would rewrite Branan's return statement as follows:</p> <p><code>return (ts-&gt;tm_mday / 7) + ((ts-&gt;tm_wday &gt; 0) &amp;&amp; (ts-&gt;tm_wday &lt;= (ts-&gt;tm_mday % 7)));</code></p>
<p>Assuming your first week is week 1:</p> <pre><code>int getWeekOfMonth() { time_t my_time; struct tm *ts; my_time = time(NULL); ts = localtime(&amp;my_time); return ((ts-&gt;tm_mday -1) / 7) + 1; } </code></pre> <p>For 0-index, drop the <code>+1</code> in the return statement.</p>
<p>Consider this pseudo-code, since I am writing it in mostly C syntax but pretending I can borrow functionality from other languages (string->int assignment, string->time conversion). Adapt or expand for your language of choice.</p> <pre><code>int week_num_in_month(time_t timestamp) { int first_weekday_of_month, day_of_month; day_of_month = strftime(timestamp,"%d"); first_weekday_of_month = strftime(timefstr(strftime(timestamp,"%d/%m/01")),"%w"); return (day_of_month + first_weekday_of_month - 1 ) / 7 + 1; } </code></pre> <p>Obviously I am assuming that you want to handle weeks of the month the way the standard time functions handle weeks of the year, as opposed to just days 1-7, 8-13, etc.</p>
12,274
<p>I need to monitor number of the facebook group users and display it on the website. I know that it is possible to get User IDs using their API, but they are limited to 500 only (if the total number of members is 500+). </p> <p>What would be the easiest way to get total number of members that signed up to a Facebook Group that I'd set up? Is this at all possible?</p>
<p>If you write an http bot, it shouldn't be very hard to scrap, given that real-time performance is not the key.</p>
<p>According to the documentation for <code>Groups.getMembers</code> it isn't possible to get > 500 group members with an API call. Worse, you seem to only be able to get 500 <em>random</em> members.</p> <p>You may want to consider using Facebook Connect with your site instead. I'm no expert on Connect but I believe you wont have this problem using it since you are actually writing Facebook-specific code -- seems like there would be no purpose in limiting results. That'd be the direction I'd look, at least.</p> <p>Good luck.</p>
41,902
<p>I have an element that is similar to a tag (because it has word-wrap: pre;) to display code on a website. The only problem is that the tab size is too large and causes the element to horizontally scroll often because it is of fixed width.</p> <p>Is it possible to change the tab size?</p>
<p>You could replace tabs with spaces. Then you could control exactly the size of the indents.</p>
<p>We need some more clarity into your question, but are you perchance looking for the <code>text-indent</code> css property? You can set the indentation amount, e.g.:</p> <pre><code>&lt;style type="text/css"&gt; p { text-indent: 40px; } &lt;/style&gt; </code></pre>
47,498
<p>I am trying to add a new hello world service to amfphp, I am developing locally</p> <pre><code>&lt;?php /** * First tutorial class */ class HelloWorld { /** * first simple method * @returns a string saying 'Hello World!' */ function sayHello() { return "Hello World!"; } } ?&gt; </code></pre> <p>when exploring in the amfphp browser i get a "TypeError: Error #1009: Cannot access a property or method of a null object reference." need help...</p>
<p>I recommend <a href="http://www.charlesproxy.com/" rel="nofollow noreferrer">Charles</a> for solving this type of problem, this let's you see what's going across the wire. In your case it's likely something simple as a syntax error in the php file. PHP will output the error information into what the Service Browser expects to be amf-encoded data, wreaking havoc to any parsing it tries. Using Charles you can easily see this and fix it!</p>
<p>You're trying to access a variable/method that's null. The code here is fine so the problem is somewhere else..</p>
12,815
<p>Do you know any solution to put a picture over a Flash?</p> <p>It <strong>must</strong> work in IE6, IE7, Firefox for Windows, MacOSX, Linux and Safari.</p>
<p>Off the top of my head you could try this:</p> <p>Absolute positioned div with the image over the swf </p> <p>You must set swf's parameter "wmode" value as "transparent".</p> <p>You could also go to www.actionscript.org and do a search on their forum.</p>
<p>The wmode=opaque provides better performance than "transparent", with pretty much the same results.</p>
19,685
<p>I'm not sure how password hashing works (will be implementing it later), but need to create database schema now.</p> <p>I'm thinking of limiting passwords to 4-20 characters, but as I understand after encrypting hash string will be of different length.</p> <p>So, how to store these passwords in the database?</p>
<p>Update: Simply using a hash function is not strong enough for storing passwords. You should read <a href="https://stackoverflow.com/a/55753734/20860">the answer from Gilles on this thread</a> for a more detailed explanation.</p> <p>For passwords, use a key-strengthening hash algorithm like Bcrypt or Argon2i. For example, in PHP, use the <a href="https://www.php.net/manual/en/function.password-hash.php" rel="noreferrer">password_hash() function</a>, which uses Bcrypt by default.</p> <pre><code>$hash = password_hash("rasmuslerdorf", PASSWORD_DEFAULT); </code></pre> <p>The result is a 60-character string similar to the following (but the digits will vary, because it generates a unique salt).</p> <pre><code>$2y$10$.vGA1O9wmRjrwAVXD98HNOgsNpDczlqm3Jq7KnEd1rVAGv3Fykk1a </code></pre> <p>Use the SQL data type <code>CHAR(60)</code> to store this encoding of a Bcrypt hash. Note this function doesn't encode as a string of hexadecimal digits, so we can't as easily unhex it to store in binary.</p> <p>Other hash functions still have uses, but not for storing passwords, so I'll keep the original answer below, written in 2008.</p> <hr> <p>It depends on the hashing algorithm you use. Hashing always produces a result of the same length, regardless of the input. It is typical to represent the binary hash result in text, as a series of hexadecimal digits. Or you can use the <a href="http://dev.mysql.com/doc/refman/5.5/en/string-functions.html#function_unhex" rel="noreferrer"><code>UNHEX()</code></a> function to reduce a string of hex digits by half.</p> <ul> <li>MD5 generates a 128-bit hash value. You can use CHAR(32) or BINARY(16)</li> <li>SHA-1 generates a 160-bit hash value. You can use CHAR(40) or BINARY(20)</li> <li>SHA-224 generates a 224-bit hash value. You can use CHAR(56) or BINARY(28)</li> <li>SHA-256 generates a 256-bit hash value. You can use CHAR(64) or BINARY(32)</li> <li>SHA-384 generates a 384-bit hash value. You can use CHAR(96) or BINARY(48)</li> <li>SHA-512 generates a 512-bit hash value. You can use CHAR(128) or BINARY(64)</li> <li>BCrypt generates an implementation-dependent 448-bit hash value. <a href="https://stackoverflow.com/questions/5881169/storing-a-hashed-password-bcrypt-in-a-database-type-length-of-column">You might need CHAR(56), CHAR(60), CHAR(76), BINARY(56) or BINARY(60)</a></li> </ul> <p>As of 2015, NIST <a href="https://csrc.nist.gov/Projects/Hash-Functions/NIST-Policy-on-Hash-Functions" rel="noreferrer">recommends using SHA-256 or higher</a> for any applications of hash functions requiring interoperability. But NIST does not recommend using these simple hash functions for storing passwords securely.</p> <p>Lesser hashing algorithms have their uses (like internal to an application, not for interchange), but they are <a href="http://web.archive.org/web/20081222011930/http://www.larc.usp.br/~pbarreto/hflounge.html" rel="noreferrer">known to be crackable</a>.</p>
<p>for md5 vARCHAR(32) is appropriate. For those using AES better to use varbinary.</p>
30,717
<p>For example, if you type something in upper-right google/yahoo search box in firefox there will be some kind 'suggested auto complete' sort of thing. </p> <p>Another example is in youtube search box and Stackoverflow tags edit box just below this question preview. How do they work? What technology behind 'em?</p>
<p>That's done with the use of AJAX, this site has a nice tutorial on it: <a href="http://www.dynamicajax.com/fr/AJAX_Suggest_Tutorial-.html" rel="nofollow noreferrer">AJAX Suggest Tutorial</a>, and the <a href="https://web.archive.org/web/20170129160828/www.dynamicajax.com/fr/AJAX_Suggest_Tutorial-.html" rel="nofollow noreferrer">WaybackMachine version, as website seems down</a>.</p> <p>A database with keywords and a bit of code is all there is to it as far as I know.</p> <p>I'm learning how to use it right now actually, for work. :)</p> <p>Another resource is <a href="https://www.w3schools.com/js/js_ajax_intro.asp" rel="nofollow noreferrer">w3schools</a>. They have covered it as well. </p>
<p><a href="http://digitarald.de/project/autocompleter/" rel="nofollow noreferrer">Here is one for MooTools</a>.</p>
45,434
<p>In a web-application implemented in java using JSP and Servlets; if I store information in the user session, this information is shared from all the tabs from the same browser. How to differ sessions in the browser-tabs? In this example: </p> <pre><code>&lt;%@page language="java"%&gt; &lt;% String user = request.getParameter("user"); user = (user == null ? (String)session.getAttribute("SESSIONS_USER") : user); session.setAttribute("SESSIONS_USER",user); %&gt; &lt;html&gt;&lt;head&gt;&lt;/head&gt;&lt;body&gt; &lt;%=user %&gt; &lt;form method="post"&gt; User:&lt;input name="user" value=""&gt; &lt;input type="submit" value="send"&gt; &lt;/form&gt; &lt;/body&gt;&lt;/html&gt; </code></pre> <p>Copy this code in a jsp page (<code>testpage.jsp</code>), deploy this file in an existing context of a web application on the server (I use Apache Tomcat), then open a browser (FF, IE7 or Opera) using the correct URL (<code>localhost/context1/testpage.jsp</code>), type your name in the input and submit the form. Then open a new tab in the same browser, and then you can see your name (get from the session) on the new tab. Be careful with the browser-cache, sometimes seems that it doesn't happen, but it's in the cache, refresh the second tab.</p> <p>Thanks.</p>
<p>You can use HTML5 SessionStorage (window.sessionStorage). You will generate a random id and save in session Storage per Browser Tab. Then each browser tab has his own Id. </p> <blockquote> <p>Data stored using sessionStorage do not persist across browser tabs, even if two tabs both contain webpages from the same domain origin. In other words, data inside sessionStorage is confined to not just the domain and directory of the invoking page, but the browser tab in which the page is contained in. Contrast that to session cookies, which do persist data from tab to tab.</p> </blockquote>
<p>I've been reading this post because I thought I wanted to do the same thing. I have a similar situation for an application I'm working on. And really it's a matter of testing more than practicality.</p> <p>After reading these answers, especially the one given by Michael Borgwardt, I realized the work flow that needs to exist:</p> <ol> <li>If the user navigates to the login screen, check for an existing session. If one exists bypass the login screen and send them to the welcome screen.</li> <li>If the user (in my case) navigates to the enrollment screen, check for an existing session. If one exists, let the user know you're going to log that session out. If they agree, log out, and begin enrollment.</li> </ol> <p>This will solve the problem of user's seeing "another user's" data in their session. They aren't really seeing "another user's" data in their session, they're really seeing the data from the only session they have open. Clearly this causes for some interesting data as some operations overwrite some session data and not others so you have a combination of data in that single session.</p> <p>Now, to address the testing issue. The only viable approach would be to leverage <a href="http://msdn.microsoft.com/en-us/library/ed8yd1ha.aspx" rel="nofollow">Preprocessor Directives</a> to determine if cookie-less sessions should be used. See, by building in a specific configuration for a specific environment I'm able to make some assumptions about the environment and what it's used for. This would allow me to technically have two users logged in at the same time and the tester could test multiple scenarios from the same browser session without ever logging out of any of those server sessions.</p> <p>However, this approach has some serious caveats. Not least of which is the fact that what the tester is testing is <strong>not</strong> what's going to run in production.</p> <p>So I think I've got to say, this is ultimately a <strong>bad idea.</strong></p>
48,132
<p>I have seen posts that show three ways to reset the DMV views:</p> <ol> <li>Reset the SQL Service</li> <li>Detatch the database</li> <li>Close the database</li> </ol> <p>All of these methods seem to require taking the system off-line for a few moments. Is there a way to reset the statistics on demand without interrupting use of the database? When we have odd performance issues come up in production it is useful to limit the data in the dmv views to data collected during the duration of the performance issue to help describe the state of the system during the performance issue.</p>
<p>You can <a href="http://msdn.microsoft.com/en-us/library/ms189768(SQL.90).aspx" rel="nofollow noreferrer">reset exactly 2 DMVs</a> only (BOL link)</p> <pre><code>sys.dm_os_latch_stats sys.dm_os_wait_stats </code></pre>
<p>As far as I know, these views will only be updated when the instance is restarted.</p> <p>However, for some views you could take a copy of the data before you start measuring and doing a diff afterwards. </p>
38,138
<p>I'm developing a small utility application that needs to detect whether another one has one of its MDI child windows open (it's an off-the-shelf Win32 business application over which I have neither source code nor control). From my app, I would like to be able to poll or detect when a particular MDI Child window is open.</p> <p>In .Net, it's easy to iterate over running processes, but I haven't found an easy way to iterate through the (sub)windows and controls of a given Win32 process from .Net.</p> <p>Any ideas?</p> <p><strong>Update</strong><br> Thanks for the answers they got me on the right path.<br> I found an <a href="http://www.vbaccelerator.com/home/NET/Code/Libraries/Windows/Enumerating_Windows/article.asp" rel="nofollow noreferrer">article with a test project</a> that uses both <code>EnumWindows</code>and <code>EnumChidWindows</code> and other API calls to get extended information on controls.</p>
<p>You must use native Win32 API.</p> <p><a href="http://www.pinvoke.net/default.aspx/user32/EnumChildWindows.html" rel="noreferrer">EnumChildWindows (user32)</a></p> <p><code></p> <pre><code>[DllImport("user32")] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool EnumChildWindows(IntPtr window, EnumWindowProc callback, IntPtr i); /// &lt;summary&gt; /// Returns a list of child windows /// &lt;/summary&gt; /// &lt;param name="parent"&gt;Parent of the windows to return&lt;/param&gt; /// &lt;returns&gt;List of child windows&lt;/returns&gt; public static List&lt;IntPtr&gt; GetChildWindows(IntPtr parent) { List&lt;IntPtr&gt; result = new List&lt;IntPtr&gt;(); GCHandle listHandle = GCHandle.Alloc(result); try { EnumWindowProc childProc = new EnumWindowProc(EnumWindow); EnumChildWindows(parent, childProc, GCHandle.ToIntPtr(listHandle)); } finally { if (listHandle.IsAllocated) listHandle.Free(); } return result; } /// &lt;summary&gt; /// Callback method to be used when enumerating windows. /// &lt;/summary&gt; /// &lt;param name="handle"&gt;Handle of the next window&lt;/param&gt; /// &lt;param name="pointer"&gt;Pointer to a GCHandle that holds a reference to the list to fill&lt;/param&gt; /// &lt;returns&gt;True to continue the enumeration, false to bail&lt;/returns&gt; private static bool EnumWindow(IntPtr handle, IntPtr pointer) { GCHandle gch = GCHandle.FromIntPtr(pointer); List&lt;IntPtr&gt; list = gch.Target as List&lt;IntPtr&gt;; if (list == null) { throw new InvalidCastException("GCHandle Target could not be cast as List&lt;IntPtr&gt;"); } list.Add(handle); // You can modify this to check to see if you want to cancel the operation, then return a null here return true; } /// &lt;summary&gt; /// Delegate for the EnumChildWindows method /// &lt;/summary&gt; /// &lt;param name="hWnd"&gt;Window handle&lt;/param&gt; /// &lt;param name="parameter"&gt;Caller-defined variable; we use it for a pointer to our list&lt;/param&gt; /// &lt;returns&gt;True to continue enumerating, false to bail.&lt;/returns&gt; public delegate bool EnumWindowProc(IntPtr hWnd, IntPtr parameter); </code></pre> <p></code></p>
<p>You can use P/Invoke to access EnumWindows and EnumChidWindows to itereate through the subwindows/controls of any window.</p>
35,520
<p>Example: I have two shared objects (same should apply to .dlls). The first shared object is from a third-party library, we'll call it libA.so. I have wrapped some of this with JNI and created my own library, libB.so. Now libB depends on libA.</p> <p>When webstarting, both libraries are places in some webstart working area. My java code attempts to load libB. At this point the system loader will attempt to load libA which is not in the system library path (java.library.path won't help this). The end result is that libB has an unsatisfied link and cannot be used. </p> <p>I have tried loading libA before libB, but that still does not work. Seems the OS wants to do that loading for me. Is there any way I can make this work other than statically compiling?</p>
<p>Static compilation proved to be the only way to webstart multiple dependent native libraries.</p>
<p>Are both native libraries packaged into a <em>signed</em> jar which is listed as</p> <pre><code>&lt;nativelib ...&gt; </code></pre> <p>In the JNLP file?</p>
2,664
<p>Can one be simulated by periodicly syncing with GPS and in the meen while working with the accelerometer? I know for example that the N95 accelerometer is invarient to rotation on the Y axis (while beeing face up/down).</p>
<p>The original iPhone and the iPhone 3G use GPS to calculate the heading, however the iPhone 3GS now has a 3-dimensional magnetometer compass in it.</p> <p>This can only be done taking two GPS coordinates (while moving) and determining the direction from point A to B.</p>
<p>Extra info: The IPHONE 1 did not have GPS or compass.</p>
6,431
<p>Rep steps:</p> <ol> <li>create example .NET form application</li> <li>put a TextBox on the form</li> <li>wire a function up to the TextBox's Enter event</li> </ol> <p>When you run this application, the <strong>Control.Enter</strong> event fires when focus first goes to the TextBox. However, if you click away into another application and then click back into the test application, the event will not fire again.</p> <p>So <strong>moving between applications does not trigger Enter/Leave</strong>.</p> <p>Is there another alternative <em>Control-level</em> event that I can use, which will fire in this scenario?</p> <p>Ordinarily, I would use <strong>Form.Activated</strong>. Unfortunately, that is troublesome here because my component is hosted by a docking system that can undock my component into a new Form without notifying me.</p>
<p>What are you trying to do in the Enter event?</p> <p>I can't find another control-level event that fires in your example program but when my test app does regain focus, the control that last had focus still has it.</p> <p>Interesting question but it needs a little more context.</p>
<p>in this example if you toggle between clicking the textboxes neither the enter or got focus will do as expected, however if you click the child forms instead both will behave as expected.</p> <pre><code> using System; using System.Collections.Generic; using System.Linq; using System.Windows.Forms; namespace EnterBrokenExample { static class Program { /// &lt;summary&gt; /// The main entry point for the application. /// &lt;/summary&gt; [STAThread] static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Form Form1 = new Form(); Form c1 = new Form(); Form c2 = new Form(); Form1.IsMdiContainer = true; c1.MdiParent = Form1; c2.MdiParent = Form1; c1.Show(); c2.Show(); TextBox tb1 = new TextBox(); c1.Controls.Add(tb1); tb1.Enter += ontbenter; tb1.Text = "Some Text"; tb1.GotFocus += ongotfocus; TextBox tb2 = new TextBox(); c2.Controls.Add(tb2); tb2.Enter += ontbenter; tb2.Text = "some other text"; tb2.GotFocus += ongotfocus; Application.Run(Form1); } static void ontbenter(object sender, EventArgs args) { if (!(sender is TextBox)) return; TextBox s = (TextBox)sender; s.SelectAll(); } static void ongotfocus(object sender, EventArgs args) { if (!(sender is TextBox)) return; TextBox s = (TextBox)sender; s.SelectAll(); } } } </code></pre>
18,787
<p>I have an array with holes that I have to fill with different materials. My question is there is an easy way to fill them directly? I tried array, array draft and it is annoying to adjust them. In Blender, it easy to select the vertices and fill. Maybe it is a stupid question, but I am not really an expert.</p> <p><a href="https://i.stack.imgur.com/7VwUW.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/7VwUW.png" alt="enter image description here" /></a></p>
<h1>The problem</h1> <p>FDM printers slice models in STL or OBJ format. Neither of these formats can transmit properties like <em>Materials</em>: they consist <strong>fully</strong> of surface definitions.</p> <h1>But... Multi-Material printing is a thing, yes?</h1> <p>Yes, but Multi-material prints use a simple trick: a single STL object can contain <em>more</em> than one surface definition, and you can slice more than one STL at once. But since slicers usually can't separate these from one another, they usually load multiple STLs and define the materials for each differently. For example, <a href="https://www.thingiverse.com/thing:3197896" rel="nofollow noreferrer">Adalinda</a> has 4 different STLs, some containing multiple chunks of material, each STL corresponding to one printed color. And <a href="https://youtu.be/MnOWX4Ujtv8?list=TLPQMDIwMjIwMjHXGYYAQZ7qbw" rel="nofollow noreferrer">in this video Joel</a> explains how printing that way works for an older version of the MMU.</p> <p>So, to print the &quot;cubes&quot; in a different material, you'd need to have two STLs: The grid as one export, and the cubes as another. Then the <strong>Rest</strong> is slicing.</p> <h1>Way around?</h1> <p>Now, you might not have a Multi-Material Printer? Then you might want to design your item in parts that snap into place or have an interference fit. For example, you might print a plate with all the cubes on one side, and a grid that has a relief on the back where the plate goes. Then you print two times with different materials and push the cube part into the grate, some glue in between, and voila! It looks like one print from the surface. With a clamshell design, you might even completely hide the existence of the carrier plate - by having two grates that surround a hollow cavity for the cube-plate, and the cube plate pushes out into either of the clamshells.</p>
<p>If you are asking for print then it is yes with FDM (fused deposition modeling) with multiple extrusion you can fill with different material easily. But if you are trying to change the material in your digital design then you need to work on every hole in the array, especially with FreeCAD. If you find any, please update here.</p>
1,830
<p>I couldn't find any useful information on Microsoft's site, so here is the question: has the compiler in Visual C++ 2008 been improved significantly since the 2005 version? I'm especially looking for better optimization.</p>
<p>Straight from the horses mouth....</p> <blockquote> <p><a href="http://msdn.microsoft.com/en-us/library/bb384632.aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/bb384632.aspx</a></p> </blockquote>
<p>In my experience, compiler optimizations rarely improve more than a few percent between versions at most; if you really need more performance, that few percent just isn't going to cut it--you're going to have to get down and dirty in the code if you want more.</p> <p>Remember, compilers are extremely dumb, and can usually be outwitted by a smart programmer; the only question is whether its worth your time and effort to do so. If you have a single core function that makes up 90% of your CPU time, it might definitely be so. If runtime is spread equally over ten thousand lines of code, probably not.</p> <p>Of course, if your speed problem is due to slow algorithms, no compiler can save you.</p>
14,532
<p>Can these two SVN clients collaborate? I have my projects checked out with Tortoise, but now I would like to be able to use the SVN functionality (mostly updating and committing) from inside Eclipse. But the Subcipse doesn't see the SVN status of the files checked out by Tortoise.</p> <p>I'm doing similar with Tortoise and MSVS plugin Ankh SVN and it works great. But now I need it to work in Eclipse...</p> <p>Thanks</p>
<p>When you check code out of Subversion to create a "sandbox", the directories all contain meta-data in the .svn directory. Any client you try to use against the "sandbox" will (assuming the client version is not behind the server), read the meta-data and understand the state of the sandbox and how to manage it with respect to the server.</p> <p>So ... Yes, it will work just fine;)</p>
<p>Watchout for versions as mentioned before. For example Tortoise (1.8.2) requires Subversion 1.10 at Eclipse side. Update site: <a href="http://subclipse.tigris.org/update_1.10.x" rel="nofollow">http://subclipse.tigris.org/update_1.10.x</a></p>
47,352
<p>How do I implement a Copy menu item in a Windows application written in C#/.NET 2.0?</p> <p>I want to let the user to mark some text in a control and then select the Copy menu item from an Edit menu in the menubar of the application and then do a Paste in for example Excel. </p> <p>What makes my head spin is how to first determine which child form is active and then how to find the control that contains the marked text that should be copied to the clipboard. </p> <p>Help, please.</p>
<p>With the aid of some heavy pair programming a colleague of mine and I came up with this, feel free to refactor.</p> <p>The code is placed in the main form. The copyToolStripMenuItem_Click method handles the Click event on the Copy menu item in the Edit menu.</p> <pre><code> /// &lt;summary&gt; /// Recursively traverse a tree of controls to find the control that has focus, if any /// &lt;/summary&gt; /// &lt;param name="c"&gt;The control to search, might be a control container&lt;/param&gt; /// &lt;returns&gt;The control that either has focus or contains the control that has focus&lt;/returns&gt; private Control FindFocus(Control c) { foreach (Control k in c.Controls) { if (k.Focused) { return k; } else if (k.ContainsFocus) { return FindFocus(k); } } return null; } private void copyToolStripMenuItem_Click(object sender, EventArgs e) { Form f = this.ActiveMdiChild; // Find the control that has focus Control focusedControl = FindFocus(f.ActiveControl); // See if focusedControl is of a type that can select text/data if (focusedControl is TextBox) { TextBox tb = focusedControl as TextBox; Clipboard.SetDataObject(tb.SelectedText); } else if (focusedControl is DataGridView) { DataGridView dgv = focusedControl as DataGridView; Clipboard.SetDataObject(dgv.GetClipboardContent()); } else if (...more?...) { } } </code></pre>
<p>It seems to me that you might be better off breaking this into smaller tasks/questions. You have a few issues you are stuck on from the way it sounds.</p> <p>You have multiple 'child' windows open. Is this an MDI application? When an action is performed on one of those child windows, it should fire an event in that window's event handlers. That is your first thing to set up. If this is a datagridview I would suggest a simple test to start. Try trapping the <a href="http://msdn.microsoft.com/en-us/library/system.windows.forms.datagridview.selectionchanged.aspx" rel="nofollow noreferrer">DataGridView.SelectionChanged</a> event. Just throw in something like <code>MessageBox.Show("I copied your datas!");</code> for now.</p> <p>This should get you started where you will at least understand how this event will be raised to you.</p> <p>From here, we will need to know a little more about your datagrid, and the rows and child controls in those rows. Then we can likely create events in the render events that will be raised at the appropriate times, with the appropriate scope.</p>
8,826
<p>We are currently evaluating different applications that interface with Visual Studio 2008 (C#) and Subversion to do automated builds of our core libraries. We are hoping to have nightly builds performed and either email the list of changes made to each developer or have the latest versions be pushed to each workstation. What has been your experience with these tools and what are some recommendations?</p> <hr> <p><strong>Suggested software</strong></p> <ul> <li><a href="http://confluence.public.thoughtworks.org/display/CCNET/Welcome+to+CruiseControl.NET" rel="nofollow noreferrer">Cruise Control .NET</a></li> <li><a href="http://hudson-ci.org/" rel="nofollow noreferrer">Hudson</a></li> <li><a href="http://www.jetbrains.com/teamcity/" rel="nofollow noreferrer">TeamCity</a></li> </ul> <p><strong>Suggested articles</strong></p> <ul> <li><a href="http://dotnet.org.za/cjlotz/archive/2008/01/15/continuous-integration-from-theory-to-practice-2nd-edition.aspx" rel="nofollow noreferrer">Continuous Integration: From Theory to Practice 2nd Edition (CC.net)</a></li> <li><a href="http://blogs.freshlogicstudios.com/Posts/View.aspx?Id=87a1c0f7-a75e-4f1a-8d3a-6c52c6ad9f46" rel="nofollow noreferrer">Automating Your ASP.NET Build and Deploy Process with Hudson</a></li> </ul>
<p>Cruise Control.net (ccnet) does everything you are looking for. Its pretty easy to use, just make sure if you are going to run it as a service, you give it an account and don't make it run as network service, that way you can give it rights on intranet boxes and have it do xcopy deploys.</p> <p>It has all kinds of email modes, on failure, on all, on fix after failure, and many many more.</p>
<p>A couple of tidbits about working with cc.net and msbuild. If you are building C/C+= projects, msbuild is, um, unreliable at least with VS 2005 (and perhaps earlier). I have not tested with VS 2008. We found that sometimes msbuild would work properly, sometimes not. In trying to solve the problem, we found vcbuild.exe which seems to work well in place of msbuild when building C/C++ solutions.</p>
7,513
<p>In an Outlook 2003 macro; Is there a way to move a message between folders without changing the ReceivedTime-header?</p> <p>I currently use the method <code>MailItem.Move</code>. But that automatically sets the <code>ReceivedTime</code> property to the current time, which isn't really what I want.</p>
<p>I just tried moving a mailitem from my inbox to the deleted items folder, and it seems to have kept the receivedtime without a problem...</p> <p>You may want to try using the MailItem.copy function and moving the resulting mailitem object, but like I said I'm not seeing the same problem...</p> <p>Hope that helps...</p>
<p>Do an item.Save() and then do item.Move(), It will stamp current timestamp.</p>
8,305
<p>Ok, I've run across my first StackOverflowError since joining this site, I figured this is a must post :-). My environment is Seam 2.0.1.GA, JBoss 4.2.2.GA and I'm using JSF. I am in the process of converting from a facelets view to JSP to take advantage of some existing JSP tags used on our existing site. I changed the faces-config.xml and the web.xml configuration files and started to receive the following error when trying to render a jsp page. Anyone have any thoughts?</p> <blockquote> <p>2008-09-17 09:45:17,537 DEBUG [org.jboss.seam.contexts.FacesLifecycle] Begin JSF request for /form_home.jsp 2008-09-17 09:45:17,587 ERROR [org.apache.catalina.core.ContainerBase.[jboss.web].[localhost].[/].[Faces Servlet]] Servlet.service() for servlet Faces Servlet threw exception java.lang.StackOverflowError at org.apache.catalina.core.ApplicationHttpRequest.getAttribute(ApplicationHttpRequest.java:210) at org.apache.catalina.core.ApplicationHttpRequest.getAttribute(ApplicationHttpRequest.java:222) at org.apache.catalina.core.ApplicationHttpRequest.getAttribute(ApplicationHttpRequest.java:222) at org.apache.catalina.core.ApplicationHttpRequest.getAttribute(ApplicationHttpRequest.java:222) ...</p> </blockquote> <p>My faces-config.xml file is now empty with no FaceletsViewHandler:</p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;faces-config version="1.2" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xi="http://www.w3.org/2001/XInclude" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-facesconfig_1_2.xsd"&gt; &lt;/faces-config&gt; </code></pre> <p>And my Web.xml file:</p> <pre><code>&lt;?xml version="1.0"?&gt; &lt;web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"&gt; &lt;!-- Ajax4jsf --&gt; &lt;context-param&gt; &lt;param-name&gt;org.richfaces.SKIN&lt;/param-name&gt; &lt;param-value&gt;blueSky&lt;/param-value&gt; &lt;/context-param&gt; &lt;!-- Seam --&gt; &lt;listener&gt; &lt;listener-class&gt;org.jboss.seam.servlet.SeamListener&lt;/listener-class&gt; &lt;/listener&gt; &lt;filter&gt; &lt;filter-name&gt;Seam Filter&lt;/filter-name&gt; &lt;filter-class&gt;org.jboss.seam.servlet.SeamFilter&lt;/filter-class&gt; &lt;/filter&gt; &lt;filter-mapping&gt; &lt;filter-name&gt;Seam Filter&lt;/filter-name&gt; &lt;url-pattern&gt;*.jsp&lt;/url-pattern&gt; &lt;/filter-mapping&gt; &lt;servlet&gt; &lt;servlet-name&gt;Seam Resource Servlet&lt;/servlet-name&gt; &lt;servlet-class&gt;org.jboss.seam.servlet.SeamResourceServlet &lt;/servlet-class&gt; &lt;/servlet&gt; &lt;servlet-mapping&gt; &lt;servlet-name&gt;Seam Resource Servlet&lt;/servlet-name&gt; &lt;url-pattern&gt;/seam/resource/*&lt;/url-pattern&gt; &lt;/servlet-mapping&gt; &lt;!-- Seam end --&gt; &lt;!-- JSF --&gt; &lt;context-param&gt; &lt;param-name&gt;javax.faces.DEFAULT_SUFFIX&lt;/param-name&gt; &lt;param-value&gt;.jsp&lt;/param-value&gt; &lt;/context-param&gt; &lt;servlet&gt; &lt;servlet-name&gt;Faces Servlet&lt;/servlet-name&gt; &lt;servlet-class&gt;javax.faces.webapp.FacesServlet&lt;/servlet-class&gt; &lt;load-on-startup&gt;1&lt;/load-on-startup&gt; &lt;/servlet&gt; &lt;servlet-mapping&gt; &lt;servlet-name&gt;Faces Servlet&lt;/servlet-name&gt; &lt;url-pattern&gt;*.jsp&lt;/url-pattern&gt; &lt;/servlet-mapping&gt; </code></pre>
<p>I was able to figure out this problem. Apparently you can not configure web.xml to have the same param-value of .jsp for Javax.faces.DEFAULT_SUFFIX as the Faces Servlet url-pattern (*.jsp). If you change your url-pattern to <em>.jspx or to /whateverdirnameyouwant/</em> the application starts up with no stack overflow errors. (note: the key is that DEFAULT_SUFFIX and Faces Servlet url-pattern cannot be the same regardless of what they are.) Hope this helps anyone else that experiences this specific problem.</p>
<p>So, I had a similar error. For me, it was that I had a JSF project and I was messing around with the file extensions. To start with, I had all my web files with extension .jsp. This was working, but then I wanted them to be all .jsf, then after that I went all in on using .xhtml. In the process, my web.xml file changed to accomodate xhtml and jsf. Changing the web.xml file was fine. What got me the StackOverflowError was that I had index.xhtml with a ui.include tag pointing to header.jsf. So I had a xhtml file pointing to a jsf file. I had thought that web.xml would be able to handle this, but it did not, I got the StackOverflowError. So, to fix this, now all my JSF files have extension .xhtml, and nested ui:include tags point to .xhtml files.</p> <p>On the flip side, though, the browser url can handle the index.jsp, index.jsf, index.xhtml just fine. So the web.xml (with servlet mappings for jsp, jsf and xhtml) handles the browser url just fine, but not for what my problem above highlighted.</p>
11,111
<p>Any suggestion how I can document my Perl code? What do you use and what tools are available to help me?</p> <p>Which module do you use to convert pod to html?</p>
<p>Look inside almost any Perl module and you'll see the <a href="http://perldoc.perl.org/perlpod.html" rel="noreferrer">Plain Old Documentation (POD)</a> format. On <a href="http://search.cpan.org" rel="noreferrer">CPAN Search</a>, when looking at a module you have the option of viewing the raw source, so that's one way you can look at the raw pod, but you can also use <a href="http://perldoc.perl.org/perldoc.html" rel="noreferrer">perldoc</a> from the command line. The <code>-m</code> switch shows you the file</p> <pre><code>perldoc -m Foo::Bar </code></pre> <p>Or, if you want to find the file so you can look at it in your favorite editor, use the <code>-l</code> switch to find it:</p> <pre><code>perldoc -l Foo::Bar </code></pre> <p>Once you start documenting your program, you put the Pod in the file right with the code, either interwoven with the code so the documentation is next to the relevant parts, or at the beginning, middle, or end as one big chunk.</p> <p>Pod is easily translated to several other formats, such as LaTeX, Postscript, HTML, and so on with translators that come with Perl (pod2latex, pod2ps, pod2html). I even have a pod translator that goes to InDesign. Writing your own Pod translator is easy with <a href="http://search.cpan.org/dist/Pod-Simple" rel="noreferrer">Pod::Simple</a>, so if you don't find a translator to your favorite final form, just make it yourself.</p> <p>There are also several tools that you can add to your test suite to check your Pod. The <a href="http://search.cpan.org/dist/Test-Pod" rel="noreferrer">Test::Pod</a> module checks for format errors, the <a href="http://search.cpan.org/dist/Test-Pod-Coverage" rel="noreferrer">Test::Pod::Coverage</a> module checks the you've documented each subroutine, and so on. You also might be interested in my <a href="http://www.perlmonks.org/?node_id=408254" rel="noreferrer">Perl documentation documentation</a>.</p>
<p>You might also want to check out <a href="https://rads.stackoverflow.com/amzn/click/com/0596001738" rel="nofollow noreferrer" rel="nofollow noreferrer">Perl Best Practices</a> by Damian Conway. I used some of the tips to clean up a small Perl code base I inherited.</p>
23,155
<p>In my application I keep a LINQ object fetched from the database, and regularly modifies it followed by <code>db.SubmitChanges()</code>.</p> <p>I have read that you are not supposed to keep around the <code>DataContext</code> object for a long time. But if I close my <code>DataContext</code> between modifications, I guess the data object loses its link to the actual database row.</p> <p>What is the best alternative to keeping the DataContext open? Do I really have to reload the row every time I want to update it?</p>
<p>otherwise you could execute a direct SQL query against the database to make the update as quick as possible. </p> <p>Due to concurrency issues the default Linq UPDATE statement is not be most optimal due to excessive compares. take a look in SQL profiler or use the Linq SQL visualizer.</p> <p>//andy</p>
<p>Reloading the row when you want to update it shouldn't be much of a performance hit, and it will guarantee that you are updating the latest version of the row (in case another user/process has modified it since you first opened it).</p> <p>If you know nothing else will be updating the row, then you could probably keep the DataContext around without much of a problem (barring a loss of connection to the database).</p>
30,602
<p>I came across a printed <a href="http://www.eiffel.com/general/column/2008/02.html" rel="nofollow noreferrer">article by Bertrand Meyer</a> where he states that tests can be generated from specifications. My development team does nothing like this, but it sounds like a good technique to consider. How are you generating tests from specifications? How would you describe the success your having in discovering program faults via this method?</p>
<p>This might be a reference to <a href="http://rspec.info/" rel="nofollow noreferrer">RSpec</a>, which is a really clever way of developing tests as a series of requirements. I'm still getting used to it, but it's been very handy in both defining what I need to do and then ensuring I do it.</p>
<p>I would say it depends on your specs. I have yet to work anywhere where the specs were good enough to create full unit tests from specifications - the level of detail just wasn't there. My managers always told us that if we specified to that level they could just ship the specs off to India and get it coded on the cheap ;)</p>
4,877
<p>Working on implementing TFS throughout our organization. It is easy to integrate with <code>.NET</code> projects and any platform that uses Eclipse or a derivative of Eclipse for editing.<br> What's the best way to use TFS version control with Xcode (now that I find out we need to write some iPhone apps)?</p>
<p>Xcode integration is something that we at <a href="http://www.teamprise.com" rel="noreferrer">Teamprise</a> have been looking into a lot. One of the main problems for us is that Apple does not provide a version control API that we can hook into to add a new version control system to Xcode - for integrated version control it is either the systems that Apple provide access to or nothing at the moment.</p> <p>That said, we do have a number of customers who develop in Xcode for TFS. They either use <a href="http://www.teamprise.com/products/explorer/" rel="noreferrer">Teamprise Explorer</a> (which is a standalone GUI client to TFS compiled as a Universal Binary) or they have macros inside Xcode that perform basic check-out and get operations in-conjunction with the <a href="http://www.teamprise.com/products/clc/" rel="noreferrer">TFS command line (tf)</a>. It's obviously not the ideal experience but acceptable for them. The stand-alone GUI has the advantage that you can do all the work item tracking stuff there as well and integrate this with your check-ins.</p> <p>Sorry if this is a very "marketing" type answer - just trying to let you know what our current customers do with Xcode. If you want more details around the macro approach then let me know.</p> <p>Hope that helps,</p> <p>Martin.</p>
<p>The biggest problem with this is that Xcode only runs on OS X and TFS client tools only run on Windows. If you're host operating system in OS X and you have a Windows virtual environment running locally (like Parallels or VMFusion) then you could use Team Explorer or the command-line tools to work with the repository.</p> <p>But this is a lot of work just to use a really dated version control system. If you don't have to use TFS I would probably use SVN or something else with native OS X support.</p>
9,567
<p>I'm using the <a href="http://docs.jquery.com/UI/Sortables" rel="noreferrer">jQuery UI sortables</a> plugin to allow re-ordering of some list items. Inside each list item, I've got a couple of radio buttons which allow the item to be enabled or disabled.</p> <p>When the item is dragged, both radio buttons get deselected, which doesn't seem like it should be happening. Is this correct behavior, and if not, what is the best way to work around this?</p> <p>Here is a code sample demonstrating this problem:</p> <pre><code>&lt;!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"&gt; &lt;html xmlns="http://www.w3.org/1999/xhtml" &gt; &lt;head&gt; &lt;title&gt;jQuery Sortables Problem&lt;/title&gt; &lt;script src="jquery-1.2.6.min.js" type="text/javascript"&gt;&lt;/script&gt; &lt;script src="jquery-ui.min.js" type="text/javascript"&gt;&lt;/script&gt; &lt;style type="text/css"&gt; .items { margin-top: 30px; margin-left: 0px; padding-left: 25px; cursor: move; } .items li { padding: 10px; font-size: 15px; border: 1px solid #666; background: #eee; width: 400px; margin-bottom: 15px; float: left; clear:both; } &lt;/style&gt; &lt;/head&gt; &lt;body&gt; &lt;ol id="itemlist" class="items"&gt; &lt;li id="1" class="item"&gt; Item 1 &lt;input name="status_1" type="radio" value="1" checked="checked" /&gt;enabled &lt;input name="status_1" type="radio" value="0" /&gt;disabled &lt;/li&gt; &lt;li id="2" class="item"&gt; Item 2 &lt;input name="status_2" type="radio" value="1" checked="checked" /&gt;enabled &lt;input name="status_2" type="radio" value="0" /&gt;disabled &lt;/li&gt; &lt;li id="3" class="item"&gt; Item 3 &lt;input name="status_3" type="radio" value="1" checked="checked" /&gt;enabled &lt;input name="status_3" type="radio" value="0" /&gt;disabled &lt;/li&gt; &lt;li id="4" class="item"&gt; Item 4 &lt;input name="status_4" type="radio" value="1" checked="checked" /&gt;enabled &lt;input name="status_4" type="radio" value="0" /&gt;disabled &lt;/li&gt; &lt;/ol&gt; &lt;script type="text/javascript"&gt; $('#itemlist').sortable(); &lt;/script&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>As soon as a list item is grabbed with the mouse, both the radio buttons get deselected.</p> <p>If this is a bug, one workaround would be to automatically select the 'enabled' radio button when the item is moved, so any advice on how to achieve this would also be most appreciated.</p> <p>Update: I've tested this in FireFox 3, Internet Explorer 7, Opera 9.5, and Safari 3.1.2, all on Windows XP x64, and this issue occurs in all of them.</p>
<p>It may not be exactly what you're looking for, but changing</p> <pre><code>$('#itemlist').sortable(); </code></pre> <p>to</p> <pre><code>$('#itemlist').sortable({placeholder: ".items li"}); </code></pre> <p>keeps the radio button selections.</p>
<p>Is this in Internet Explorer? IE is known to lose the selection of checkboxes and radios when copied/moved.</p> <p><a href="http://webbugtrack.blogspot.com/2007/11/bug-299-setattribute-checked-does-not.html" rel="nofollow noreferrer">http://webbugtrack.blogspot.com/2007/11/bug-299-setattribute-checked-does-not.html</a></p> <p>defaultChecked needs to be reset for IE to behave</p>
36,182
<p>Can any body tell me the differences between them?</p>
<p>In the C standard, a standalone implementation doesn't have to provide all of the library functions that a hosted implementation has to provide. The C standard doesn't care about embedded, but vendors of embedded systems usually provide standalone implementations with whatever amount of libraries they're willing to provide.</p> <p>C is a widely used general purpose high level programming language mainly intended for system programming.</p> <p>Embedded C is an extension to C programming language that provides support for developing efficient programs for embedded devices.It is not a part of the C language</p> <p>You can also refer to the articles below:</p> <ul> <li><a href="http://www.differencebetween.info/difference-between-c-and-embedded-c" rel="noreferrer">Difference between C and Embedded C</a> </li> <li><a href="http://en.wikipedia.org/wiki/Embedded_C" rel="noreferrer">Embedded C</a> </li> <li><a href="http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1169.pdf" rel="noreferrer">ISO/IEC J TC1 SC22 WG14 N1169</a></li> </ul>
<p>C is a only programming language its used in system programming. but embedded C is used to implement the projects like real time applications </p>
28,796
<p>When I browse code in Vim, I need to see opening and closing parenthesis/ brackets, and pressing <kbd>%</kbd> seems unproductive.</p> <p>I tried <code>:set showmatch</code>, but it makes the cursor jump back and forth when you type in a bracket. But what to do if I am browsing already written code?</p>
<pre><code>DoMatchParen </code></pre> <p>in your <code>.vimrc</code> file</p> <p>or</p> <pre><code>:DoMatchParen </code></pre> <p>within vim itself.</p> <p>Edit: This comes from the <a href="http://vimdoc.sourceforge.net/htmldoc/pi_paren.html" rel="noreferrer">pi_paren</a> plugin (which is a standard plugin).</p>
<p>Maybe what you want is this plugin:</p> <p><a href="http://www.vim.org/scripts/script.php?script_id=350" rel="nofollow noreferrer">http://www.vim.org/scripts/script.php?script_id=350</a></p>
28,749
<p>What is Big O notation? Do you use it?</p> <p>I missed this university class I guess :D</p> <p>Does anyone use it and give some real life examples of where they used it?</p> <hr /> <h3>See also:</h3> <p><a href="https://stackoverflow.com/questions/107165/big-o-for-eight-year-olds">Big-O for Eight Year Olds?</a><br /> <a href="https://stackoverflow.com/questions/3255/big-o-how-do-you-calculateapproximate-it">Big O, how do you calculate/approximate it?</a><br /> <a href="https://stackoverflow.com/questions/111426/did-you-apply-computational-complexity-theory-in-real-life">Did you apply computational complexity theory in real life?</a></p>
<p>One important thing most people forget when talking about Big-O, thus I feel the need to mention that:</p> <p>You cannot use Big-O to compare the <strong>speed</strong> of two algorithms. Big-O only says how much slower an algorithm will get (approximately) if you double the number of items processed, or how much faster it will get if you cut the number in half.</p> <p>However, if you have two entirely different algorithms and one (<code>A</code>) is <code>O(n^2)</code> and the other one (<code>B</code>) is <code>O(log n)</code>, it is not said that <code>A</code> is slower than <code>B</code>. Actually, with 100 items, <code>A</code> might be ten times faster than <code>B</code>. It only says that with 200 items, <code>A</code> will grow slower by the factor <code>n^2</code> and <code>B</code> will grow slower by the factor <code>log n</code>. So, if you benchmark both and you know how much time <code>A</code> takes to process 100 items, and how much time <code>B</code> needs for the same 100 items, and <code>A</code> is faster than <code>B</code>, you can calculate at what amount of items <code>B</code> will overtake <code>A</code> in speed (as the speed of <code>B</code> decreases much slower than the one of <code>A</code>, it will overtake <code>A</code> sooner or later—this is for sure).</p>
<p>It says how many iterations an algorithm has in the worst case.</p> <p>to search for an item in an list, you can traverse the list until you got the item. In the worst case, the item is in the last place.</p> <p>Lets say there are n items in the list. In the worst case you take n iterations. In the Big O notiation it is O(n).</p> <p>It says factualy how efficient an algorithm is.</p>
16,108
<p>There are many posts on the internet about the ReadDirectoryChangesW API function missing files when there is a lot of file activity. Most blame the speed at which the ReadDirectoryChangesW function loop is called. This is an incorrect assumption. The best explanation I have seen is in the following post, the comment on Monday, April 14, 2008 2:15:27 PM</p> <p><a href="http://social.msdn.microsoft.com/forums/en-US/netfxbcl/thread/4465cafb-f4ed-434f-89d8-c85ced6ffaa8/" rel="noreferrer">http://social.msdn.microsoft.com/forums/en-US/netfxbcl/thread/4465cafb-f4ed-434f-89d8-c85ced6ffaa8/</a></p> <p>The summary is that the ReadDirectoryChangesW function reports file changes as they leave the file-write-behind queue, not as they are added. And if too many are added before being committed, you lose notice on some of them. You can see this with your implementation, if you just write a program to generate a 1000+ files in a directory real quick. Just count how many file event notices you get and you will see there are times when you will not receive all of them.</p> <p>The question is, has anyone found a reliable method to use the ReadDirectoryChangesW function without having to flush the volume each time? This is not allowed if the user is not an Administrator and can also take some time to complete.</p>
<p>If the API is unreliable, then a workaround may be your only option. That of course likely involves keeping track of lastmodified and filenames. <s>What this doesn't mean is that you need to poll when looking for changes, rather, you can use the FileSystemWatcher as a means to trigger checking. </s></p> <p>So if you keep track of the last 50-100 times the ReadDirectoryChangesW<s>/FSW</s> event happened, and you see that it is being called rapidly, you can detect this and trigger the special condition to get all the files that have been changed (and set a flag to prevent future bogus FSW events temporarily) in a few seconds.</p> <p>Since some people are confused in the comments about this solution, I am proposing that you should monitor how fast events are arriving from the ReadDirectoryChangesW and when they are arriving too fast, try to attempt a workaround (usually a manual sweep of a directory). </p>
<p>I met same problem. But, I didn't find a solution that guarantee to get all of events. In several tests, I could know that ReadDirectoryChangesW function should be called again as fast as possible after GetQueuedCompletionStatus function returned. I guess if a processing speed of filesystem is very faster than my application processing speed, the application might be able to lose some events.</p> <p>Anyway, I separated a parsing logic from a monitoring logic and placed a parsing logic on a thread.</p>
8,147
<p>So, I am using the Linq entity framework. I have 2 entities: <code>Content</code> and <code>Tag</code>. They are in a many-to-many relationship with one another. <code>Content</code> can have many <code>Tags</code> and <code>Tag</code> can have many <code>Contents</code>. So I am trying to write a query to select all contents where any tags names are equal to <code>blah</code></p> <p>The entities both have a collection of the other entity as a property(but no IDs). This is where I am struggling. I do have a custom expression for <code>Contains</code> (so, whoever may help me, you can assume that I can do a "contains" for a collection). I got this expression from: <a href="http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=2670710&amp;SiteID=1" rel="nofollow noreferrer">http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=2670710&amp;SiteID=1</a></p> <h2>Edit 1</h2> <p><a href="https://stackoverflow.com/questions/110314/linq-to-entities-building-where-clauses-to-test-collections-within-a-many-to-ma#131551">I ended up finding my own answer.</a></p>
<p>After reading about the <a href="http://www.albahari.com/nutshell/predicatebuilder.aspx" rel="noreferrer">PredicateBuilder</a>, reading all of the wonderful posts that people sent to me, posting on other sites, and then reading more on <a href="http://blogs.msdn.com/meek/archive/2008/05/02/linq-to-entities-combining-predicates.aspx" rel="noreferrer">Combining Predicates</a> and <a href="http://msdn.microsoft.com/en-us/library/bb738681.aspx" rel="noreferrer">Canonical Function Mapping</a>.. oh and I picked up a bit from <a href="http://tomasp.net/blog/linq-expand.aspx" rel="noreferrer">Calling functions in LINQ queries</a> (some of these classes were taken from these pages). </p> <p>I FINALLY have a solution!!! Though there is a piece that is a bit hacked... </p> <p>Let's get the hacked piece over with :(</p> <p>I had to use reflector and copy the ExpressionVisitor class that is marked as internal. I then had to make some minor changes to it, to get it to work. I had to create two exceptions (because it was newing internal exceptions. I also had to change the ReadOnlyCollection() method's return from:</p> <pre><code>return sequence.ToReadOnlyCollection&lt;Expression&gt;(); </code></pre> <p>To:</p> <pre><code>return sequence.AsReadOnly(); </code></pre> <p>I would post the class, but it is quite large and I don't want to clutter this post any more than it's already going to be. I hope that in the future that class can be removed from my library and that Microsoft will make it public. Moving on...</p> <p>I added a ParameterRebinder class:</p> <pre><code>public class ParameterRebinder : ExpressionVisitor { private readonly Dictionary&lt;ParameterExpression, ParameterExpression&gt; map; public ParameterRebinder(Dictionary&lt;ParameterExpression, ParameterExpression&gt; map) { this.map = map ?? new Dictionary&lt;ParameterExpression, ParameterExpression&gt;(); } public static Expression ReplaceParameters(Dictionary&lt;ParameterExpression, ParameterExpression&gt; map, Expression exp) { return new ParameterRebinder(map).Visit(exp); } internal override Expression VisitParameter(ParameterExpression p) { ParameterExpression replacement; if (map.TryGetValue(p, out replacement)) { p = replacement; } return base.VisitParameter(p); } } </code></pre> <p>Then I added a ExpressionExtensions class:</p> <pre><code>public static class ExpressionExtensions { public static Expression&lt;T&gt; Compose&lt;T&gt;(this Expression&lt;T&gt; first, Expression&lt;T&gt; second, Func&lt;Expression, Expression, Expression&gt; merge) { // build parameter map (from parameters of second to parameters of first) var map = first.Parameters.Select((f, i) =&gt; new { f, s = second.Parameters[i] }).ToDictionary(p =&gt; p.s, p =&gt; p.f); // replace parameters in the second lambda expression with parameters from the first var secondBody = ParameterRebinder.ReplaceParameters(map, second.Body); // apply composition of lambda expression bodies to parameters from the first expression return Expression.Lambda&lt;T&gt;(merge(first.Body, secondBody), first.Parameters); } public static Expression&lt;Func&lt;T, bool&gt;&gt; And&lt;T&gt;(this Expression&lt;Func&lt;T, bool&gt;&gt; first, Expression&lt;Func&lt;T, bool&gt;&gt; second) { return first.Compose(second, Expression.And); } public static Expression&lt;Func&lt;T, bool&gt;&gt; Or&lt;T&gt;(this Expression&lt;Func&lt;T, bool&gt;&gt; first, Expression&lt;Func&lt;T, bool&gt;&gt; second) { return first.Compose(second, Expression.Or); } } </code></pre> <p>And the last class I added was PredicateBuilder:</p> <pre><code>public static class PredicateBuilder { public static Expression&lt;Func&lt;T, bool&gt;&gt; True&lt;T&gt;() { return f =&gt; true; } public static Expression&lt;Func&lt;T, bool&gt;&gt; False&lt;T&gt;() { return f =&gt; false; } } </code></pre> <p>This is my result... I was able to execute this code and get back the resulting "content" entities that have matching "tag" entities from the tags that I was searching for!</p> <pre><code> public static IList&lt;Content&gt; GetAllContentByTags(IList&lt;Tag&gt; tags) { IQueryable&lt;Content&gt; contentQuery = ... Expression&lt;Func&lt;Content, bool&gt;&gt; predicate = PredicateBuilder.False&lt;Content&gt;(); foreach (Tag individualTag in tags) { Tag tagParameter = individualTag; predicate = predicate.Or(p =&gt; p.Tags.Any(tag =&gt; tag.Name.Equals(tagParameter.Name))); } IQueryable&lt;Content&gt; resultExpressions = contentQuery.Where(predicate); return resultExpressions.ToList(); } </code></pre> <p>Please let me know if anyone needs help with this same thing, if you would like me to send you files for this, or just need more info.</p>
<p><em>NOTE: please edit the question itself, rather than replying with an answer -- this is not a discussion thread, and they can re-order themselves at any time</em></p> <p>If you're searching for all Contents that are marked with any one of a set of tags:</p> <pre><code>IEnumerable&lt;Tag&gt; otherTags; ... var query = from content in contentQuery where content.Tags.Intersection(otherTags).Any() select content; </code></pre> <p>It looks like you might be using LINQ To SQL, in which case it might be better if you write a stored procedure to do this one: using LINQ to do this will probably not run on SQL Server -- it's very likely it will try to pull down everything from <code>contentQuery</code> and fetch all the <code>.Tags</code> collections. I'd have to actually set up a server to check that, though.</p>
13,554
<p>I would like to customize the background (and maybe the border too) of all of the UITableViewCells within my UITableView. So far I have not been able to customize this stuff, so I have a bunch of white background cells which is the default.</p> <p>Is there a way to do this with the iPhone SDK?</p>
<p>You need to set the backgroundColor of the cell's contentView to your color. If you use accessories (such as disclosure arrows, etc), they'll show up as white, so you may need to roll custom versions of those.</p>
<p>If we can override your cell class, you can try this approach</p> <pre class="lang-swift prettyprint-override"><code>override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) selectionStyle = .none } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) backgroundColor = selected ? .red : .clear } </code></pre>
35,623
<p>After becoming somewhat estranged open source, and spending some years developing web applications in <a href="https://en.wikipedia.org/wiki/ASP.NET" rel="nofollow noreferrer">ASP.NET</a>, I'm going to start doing quite a lot of PHP / MySQL development.</p> <p>I've quite painlessly installed <a href="https://www.wampserver.com/en/" rel="nofollow noreferrer">WampServer</a> to get a development environment up and running on my Windows machine, but the platform I'll be targeting will most likely be Linux. Am I likely to run into problems due to developing on Windows while targeting Linux? Is it advisable to invest in getting a Linux environment setup in which to develop my LAMP applications?</p>
<p>If you can, I'd invest in some kind of Linux, or at least *nix, development environment. For simple applications and websites, your setup is fine, but you will eventually run into subtle differences when you deploy.</p> <p>Here are some things off the top of my head you'll want to watch out for if you stick with your Windows environment.</p> <ol> <li><p>File paths. A lot of PHP functions take file paths as arguments. Do <em>not</em> use the Windows backslash (\) separator. Even though you're on Windows, PHP will let you use a forward slash separator. Ideally abstract this away with your own file path class.</p> </li> <li><p>Apache Modules, PECL Extensions. Apache Windows and Apache Unix often come with a different set of Apache Modules installed by default. Also, the same version of a module may run differently on a different platform. If your application relies on <em>any</em> Apache module, make sure it's available for both platforms. The same goes for PHP custom extensions (PECL).</p> </li> <li><p>Process Forking. Using exec, `, etc. in a web application is a bad idea to begin with, but if you're using these functions they're going to behave differently between Windows and *nix</p> </li> <li><p>File writing, locking, etc. works different</p> </li> <li><p>Email is handled differently on both platforms</p> </li> <li><p>The PHP group's code word for Windows is &quot;some platforms&quot;. You can research more <a href="http://www.google.com/search?q=site%3Aphp.net+%22some+platforms%22&amp;btnG=Search" rel="nofollow noreferrer">on your own</a> if you'd like</p> </li> </ol> <p>In general, the closer your development environment matches your production environment, the fewer environment/deployment related issues you'll have.</p>
<p>No, because pretty much the only thing you can't do on WAMP if you target LAMP is using <a href="http://fr.php.net/manual/en/function.system.php" rel="nofollow noreferrer">System()</a>/<a href="http://fr.php.net/manual/en/book.exec.php" rel="nofollow noreferrer">Exec</a> Calls, and <strong>usually</strong> that is a good thing because those should be used very sparsely.</p>
28,163
<p>We need to regularly synchronize many dozens of binary files (project executables and DLLs) between many developers at several different locations, so that every developer has an up to date environment to build and test at. Due to nature of the project, updates must be done often and on-demand (overnight updates are not sufficient). This is not pretty, but we are stuck with it for a time.</p> <p>We settled on using a regular version (source) control system: put everything into it as binary files, get-latest before testing and check-in updated DLL after testing.</p> <p>It works fine, but a version control client has a lot of features which don't make sense for us and people occasionally get confused.</p> <p>Are there any tools better suited for the task? Or may be a completely different approach?</p> <p><strong>Update:</strong> </p> <p>I need to clarify that it's not a tightly integrated project - more like extensible system with a heap of "plugins", including thrid-party ones. We need to make sure those modules-plugins works nicely with recent versions of each other and the core. Centralised build as was suggested was considered initially, but it's not an option.</p>
<p>I'd probably take a look at rsync.</p> <p>Just create a .CMD file that contains the call to rsync with all the correct parameters and let people call that. rsync is very smart in deciding what part of files need to be transferred, so it'll be very fast even when large files are involved.</p> <p>What rsync doesn't do though is conflict resolution (or even detection), but in the scenario you described it's more like reading from a central place which is what rsync is designed to handle.</p>
<p>Building the project should be a centralized process in order to allow for better control soon your solution will be caos in the long run. Anyway here is what I'd do.</p> <ul> <li>Create the usual repositories for source files, resources, documentation, etc for each project.</li> <li>Create a repository for resources. There will be the latest binary versions for each project as well as any required resources, files, etc. Keep a good folder structure for each project so developers can "reference" the files directly.</li> <li>Create a repository for final buidls which will hold the actual stable release. This will get the stable files, done in an automatic way (if possible) from the checked in sources. This will hold the real product, the real version for integration testing and so on.</li> </ul> <p>While far from being perfect you'll be able to define well established protocols. Check in your latest dll here, generate the "real" versión from latest source here.</p>
8,288
<p>Where do you draw the line to stop making abstractions and to start writing sane code? There are tons of examples of 'enterprise code' such as the dozen-file "FizzBuzz" program... even something simple such as an RTS game can have something like:</p> <pre><code>class Player {} ;/// contains Weapons class Weapons{} ;/// contains BulletTypes class BulletType{} ;///contains descriptions of Bullets class Bullet{} ;///extends PlaceableObject and RenderableObject which can be placed/drawn respectively class PlaceableObject{} ;///has x,y,z, coords class RenderableObject{} ;///an object with a draw() command class MovingObject{}; ///an object with a move() function </code></pre> <p>etc... and it can turn into a nightmare. This can be drawn to its logical extreme, much like functional programming can be drawn to the extreme where you can create a language with only variables, function application, and anonymous function definitions (although I must admit that is slightly more elegant)... </p> <p>Any sane advice on this topic?</p>
<ol> <li><strong>YAGNI (You Ain't Gotta Need It).</strong> Don't create abstractions you don't see immediate use for or a sensible reason. This way you have a simple thing that may become more complex, instead of a complicated things that you would strive to make simpler, but lose.</li> <li>Make sure the abstractions make sense. If they're too far from reality, too hard to justify... forget it.</li> <li>Let the solution feel natural. Work on it until it does. Then for an unfamiliar person the solution should seem so obvious, that he screams "how could you have done it differently?".</li> <li><strong>Don't try to predict the future.</strong> You can't. If you try to cover all 10 possible cases, you will soon discover 11th and more, and it will be more difficult to implement it because of previous 10, not encountered in practice. <strong>Make it simple and easy to adapt.</strong> Software needs to be changed, but ease of adaptation (agility) is often much better strategy than trying to cover all maybe-possible cases up-front.</li> </ol>
<p>I believe that the criteria may be deduced from a clear definition of what abstraction is.</p> <p>You are referring to abstraction within the Object-Oriented programing paradigm, where you have at your disposal the three principles: <a href="https://stackoverflow.com/questions/99688">'abstraction' - 'encapsulation' - 'information hiding or visibility'</a>.</p> <p><strong>Abstraction is the process of choosing which attributes of the object are relevant to your system, and which must be completely ignored.</strong></p> <p>That means, the abstraction limit does not concern so much the <em>number</em> of concepts you define (Player, Weapons, Bullets, ...), but <em>what you choose to put inside</em> those concepts.</p> <p>It is basically <em>triage</em>, where you will consider only from a concept what is useful to the services you need to define.</p> <p>So <strong><em>a good criteria to start writing sane code might be the APIs</em></strong>, as the eclipse program suggest: <strong><a href="http://www.eclipse.org/eclipse/development/apis/API-First.pdf" rel="nofollow noreferrer">API first</a></strong>.</p> <p>Indeed, "Good APIs require design iteration", meaning the list of objects you mentioning in your question will be refined as the API needed is itself refined.</p> <p>Plus, APIs mean to have well-defined component boundaries and dependencies (as in 'Core - Player - vs. UI - RenderableObject - '), meaning the very detailed list you mentioning can not be viewed as a long endless list of concepts, but must be clearly grouped into different <strong><em>functional perimeters</em></strong> (or functional components), from an applicative architecture.</p> <p>Since APIs exist to serve the needs of clients, you will keep those objects only because they make sense for the client. The others objects should be in 'internal' packages and never be referred directly by any other parts of your application.</p> <p>With that in mind, <a href="https://stackoverflow.com/questions/216150#216169">@phjr advices</a> make perfect sense ;)</p>
26,575
<p>Ok, this is a bit of a cheeky question. I want to build a simple text editor (using my own text mode screen handling). I just want a good example of data structures that can be used to represent the text buffer, and some simple examples of char/text insertion/deletion. I can handle all the rest of the code myself (file i/o, console i/o etc). A link to a nice simple editor source would be great (C or C++).</p>
<p>I used to work for a company whose main product was a text editor. While I mainly worked on the scripting language for it, the internal design of the editor itself was naturally a major topic of discussion.</p> <p>It seemed like it broke down into two general trains of thought. One was that you stored each line by itself, and then link them together in a linked list or other overall data structure that you were happy with. The advantage was that any line-oriented editing actions (such as deleting an entire line, or moving a line block within a file) were beyond trivial to implement and therefore lightning fast. The down side was that loading and saving the file took a bit more work, because you'd have to traverse the entire file and build these data structures.</p> <p>The other train of thought at that time was to try to keep hunks of text together regardless of line breaks when they hadn't been changed, breaking them up only as required by editing. The advantage was that an unedited hunk of the file could be blasted out to a file very easily. So simple edits where you load a file, change one line, and save the file, were super fast. The disadvantage was that line-oriented or column-block operations were very time consuming to execute because you would have to parse through these hunks of text and move alot of data around.</p> <p>We always stuck with the line-oriented design, for whatever that is worth, and our product was considered one of the fastest editors at the time.</p>
<p>Check out vim, it's open-source. Poke around in it to see how it handles what you want.</p>
18,635
<p>I remember reading in some Java book about any operator other than 'instanceof' for comparing the type hierarchy between two objects.</p> <p>instanceof is the most used and common. I am not able to recall clearly whether there is indeed another way of doing that or not.</p>
<p>Yes, there is. Is not an operator but a method on the Class class.</p> <p>Here it is: <a href="http://java.sun.com/javase/6/docs/api/java/lang/Class.html#isInstance(java.lang.Object)" rel="nofollow noreferrer">isIntance(Object o ) </a></p> <p>Quote from the doc:</p> <blockquote> <p><em>...This method is the dynamic equivalent of the Java language instanceof operator</em></p> </blockquote> <pre><code>public class Some { public static void main( String [] args ) { if ( Some.class.isInstance( new SubClass() ) ) { System.out.println( "ieap" ); } else { System.out.println( "noup" ); } } } class SubClass extends Some{} </code></pre>
<pre><code>if ( someClass.isAssignableFrom( obj.getClass() ) ) </code></pre> <p>is equivalent to</p> <pre><code>if ( obj instanceof Foo ) </code></pre> <p>Use <code>instanceof</code> if the class to be checked against is known at compile time, use <code>isAssignableFrom</code> if it is only known at runtime.</p>
49,354
<p>I'm looking for best practices to integrate log4net to SharePoint for web request, feature activation and all timer stuff. </p> <p>I have several subprojects in my farm, and I would like to have only one Log4Net.config file.</p> <p><strong>[Edit]</strong><br> Not only I need to configure log4net for the web application, which is easy to do (I use global.asax, and a log4net.config file, so I can modify log settings withtout reloading the webapp), but I also need to log asynchronous events:</p> <ul> <li>Event Handler (like ItemAdded)</li> <li>Timer Jobs</li> <li>...</li> </ul>
<p>I implemented this recently and came up with a solution that worked for me.</p> <p>Deploy your log4net config file to the 12 hive and the log4net dll into the GAC using a globally scoped solution. Then in your application code explicitly initialize log4net from the location of your global file. This allows you to log feature receiver, timer jobs and web application code. </p> <pre><code>[assembly: log4net.Config.XmlConfigurator(ConfigFile = @"C:\Program Files\Common Files\Microsoft Shared\" + @"Web Server Extensions\12\CONFIG\log4net.config", Watch = true)] </code></pre> <p>see here <a href="http://www.codeproject.com/KB/sharepoint/SharepointLog4Net.aspx" rel="noreferrer">http://www.codeproject.com/KB/sharepoint/SharepointLog4Net.aspx</a></p>
<p>You could release the config file as part of the solution package(s) to the 12 hive (use <a href="http://www.codeplex.com/stsdev" rel="nofollow noreferrer">STSDev</a>) to create any packages). This would give you a set location for the config and any changes to it can be released in a controlled manner (i.e. no need for manual editm, just roll back and re-install the solution).</p>
27,044
<p>After you've let the VS.NET (2008 in this case) wizard upgrade your solution, do you perform any manual steps to upgrade specific properties of your solution and projects? For instance, you have to go to each project and target a new version of the framework (from 2.0 to 3.5 in this case). Even after targeting a new version of the framework, I find assembly references still point to the assemblies from the old version (2.0 rather than 3.5 even after changing the target). Does this mean I lose out on the performance benefits of assemblies in the new version of the framework?</p>
<p>All versions of the .Net Framework from 2.0 onwards (i.e. 3.0 and 3.5) use exactly the same core framework files (i.e. the CLR, you'll notice there are no directories relating to 3.0 or 3.5 in the C:\Windows\Microsoft.Net\Framework directory) therefore you shouldn't worry too much about any performance issues.</p> <p>The Core parts are referred to in Microsoft Speak as the 'Red Bits' and the rest as the 'Green Bits'.</p>
<p>the target framework feature, you'll need to manually add a reference to System.Core.dll to utilise some of the latest features like Linq.</p>
5,001
<p>What's the difference between the inner workings of Java's JVM and .NET's CLR?</p> <p>Perhaps a starting point would be, are they basically the same thing in their respective environments (Java > JVM > Machine code) (C# > CLR > IL).</p> <hr> <p><strong>Update:</strong> Several people have alluded to the points I was trying to cover:</p> <ol> <li>Garbage Collection </li> <li>Boxing/Unboxing</li> <li>JIT debugging </li> <li>Generics/Templates</li> <li>Please feel free to suggest other good topics that differentiate the two.</li> </ol> <p><a href="https://stackoverflow.com/users/5056/george-mauer">@George Mauer</a> - this sounds very interesting:</p> <blockquote> <p>Already posted this once but here is a <a href="http://www.artima.com/intv/anders.html" rel="nofollow noreferrer">series of interviews</a> with c# chief language designer Anders Hejlsberg. </p> </blockquote>
<p>From <a href="http://social.msdn.microsoft.com/forums/en-US/clr/thread/38223155-c07c-472a-8903-6cdaf5f110ea/" rel="nofollow noreferrer">here</a>. I couldn't have said it better (Well, with the exception of a flame war, this is a flameless place :-) ).</p> <blockquote> <p>Hello,</p> <p>Responding to your question seems fraught with peril by starting a flame war, so I'll proceed cautiously.</p> <p>There are a number of fundamental technical similarities between the Java Runtime and the Common Language Runtime, including garbage collected memory, an intermediate language (Microsoft IL versus Java ByteCode), core system libraries, and support for fairly high level languages, code security, and deployment.</p> <p>However, each of these 'similar' areas also have a number of sizable and small differences, and it's beyond the scope of a simple Forum post to describe most of them.</p> <p>I would suggest asking a more targetted question about any of the various runtime features and component areas (e.g. memory management, compilation, system libraries, security, etc.) and then we can provide a more targetted response (e.g. a blog, a technical article, or some books).</p> </blockquote>
<p>There differences in garbage collection as well. JVM uses Copying collector and Mark and sweep. .NET user Copying collector and Mark and compact (Much harder to implement).</p> <p>Also type erasure mentioned by Flyswat is important. JVM doesn't have a clue about generics and everything is object and associated perf. penalty of boxing and unboxing. Also reflection won't give you generic information. CLR supports generics natively.</p>
8,367
<p>I have this Python application that gets stuck from time to time and I can't find out where.</p> <p>Is there any way to signal Python interpreter to show you the exact code that's running? </p> <p>Some kind of on-the-fly stacktrace?</p> <p><strong><em>Related questions:</em></strong></p> <ul> <li><a href="https://stackoverflow.com/questions/1156023/print-current-call-stack-from-a-method-in-python-code">Print current call stack from a method in Python code</a></li> <li><a href="https://stackoverflow.com/questions/6849138/check-what-a-running-process-is-doing-print-stack-trace-of-an-uninstrumented-py">Check what a running process is doing: print stack trace of an uninstrumented Python program</a></li> </ul>
<p>I have module I use for situations like this - where a process will be running for a long time but gets stuck sometimes for unknown and irreproducible reasons. Its a bit hacky, and only works on unix (requires signals):</p> <pre><code>import code, traceback, signal def debug(sig, frame): """Interrupt running process, and provide a python prompt for interactive debugging.""" d={'_frame':frame} # Allow access to frame object. d.update(frame.f_globals) # Unless shadowed by global d.update(frame.f_locals) i = code.InteractiveConsole(d) message = "Signal received : entering python shell.\nTraceback:\n" message += ''.join(traceback.format_stack(frame)) i.interact(message) def listen(): signal.signal(signal.SIGUSR1, debug) # Register handler </code></pre> <p>To use, just call the listen() function at some point when your program starts up (You could even stick it in site.py to have all python programs use it), and let it run. At any point, send the process a SIGUSR1 signal, using kill, or in python:</p> <pre><code> os.kill(pid, signal.SIGUSR1) </code></pre> <p>This will cause the program to break to a python console at the point it is currently at, showing you the stack trace, and letting you manipulate the variables. Use control-d (EOF) to continue running (though note that you will probably interrupt any I/O etc at the point you signal, so it isn't fully non-intrusive.</p> <p>I've another script that does the same thing, except it communicates with the running process through a pipe (to allow for debugging backgrounded processes etc). Its a bit large to post here, but I've added it as a <a href="http://code.activestate.com/recipes/576515/" rel="noreferrer">python cookbook recipe</a>.</p>
<p>At the point where the code is run, you can insert this small snippet to see a nicely formatted printed stack trace. It assumes that you have a folder called <code>logs</code> at your project's root directory.</p> <pre class="lang-py prettyprint-override"><code># DEBUG: START DEBUG --&gt; import traceback with open('logs/stack-trace.log', 'w') as file: traceback.print_stack(file=file) # DEBUG: END DEBUG --! </code></pre>
16,013
<p>I need to achieve the following when opening an HTML in Excel <code>(Response.contentType="application/vnd.ms-excel")</code> :</p> <ul> <li>force Excel to consider content of td cells as numbers</li> <li>make the above so that any subsequent user-entered formulas work on these cells (when the spreadsheet is opened)</li> </ul> <p>So far I was successful with adding <code>style="vnd.ms-excel.numberformat:0.00"</code> to the td cells in question. The contents of the cells are correctly shown as numbers when I right click on them in the Excel, however the formulas don't work.</p> <p>If successful, that technique would be quite useful because any web Excel report could be user enhanced with appropriate formulas according to custom requirements. Thanks in advance.</p>
<p>If you add a CSS Class to your page:</p> <pre><code>.num { mso-number-format:General; } .date { mso-number-format:"Short Date"; } </code></pre> <p>And slap those classes on your TD's, does it work?</p> <pre><code>&lt;td class="num"&gt;34&lt;/td&gt; &lt;td class="num"&gt;17.0&lt;/td&gt; &lt;td class="date"&gt;12/17/2008&lt;/td&gt; &lt;!-- if you are playing with dates too --&gt; </code></pre> <p><strong><em>Update:</em></strong> <a href="http://cosicimiento.blogspot.com/2008/11/styling-excel-cells-with-mso-number.html" rel="noreferrer">Additional formatting options</a> from @Aaron.</p>
<pre><code>mso-number-format:0 NO Decimals mso-number-format:&quot;\#\,\#\#0\.000&quot; 3 Decimals mso-number-format:&quot;mm\/dd\/yy&quot; Thousand comma with 3 decimals mso-number-format:&quot;mmmm\\ d\\\,\\ yyyy&quot; Date7 mso-number-format:&quot;m\/d\/yy\\ h\:mm\\ AM\/PM&quot; Date9 </code></pre> <p>Text Column</p> <pre><code>&quot;&lt;td style=\&quot;mso-number-format:'\@'\&quot;&gt;&quot; </code></pre> <p>or</p> <pre><code>&lt;td style=&quot;mso-number-format:'\@'&quot;&gt; </code></pre>
46,181
<p>This sounds really stupid, but I was told that you could drag-and-drop visual components (including JavaScript or AJAX components?) onto a web page view in ASP.NET MVC and then "customize" the components by editing code behind them once they were in place. Either I misunderstood what I was told or I'm blind and don't see how to do this, but the ability to do this would help a lot, especially since I can't really design things to save my life.</p> <p><strong>EDIT 1:</strong> For clarification: The way I was told, it made it seem like you could go to a panel, drag a button over to a view area, and then the HTML/CSS to put the button there would be stubbed out. Then, you could open a code editor and tweak everything exactly how you want it to be.</p>
<p>Drag and drop is more suited to standard ASP.NET webforms, not MVC. I think you can still do it in MVC, but only if the controls do not rely on viewstate (which MVC does not support).</p> <p>try Googling on "asp.net mvc user controls"</p>
<p>Even with Webforms, the Design view is pretty useless. It's nowhere near the wysiwyg editor you're envisioning for even a relatively simple website design. While you can technically drag-and-drop components onto the page, they usually bear no resemblance to the rendered html.</p> <p>If you want to design website with either ASP.Net framework, you'll need to be comfortable writing markup. The upside of this is that the MVC framework makes the markup side of things greatly simplified.</p>
38,429
<p>Do you think ASP.NET MVC is able to develop RESTful web services and which approach you would use for it?</p>
<p>I have written a whole series of posts on developing a RESTful <a href="http://shouldersofgiants.co.uk/blog/" rel="noreferrer">Web Service using ASP.Net MVC</a>... well at least I'm 80% of the way through after 8 posts. Have a look at:</p> <p><a href="http://shouldersofgiants.co.uk/blog/" rel="noreferrer">http://shouldersofgiants.co.uk/blog/</a></p> <p>The web service I'm developing supports multiple representations (XHTML / JSON / XML / HELP) handles as many possible errors as I could find and supports POST overloading.</p>
<p>I would seriously look at ADO.NET Dataservices. (formaly code named Astoria) There's some really nice tooling for Restful services in there!</p> <p><a href="http://msdn.microsoft.com/en-us/data/bb931106.aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/data/bb931106.aspx</a></p>
27,202
<p>I am actually rendering an excel file in the browser. I use the Response.Writefile(filePath) to dod this. It is working perfectly fine in few of the machines. I am getting a pop up with "Open","Save" and "Cancel" option. </p> <p>But incase of few machines after i do a save click on the popup a plain empty page remains open. This happens only in few of the machines. This window just flickers in the other machine and closes by itself. Please let me know of what can be done to avoid this plain empty page to be closed by itself after the file is opened or saved.</p>
<p>Are you setting any HTTP headers? If you are not, you are relying on the browser to interpret the data correctly.</p> <p>To tell the browser you are sending excel content:</p> <pre><code>Response.ContentType = "application/x-excel"; </code></pre> <p>To tell the browser to treat the response as download:</p> <pre><code>Response.AddHeader("content-disposition", "inline; filename=\"" + YourSuggestedFileName + "\""); </code></pre> <p>The machines giving you trouble likely don't know what to do with the excel data.</p>
<p>The problem with this approach is that date fields and number fields are all rendered as a string. The end user has to then explicitly modify the type for these fields if they want to sort them.</p> <p>If you have the budget, I suggest using a component like: <a href="http://www.aspose.com/categories/file-format-components/aspose.cells-for-.net-and-java/default.aspx" rel="nofollow noreferrer">Aspose.Cells</a></p>
47,271
<p>While writing a custom IHttpHandler I came across a behavior that I didn't expect concerning the HttpCachePolicy object.</p> <p>My handler calculates and sets an entity-tag (using the SetETag method on the HttpCachePolicy associated with the current response object). If I set the cache-control to public using the SetCacheability method everything works like a charm and the server sends along the e-tag header. If I set it to private the e-tag header will be suppressed.</p> <p>Maybe I just haven't looked hard enough but I haven't seen anything in the HTTP/1.1 spec that would justify this behavior. Why wouldn't you want to send E-Tag to browsers while still prohibiting proxies from storing the data?</p> <pre><code>using System; using System.Web; public class Handler : IHttpHandler { public void ProcessRequest (HttpContext ctx) { ctx.Response.Cache.SetCacheability(HttpCacheability.Private); ctx.Response.Cache.SetETag("\"static\""); ctx.Response.ContentType = "text/plain"; ctx.Response.Write("Hello World"); } public bool IsReusable { get { return true; } } } </code></pre> <p>Will return</p> <pre> Cache-Control: private Content-Type: text/plain; charset=utf-8 Content-Length: 11 </pre> <p>But if we change it to public it'll return</p> <pre> Cache-Control: public Content-Type: text/plain; charset=utf-8 Content-Length: 11 Etag: "static" </pre> <p>I've run this on the ASP.NET development server and IIS6 so far with the same results. Also I'm unable to explicitly set the ETag using</p> <pre><code>Response.AppendHeader("ETag", "static") </code></pre> <p><strong>Update</strong>: It's possible to append the ETag header manually when running in IIS7, I suspect this is caused by the tight integration between ASP.NET and the IIS7 pipeline.</p> <p><strong>Clarification</strong>: It's a long question but the core question is this: <strong>why does ASP.NET do this, how can I get around it and should I?</strong></p> <p><strong>Update</strong>: I'm going to accept <a href="https://stackoverflow.com/questions/32824/why-does-httpcacheabilityprivate-suppress-etags#34004">Tony's answer</a> since it's essentially correct (go Tony!). I found that if you want to emulate the HttpCacheability.Private fully you can set the cacheability to ServerAndPrivate but you also have call cache.<a href="http://msdn.microsoft.com/en-us/library/system.web.httpcachepolicy.setomitvarystar.aspx" rel="nofollow noreferrer">SetOmitVaryStar</a>(true) otherwise the cache will add the <strong>Vary: *</strong> header to the output and you don't want that. I'll edit that into the answer when I get edit permissions (or if you see this Tony perhaps you could edit your answer to include that call?)</p>
<p>I think you need to use HttpCacheability.ServerAndPrivate</p> <p>That should give you cache-control: private in the headers and let you set an ETag.</p> <p>The documentation on that needs to be a bit better.</p> <p><strong>Edit:</strong> Markus found that you also have call cache.SetOmitVaryStar(true) otherwise the cache will add the Vary: * header to the output and you don't want that.</p>
<p>If like me you're unhappy with the workaround mentioned here of using Cacheability.ServerAndPrivate, and you really want to use Private instead - perhaps because you are customising pages individually for users and it makes no sense to cache on the server - then at least in .NET 3.5 you can set ETag through Response.Headers.Add and this works fine. </p> <p>N.B. if you do this you have to implement the comparison of the client headers yourself and the HTTP 304 response handling - not sure if .NET takes care of this for you under normal circumstances.</p>
5,282
<p>So WPF doesn't support standard sorting or filtering behavior for views of CompositeCollections, so what would be a best practice for solving this problem. </p> <p>There are two or more object collections of different types. You want to combine them into a single sortable and filterable collection (withing having to manually implement sort or filter).</p> <p>One of the approaches I've considered is to create a new object collection with only a few core properties, including the ones that I would want the collection sorted on, and an object instance of each type. </p> <pre><code>class MyCompositeObject { enum ObjectType; DateTime CreatedDate; string SomeAttribute; myObjectType1 Obj1; myObjectType2 Obj2; { class MyCompositeObjects : List&lt;MyCompositeObject&gt; { } </code></pre> <p>And then loop through my two object collections to build the new composite collection. Obviously this is a bit of a brute force method, but it would work. I'd get all the default view sorting and filtering behavior on my new composite object collection, and I'd be able to put a data template on it to display my list items properly depending on which type is actually stored in that composite item.</p> <p>What suggestions are there for doing this in a more elegant way?</p>
<p>Change the code for the About box to </p> <pre><code>Me.LabelVersion.Text = String.Format("Version {0}", My.Application.Deployment.CurrentVersion.ToString) </code></pre> <p>Please note that all the other answers are correct for "how do I get my assembly version", not the stated question "how do I show my publish version".</p>
<p>I'm no VB.NET expert, but have you tried to set the value to for example 1.0.0.*? This should increase the revision number (at least it does in the AssemblyInfo.cs in C#).</p>
3,243