instruction
stringlengths
21
27.8k
chosen
stringlengths
18
28.2k
rejected
stringlengths
18
33.6k
__index_level_0__
int64
0
50k
<p>I have the follow Linq query ... which executes correctly:</p> <pre><code>from t in Tasks where LookupTaskStarted(t.TaskId) == true select new { t.TaskId, t.Number, Started = LookupTaskStarted(t.TaskId) } </code></pre> <p>Is there anyway to create this as a property on the Linq-To-Sql class? Or do I always have to reference it like this?</p>
<p>I don't have the answer to your question, but I have a refactoring suggestion. Instead of calling LookupTaskStarted() twice, you can record the value with a <code>let</code> clause:</p> <pre><code>from t in Tasks let started = LookupTaskStarted(t.TaskId) where started select new { T.TaskId, t.Number, Started = started } </code></pre> <p>After writing that, I realized that if you are filtering by <code>started</code>, you don't need the <code>Started</code> property because all of them will be true.</p>
<p>All linq-sql classes are created as partial. You could extend and add this property. </p>
49,572
<p>what is the difference in using a standard </p> <pre><code>type sl: TStringList </code></pre> <p>compared to using a generic TList</p> <pre><code>type sl: TList&lt;string&gt; </code></pre> <p>?</p> <p>As far as I can see, both behave exactly the same.</p> <p>Is it just another way of doing the same thing?</p> <p>Are there situations where one would be better than the other?</p> <p>Thanks! </p>
<ul> <li>TStringList is a descendant of TStrings.</li> <li>TStringList knows how to sort itself alphabetically.</li> <li>TStringList has an Objects property.</li> <li>TStringList doesn't make your code incompatible with all previous versions of Delphi.</li> <li>TStringList can be used as a published property. (A bug prevents generic classes from being published, for now.)</li> </ul>
<p>TStringList has been used for far too long and has many advantages, all mentioned by Rob Kennedy.</p> <p>The only real disadvantage of using it as a pair of a string and an object is the necessity of casting object to the actual type expected and stored in this list (when reading) and as far as I know Embarcadero did not provide Delphi 2009 and up VCL libraries with generic version of TStringList.</p> <p>To overcome this limitation I implemented such list for internal use and for almost 3 years it serves it's purpose so I decided to share it today: <a href="https://github.com/t00/deltoo#tgenericstringlist" rel="nofollow">https://github.com/t00/deltoo#tgenericstringlist</a></p> <p>One important note - it changes the default property from Strings to Objects as in most cases when object is stored in a list it is also the mostly accessed property of it.</p>
35,317
<p>I'm trying to ensure a script remains running on a development server. It collates stats and provides a web service so it's supposed to persist, yet a few times a day, it dies off for unknown reasons. When we notice we just launch it again, but it's a pain in the rear and some users don't have permission (or the knowhow) to launch it up.</p> <p>The programmer in me wants to spend a few hours getting to the bottom of the problem but the busy person in me thinks there must be an easy way to detect if an app is not running, and launch it again.</p> <p>I know I <em>could</em> cron-script ps through grep:</p> <pre><code>ps -A | grep appname </code></pre> <p>But again, that's another hour of my life wasted on doing something that must already exist... Is there not a pre-made app that I can pass an executable (optionally with arguments) and that will keep a process running indefinitely?</p> <p>In case it makes any difference, it's Ubuntu.</p>
<p>I have used a simple script with cron to make sure that the program is running. If it is not, then it will start it up. This may not be the perfect solution you are looking for, but it is simple and works rather well.</p> <pre class="lang-sh prettyprint-override"><code>#!/bin/bash #make-run.sh #make sure a process is always running. export DISPLAY=:0 #needed if you are running a simple gui app. process=YourProcessName makerun="/usr/bin/program" if ps ax | grep -v grep | grep $process &gt; /dev/null then exit else $makerun &amp; fi exit </code></pre> <p>Then add a cron job every minute, or every 5 minutes.</p>
<p>I think a better solution is if you test the function, too. For example, if you had to test an apache, it is not enough only to test, if "apache" processes on the systems exist.</p> <p>If you want to test if apache OK is, then try to download a simple web page, and test if your unique code is in the output.</p> <p>If not, kill the apache with -9 and then do a restart. And send a mail to the root (which is a forwarded mail address to the roots of the company/server/project).</p>
38,258
<p>In firefox when you add an onclick event handler to a method an event object is automatically passed to that method. This allows, among other things, the ability to detect which specific element was clicked. For example</p> <pre><code>document.body.onclick = handleClick; function handleClick(e) { // this works if FireFox alert(e.target.className); } </code></pre> <p>Is there any way to approximate this in IE? i need to be able to detect which element is clicked from an event handler on the body element.</p>
<p>Here is how would I do it in case I cannot use jQuery</p> <pre><code>document.body.onclick = handleClick; function handleClick(e) { //If "e" is undefined use the global "event" variable e = e || event; var target = e.srcElement || e.target; alert(target.className); } </code></pre> <p>And here is a jQuery solution</p> <pre><code>$(document.body).click(function(e) { alert($(this).attr("class")); }); </code></pre>
<p>I think IE uses a variable called <code>event</code>. See if that works?</p>
39,746
<p>Is there a keyboard shortcut for pasting the content of the clipboard into a command prompt window on Windows XP (instead of using the right mouse button)?</p> <p>The typical <kbd>Shift</kbd>+<kbd>Insert</kbd> does not seem to work here.</p>
<p>Yes.. but awkward. <a href="https://learn.microsoft.com/en-gb/archive/blogs/adioltean/useful-copypaste-trick-in-cmd-exe" rel="nofollow noreferrer">Link</a></p> <p><kbd>alt</kbd> + <kbd>Space</kbd>, <kbd>e</kbd>, <kbd>k</kbd> &lt;-- for copy and<br> <kbd>alt</kbd> + <kbd>Space</kbd>, <kbd>e</kbd>, <kbd>p</kbd> &lt;-- for paste. </p>
<p>Under VISTA Command prompt: Click on the System Icon Select Defaults from the Menu On the Options tab in the Options group I have "Quick Edit Mode", "Insert Mode", and "Auto Complete" selected I think that "Quick Edit Mode" is what makes it work.</p> <p>To paste whatever is in the Clipboard at the insertion point: Right Click. To copy from the Command Window Select by holding down the left mouse button and dragging the pointer across what you want to copy Once selected, right click To paste at the insertion point, right click again.</p>
16,004
<p>Are there any good methods for getting ASP.NET 2.0 to validate under the XHTML 1.0 Strict (or Transitional) DTD? I'm interested to hear some ideas before I hack up the core of the HTTP response.</p> <p>One major problem is the form tag itself, this is the output I got from W3C when I tried to validate:</p> <pre><code>Line 13, Column 11: there is no attribute "name". &lt;form name="aspnetForm" method="post" action="Default.aspx" onsubmit="javascript </code></pre> <p>That tag is very fundamental to ASP.NET, as you all know. Hmmmm.</p>
<p>ASP.NET 2.0 and above can indeed output Strict (or Transitional) XHTML. This will resolve your 'there is no attribute "name"' validation error, amongst other things. To set this up, update your Web.config file with something like:</p> <pre><code>&lt;system.web&gt; ... other configuration goes here ... &lt;xhtmlConformance mode="Strict" /&gt; &lt;/system.web&gt; </code></pre> <p>For Transitional XHTML, use <code>mode="Transitional"</code> instead.</p> <p>See <a href="http://msdn.microsoft.com/en-us/library/ms178159.aspx" rel="nofollow noreferrer">How to: Configure XHTML Rendering in ASP.NET Web Sites</a> on MSDN.</p>
<p>Its possible to change the output of ASP.NET controls using techniques like the <a href="http://www.asp.net/CssAdapters/" rel="nofollow noreferrer">CSS Adapters</a>. Although I wouldn't personally recommend you use these out of the box, it might give you some hints on a good solution.</p> <p>I generally avoid using the ASP.NET controls where ever possible, except ones that don't generate markup on their own such as the Repeater control. I would look into the ASP.NET MVC framework (what StackOverflow is built on) as this gives you 100% control over markup.</p>
18,812
<p>Since we cannot setup Eclipse's RSE to use at the tool for remote editing, I have installed <a href="http://www.cis.upenn.edu/~bcpierce/unison/docs.html" rel="nofollow noreferrer">Unison</a>. But how can I get Eclipse to automatically run unison on every file save? Is there an eclipse plugin available for this?</p> <p>TIA</p>
<p>Depending on the importance, I would write a simple plugin to handle this. </p> <p>EDIT: All you <em>really</em> need to do is this:</p> <p>1) Create the plugin from the templates with the RCP\PDE Eclipse install<br> 2) Add the following code to your activator...<br></p> <pre><code>@Override public void start( final BundleContext context ) throws Exception { super.start( context ); plugin = this; ICommandService commandService = (ICommandService)plugin.getWorkbench().getService( ICommandService.class ); commandService.addExecutionListener( new IExecutionListener() { public void notHandled( final String commandId, final NotHandledException exception ) {} public void postExecuteFailure( final String commandId, final ExecutionException exception ) {} public void postExecuteSuccess( final String commandId, final Object returnValue ) { if ( commandId.equals( "org.eclipse.ui.file.save" ) ) { // add in your action here... // personally, I would use a custom preference page, // but hard coding would work ok too } } public void preExecute( final String commandId, final ExecutionEvent event ) {} } ); } </code></pre>
<p>Depending on the importance, I would write a simple plugin to handle this. </p> <p>EDIT: All you <em>really</em> need to do is this:</p> <p>1) Create the plugin from the templates with the RCP\PDE Eclipse install<br> 2) Add the following code to your activator...<br></p> <pre><code>@Override public void start( final BundleContext context ) throws Exception { super.start( context ); plugin = this; ICommandService commandService = (ICommandService)plugin.getWorkbench().getService( ICommandService.class ); commandService.addExecutionListener( new IExecutionListener() { public void notHandled( final String commandId, final NotHandledException exception ) {} public void postExecuteFailure( final String commandId, final ExecutionException exception ) {} public void postExecuteSuccess( final String commandId, final Object returnValue ) { if ( commandId.equals( "org.eclipse.ui.file.save" ) ) { // add in your action here... // personally, I would use a custom preference page, // but hard coding would work ok too } } public void preExecute( final String commandId, final ExecutionEvent event ) {} } ); } </code></pre>
25,946
<p>I'm trying to get IKVM to build (see <a href="https://stackoverflow.com/questions/71599/how-to-get-ikvm-to-build-in-visual-studio-2008">this question</a>) but now have encountered a problem not having to do with IKVM so I'm opening up a new question:</p> <p>When running nant on the IKVM directory with the Visual Studio 2008 Command Prompt (from the Start Menu), I get the following error:</p> <blockquote> <pre><code> ikvm-native-win32: [cl] Compiling 2 files to C:\ikvm-0.36.0.11\native\Release'. [cl] jni.c [cl] os.c [cl] C:\ikvm-0.36.0.11\native\os.c(25) : fatal error C1083: Cannot open include file: 'windows.h': No such file or directory [cl] Generating Code... BUILD FAILED C:\ikvm-0.36.0.11\native\native.build(17,10): External Program Failed: cl (return code was 2) </code></pre> </blockquote> <p>I have the Platform SDK installed. What am I missing? I'm sure it's something simple...</p> <p><strong>Edit #1</strong> I just checked - I do have the directory containing windows.h on the Path. <strong>Edit #2</strong> Found the answer (see my answer below): The directory containing windows.h needed to be in the "Include" path variable.</p>
<p>OK here is the answer I ended up finding: rather than being on the Path, the directory with windows.h (in my case, C:\Program Files\Microsoft SDKs\Windows\v6.0A\Include) needed to be set in the Include environment variable.</p>
<p>By the way, create environment variable %LIB%, meaning the same - path to all SDKs lib directories</p>
10,633
<p>Is there a quick way to join paths like the Join-Path function in Powershell? For example, I have two parts of a path "C:\foo" and a subdirectory "bar". Join-Path will join these and take care of the backslash delimiters. Is there a built-in method for this in .NET, or do I need to handle this myself?</p>
<p>This is your friend: <a href="http://msdn.microsoft.com/en-us/library/system.io.path.combine.aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/system.io.path.combine.aspx</a></p>
<p><em>Path.Combine</em> is the way to go.</p>
11,944
<p>I am trying to use Zend_Db_Select to write a select query that looks somewhat like this:</p> <pre><code>SELECT * FROM bar WHERE a = 1 AND (b = 2 OR b = 3) </code></pre> <p>However, when using a combination of where() and orWhere(), it seems impossible to use condition grouping like the above.</p> <p>Are there any native ways in Zend Framework to achieve the above (without writing the actual query?)</p>
<p>From <a href="http://framework.zend.com/manual/en/zend.db.select.html#zend.db.select.building.where" rel="nofollow noreferrer">the manual</a> (Example 11.61. Example of parenthesizing Boolean expressions)</p> <pre><code> // Build this query: // SELECT product_id, product_name, price // FROM "products" // WHERE (price &lt; 100.00 OR price &gt; 500.00) // AND (product_name = 'Apple') $minimumPrice = 100; $maximumPrice = 500; $prod = 'Apple'; $select = $db->select() ->from('products', array('product_id', 'product_name', 'price')) ->where("price &lt; $minimumPrice OR price &gt; $maximumPrice") ->where('product_name = ?', $prod); </code></pre>
<p>The above reference is great, but what if you are playing with strings?</p> <p>Here would is the above example with strings...</p> <pre><code>// Build this query: // SELECT product_id, product_name, price // FROM "products" // WHERE (product_name = 'Bananas' OR product_name = 'Apples') // AND (price = 100) $name1 = 'Bananas'; $name2 = 'Apples'; $price = 100; $select = $db-&gt;select() -&gt;from('products', array('product_id', 'product_name', 'price')) -&gt;where("product_name = '" . $name1 . "' OR product_name = '" . $name2 . "'") -&gt;where("price=?", $price); </code></pre> <p>I hope that helps. Took me some fooling around to get the strings to work correctly.</p> <p>Cheers.</p>
10,642
<p>As many of you probably know, online banks nowadays have a security system whereby you are asked some personal questions before you even enter your password. Once you have answered them, you can choose for the bank to "remember this computer" so that in the future you can login by only entering your password.</p> <p>How does the "remember this computer" part work? I know it cannot be cookies, because the feature still works despite the fact that I clear all of my cookies. I thought it might be by IP address, but my friend with a dynamic IP claims it works for him, too (but maybe he's wrong). He thought it was MAC address or something, but I strongly doubt that! So, is there a concept of https-only cookies that I don't clear?</p> <p>Finally, the programming part of the question: how can I do something similar myself in, say, PHP?</p>
<p>In fact they most probably use cookies. An alternative for them would be to use "<a href="http://www.bestflashanimationsite.com/tutorials/4/" rel="noreferrer">flash cookies</a>" (officially called "<a href="http://www.adobe.com/support/flash/action_scripts/local_shared_object/" rel="noreferrer">Local Shared Objects</a>"). They are similar to cookies in that they are tied to a website and have an upper size limit, but they are maintained by the flash player, so they are invisible to any browser tools.</p> <p>To clear them (and test this theory), you can use <a href="http://kb.adobe.com/selfservice/viewContent.do?externalId=52697ee8&amp;sliceId=2" rel="noreferrer">the instructions provided by Adobe</a>. An other nifty (or maybe worrying, depending on your viewpoint) feature is that the LSO storage is shared by all browsers, so using LSO you can identify users <em>even if they switched browser</em> (as long as they are logged in as the same user).</p>
<p>MAC address is possible.</p> <p>IP to physical location mapping is also a possibility.</p> <p>User agents and other HTTP headers are quiet unique to each of the machines too.</p> <p>I'm thinking about those websites that prevents you from using an accelerating download managers. There must be a way.</p>
5,299
<p>I know that a float isn't appropriate to store currency values because of rounding errors. Is there a standard way to represent money in C++? </p> <p>I've looked in the boost library and found nothing about it. In java, it seems that BigInteger is the way but I couldn't find an equivalent in C++. I could write my own money class, but prefer not to do so if there is something tested.</p>
<p>Having dealt with this in actual financial systems, I can tell you you probably want to use a number with at least 6 decimal places of precision (assuming USD). Hopefully since you're talking about currency values you won't go way out of whack here. There are proposals for adding decimal types to C++, but I don't know of any that are actually out there yet.</p> <p>The best native C++ type to use here would be long double.</p> <p>The problem with other approaches that simply use an int is that you have to store more than just your cents. Often financial transactions are multiplied by non-integer values and that's going to get you in trouble since $100.25 translated to 10025 * 0.000123523 (e.g. APR) is going cause problems. You're going to eventually end up in floating point land and the conversions are going to cost you a lot.</p> <p>Now the problem doesn't happen in most simple situations. I'll give you a precise example:</p> <p>Given several thousand currency values, if you multiply each by a percentage and then add them up, you will end up with a different number than if you had multiplied the total by that percentage if you do not keep enough decimal places. Now this might work in some situations, but you'll often be several pennies off pretty quickly. In my general experience making sure you keep a precision of up to 6 decimal places (making sure that the remaining precision is available for the whole number part). </p> <p>Also understand that it doesn't matter what type you store it with if you do math in a less precise fashion. If your math is being done in single precision land, then it doesn't matter if you're storing it in double precision. Your precision will be correct to the least precise calculation.</p> <hr> <p>Now that said, if you do no math other than simple addition or subtraction and then store the number then you'll be fine, but as soon as anything more complex than that shows up, you're going to be in trouble.</p>
<p>Our financial institution uses "double". Since we're a "fixed income" shop, we have lots of nasty complicated algorithms that use double anyway. The trick is to be sure that your end-user presentation does not overstep the precision of double. For example, when we have a list of trades with a total in trillions of dollars, we got to be sure that we don't print garbage due to rounding issues.</p>
17,959
<p>Is there any way to get numbers on how many people are reading an RSS feed? My understanding of the way feed readers work (e.g. Google Reader) is that they check the feed periodically, cache it, and serve the cached copy to whoever asks for it until it's refreshed - which would imply that there's no way to get reliable numbers on readership.</p> <h3>Follow-up</h3> <p>Lots of suggestions to use FeedBurner, but do they have a way of counting individual readers using a web-based reader like Google Reader? Otherwise it seems like the tracking pixel approach suggested by @ifwdev might be best.</p>
<p><a href="http://www.feedburner.com/fb/a/home" rel="nofollow noreferrer">Feedburner</a> provides that info, you can delegate your feed to that service. I don't really know how it works under the covers (as you said, the feed should be checked periodically...) to be reliable.</p>
<p>Feedburner works rather nicely. They do all the stats for <a href="http://perlbuzz.com/" rel="nofollow noreferrer">Perlbuzz</a>, for example. Plus you get these little widgets that you can put on the page (the yellow box on Perlbuzz that gives the count of current readers).</p> <p>You can track the logs yourself, but I don't mind having Feedburner do it for me.</p>
24,739
<p>And I'm not meaning Bits Per Minute, but Business Process Management. </p> <p>At first though BPM was overestimated, because the technology is somehow easy to address, but I've learned the value of BPM suites is in involving the non-technical, the business experts into the software design. </p> <p>I know, the user is always with us during analysis, but the artifacts we use are always very unfamiliar to them. No matter how friendly the UML diagram looks like, or how many Agile iterations we go into, there is always a gap between the final user and the final developer ( usually covered by the user manager and the IT manager :-S ) </p> <p>How do you ( as software developers ) see BPM? Does it looks interesting? Would you consider to learn one of them? Do your think in 5 yrs it will be dead? </p> <p>I know BPM is not silver bullet at all, but unless you have a very smart customer who knows how to express their requirements for us to get it right, the analysis and requirements will always be the area where the projects will fail.</p>
<p>I spent a couple years in the Content Management/Information Management circle using both FileNet and IBM BPM products. I would have to say I am incredibly unimpressed, and here is why:</p> <p>1) BPM is one of those things I have not ever seen implemented intuitively. By that I mean (similar to what you say in your question) that a business user cannot sit down, and with 30 minutes create a process/workflow.</p> <p>2) I have rarely seen a non-programmer be able to create acceptable solutions</p> <p>3) The lack of ability to explain BPM to business users, the inability of business users to comprehend, and the amount of time and money spent on BPM seems ludicrous to me. From experience in everything I have been involved in, the company could hire 1 or 2 people (technical types) to work full time and create them a custom app for the time it takes a bunch of business types to have numerous meetings and hire consultants or train business people.</p> <p>4) It is an incredibly niche market, and 90% of the outcome involves document routing and approvals. This is a VERY VERY simple concept, and one which a developer can usually code and implement a solution for much cheaper. If the developer is good, they can make it much more intuitive with less steps too.</p> <p>5) It usually takes longer to have a coder talk with 10 people in management, a bunch of business users, learn to use a bad limited product and come up with a solution than it would be just to let normal development go on.</p> <p>Don't get me wrong here - I know my experience, while quite deep compared to some, only deals with a couple products meaning I have only touched a little of what is out there. I am all in favor of innovation, but I haven't yet seen a halfway decent solution, and they all cost 20 times more than they are worth. I am sure COTS BPM type software will persist, but I hope I don't have to work with it for many more years. Hopefully then it will be halfway decent.</p>
<p>I see BPM as being something orthogonal to a traditional IT unit that "keeps the computers running" as BPM is where we try to improve how things are done by adding this technology or changing a process accordingly. I find it rather fascinating in a few ways.</p> <p>Another interesting part of it for me is that this tends to involve looking at different parts of the business, e.g. how does the sales team work, marketing, human resources, etc. and trying to see just how efficient are they and where can things be improved?</p> <p>I don't think it'll die but the meaning of the name will change and evolve I suspect where one branch may be Automating Business Experts or some other name. I do also see this blending with the idea of a portfolio of applications in an IT department of a company. The applications are improved or replaced on a regular basis to improve how things work with a continuous improvement value to it.</p> <p>Don't forget that there are those of us in IT that frequent this site. I may be a Web Developer in title but this can have a couple of different angles depending on the company: 1) Product Development - Here I help make the product or facilitate the service the company sells, 2) Information Technology - Here I help the company run by knowing the backbone of the company which is a group of machines and various pieces of software stitched together by various processes for how the company runs.</p> <p>The evolution of requirements and the technologies that can help meet those requirements are usually a couple of big things that can impact any large software integration like an ERP or CRM system. In taking years to get the software installed and the company using it correctly, there will likely be many changes as to how we thought it would work to this is how we actually use it, where not all changes are bad. It may be that by removing some part a company could save thousands of dollars on the man hours that would be spent on something that isn't really needed or useful but this wasn't known at the start and thus one of the requested features is removed from the list of things wanted at the end.</p>
26,327
<p>I have a folder checked out using TortoiseSVN. If I copy a newer version of a file over the existing versioned file, TortoiseSVN correctly identifies that the file is modified. However when I do a "diff with previous version", it reports "no differences".</p> <p>If I use WinMerge I can see that the files ARE different.</p> <p>Does anyone know why the TortoiseSVN diff is failing?</p>
<p>Diff with previous is a different command than looking what changed in your workingcopy. </p> <p>Previous is defined to be the version before the version you have in your workingcopy:</p> <pre><code> A revision argument can be one of: NUMBER revision number '{' DATE '}' revision at start of the date 'HEAD' latest in repository 'BASE' base rev of item's working copy 'COMMITTED' last commit at or before BASE 'PREV' revision just before COMMITTED </code></pre> <p>If you don't see changes against PREVIOUS, your workingcopy reverted the changes of COMMITTED</p>
<p>Did the filename change in any way? </p> <p>We had one case where someone copied a newer revision edited outside the working directory to the working directory. TortiseSVN marked the file has changed, but couldn't diff it. Turns out the original working copy was named "configfile.txt" and he renamed his "ConfigFile.txt" to make it more readable. When he named his file back to "configfile.txt" and copied that over, everything worked again.</p>
39,240
<p>I've seen this done in Borland's <a href="https://en.wikipedia.org/wiki/Turbo_C++" rel="noreferrer">Turbo C++</a> environment, but I'm not sure how to go about it for a C# application I'm working on. Are there best practices or gotchas to look out for?</p>
<p>Some sample code:</p> <pre><code> public partial class Form1 : Form { public Form1() { InitializeComponent(); this.AllowDrop = true; this.DragEnter += new DragEventHandler(Form1_DragEnter); this.DragDrop += new DragEventHandler(Form1_DragDrop); } void Form1_DragEnter(object sender, DragEventArgs e) { if (e.Data.GetDataPresent(DataFormats.FileDrop)) e.Effect = DragDropEffects.Copy; } void Form1_DragDrop(object sender, DragEventArgs e) { string[] files = (string[])e.Data.GetData(DataFormats.FileDrop); foreach (string file in files) Console.WriteLine(file); } } </code></pre>
<p>You can implement Drag&amp;Drop in WinForms and WPF. </p> <ul> <li>WinForm (Drag from app window)</li> </ul> <p>You should add mousemove event:</p> <pre><code>private void YourElementControl_MouseMove(object sender, MouseEventArgs e) { ... if (e.Button == MouseButtons.Left) { DoDragDrop(new DataObject(DataFormats.FileDrop, new string[] { PathToFirstFile,PathToTheNextOne }), DragDropEffects.Move); } ... } </code></pre> <ul> <li>WinForm (Drag to app window)</li> </ul> <p>You should add DragDrop event:</p> <p>private void YourElementControl_DragDrop(object sender, DragEventArgs e)</p> <pre><code> { ... foreach (string path in (string[])e.Data.GetData(DataFormats.FileDrop)) { File.Copy(path, DirPath + Path.GetFileName(path)); } ... } </code></pre> <p><a href="https://www.brainbeast.best/drag-and-drop-on-c-sharp-in-wpf-dot-net/" rel="nofollow noreferrer">Source with full code</a>.</p>
9,412
<p>I have used a jQuery multiple file upload control [ MultiFile from fyneworks <a href="http://www.fyneworks.com/jquery/multiple-file-upload/#tab-Overview" rel="nofollow noreferrer">http://www.fyneworks.com/jquery/multiple-file-upload/#tab-Overview</a> ] to collect some filenames but can't work out how to upload them on the server. </p> <p>The standard asp:FileUpload control only seems to allow single files and I don't want to use the swfupload control, just plain old aspx.</p>
<p>(I have answered this question myself, I just had problems finding the answer via goole or SO and it seems useful ...)</p> <p>This code works for what I need, thanks to Suprotim Agarwal <a href="http://www.dotnetcurry.com/ShowArticle.aspx?ID=68" rel="noreferrer">http://www.dotnetcurry.com/ShowArticle.aspx?ID=68</a></p> <p>Once the files have been chosen using a suitable jQuery multiple upload control (eg MultiFile from fyneworks <a href="http://www.fyneworks.com/jquery/multiple-file-upload/#tab-Overview" rel="noreferrer">http://www.fyneworks.com/jquery/multiple-file-upload/#tab-Overview</a>) and the submit button has been clicked, call the following code in the aspx file</p> <pre><code>HttpFileCollection hfc = Request.Files; for (int i = 0; i &lt; hfc.Count; i++) { HttpPostedFile hpf = hfc[i]; if (hpf.ContentLength &gt; 0) { hpf.SaveAs(Server.MapPath("Uploads") + "\\" + System.IO.Path.GetFileName(hpf.FileName)); } } </code></pre>
<p>HttpFileCollection uploads = HttpContext.Current.Request.Files;</p> <p>for (int i = 0; i &lt; uploads.Count; i++) {</p> <pre><code> HttpPostedFile upload = (HttpPostedFile)uploads[i]; </code></pre>
47,434
<p>I'm trying to call a function after I load some XML into Actionscript, and I'm just wondering how I call that function. Example:</p> <pre><code>//Function Declarations function parentFunction() { function callMe() { textField.text = "lawl"; } } </code></pre> <p>Now, <strong>how do I call the "callMe()" function</strong> in a different part of the code, like an onRelease function?</p> <pre><code>on(release) { callMe(); //doesn't work parentFunction().callMe(); //doesn't work parentFunction.callMe(); //doesn't work } </code></pre> <p>ActionScript 2.0 is just so wonky! Any ideas?</p>
<p>Are you forced to declare callMe inside of parentFunction? I assume so because otherwise you would just do</p> <p>function parent() { } function callMe() { }</p> <p>To be clear, a function can't own another function unless you provide some scope for that function to live in.</p> <p>So in JavaScript, you would do this by using the prototype object to declare the callMe function as a method of the object that parentFunction returned.</p> <p><a href="http://www.howtocreate.co.uk/tutorials/javascript/objects" rel="nofollow noreferrer">http://www.howtocreate.co.uk/tutorials/javascript/objects</a></p> <p>For ActionScript, read this article on Adobe's website: <a href="http://www.adobe.com/devnet/flex/articles/as_collections_03.html" rel="nofollow noreferrer">http://www.adobe.com/devnet/flex/articles/as_collections_03.html</a></p> <p>EDIT: After some more reading it appears the way you did things, you are actually declaring callMe as a <strong>private</strong> function. See this article which should make the whole <a href="http://www.crockford.com/javascript/private.html" rel="nofollow noreferrer">private/public javascript issue</a> a lot more understandable.</p>
<p>I'm an idiot. I forgot the whole "a function can't own another function" thing, so I figured out another way to do it. Thanks!</p>
6,175
<p>I need to create a repeatable process for deploying SQL Server Reporting Services reports. I am not in favor of using Visual Studio and or Business Development Studio to do this. The rs.exe method of scripting deployments also seems rather clunky. Does anyone have a very elegant way that they have been able to deploy reports. The key here is that I want the process to be completely automated.</p>
<p>We use rs.exe, once we developed the script we have not needed to touch it anymore, it just works.</p> <p>Here is the source (I slightly modified it by hand to remove sensitive data without a chance to test it, hope I did not brake anything), it deploys reports and associated images from subdirectories for various languages. Also datasource is created.</p> <pre><code>'===================================================================== ' File: PublishReports.rss ' ' Summary: Script that can be used with RS.exe to ' publish the reports. ' ' Rss file spans from beginnig of this comment to end of module ' (except of "End Module"). '===================================================================== Dim langPaths As String() = {"en", "cs", "pl", "de"} Dim filePath As String = Environment.CurrentDirectory Public Sub Main() rs.Credentials = System.Net.CredentialCache.DefaultCredentials 'Create parent folder Try rs.CreateFolder(parentFolder, "/", Nothing) Console.WriteLine("Parent folder created: {0}", parentFolder) Catch e As Exception Console.WriteLine(e.Message) End Try PublishLanguagesFromFolder(filePath) End Sub Public Sub PublishLanguagesFromFolder(ByVal folder As String) Dim Lang As Integer Dim langPath As String For Lang = langPaths.GetLowerBound(0) To langPaths.GetUpperBound(0) langPath = langPaths(Lang) 'Create the lang folder Try rs.CreateFolder(langPath, "/" + parentFolder, Nothing) Console.WriteLine("Parent lang folder created: {0}", parentFolder + "/" + langPath) Catch e As Exception Console.WriteLine(e.Message) End Try 'Create the shared data source CreateDataSource("/" + parentFolder + "/" + langPath) 'Publish reports and images PublishFolderContents(folder + "\" + langPath, "/" + parentFolder + "/" + langPath) Next 'Lang End Sub Public Sub CreateDataSource(ByVal targetFolder As String) Dim name As String = "data source" 'Data source definition. Dim definition As New DataSourceDefinition definition.CredentialRetrieval = CredentialRetrievalEnum.Store definition.ConnectString = "data source=" + dbServer + ";initial catalog=" + db definition.Enabled = True definition.EnabledSpecified = True definition.Extension = "SQL" definition.ImpersonateUser = False definition.ImpersonateUserSpecified = True 'Use the default prompt string. definition.Prompt = Nothing definition.WindowsCredentials = False 'Login information definition.UserName = "user" definition.Password = "password" Try 'name, folder, overwrite, definition, properties rs.CreateDataSource(name, targetFolder, True, definition, Nothing) Catch e As Exception Console.WriteLine(e.Message) End Try End Sub Public Sub PublishFolderContents(ByVal sourceFolder As String, ByVal targetFolder As String) Dim di As New DirectoryInfo(sourceFolder) Dim fis As FileInfo() = di.GetFiles() Dim fi As FileInfo Dim fileName As String For Each fi In fis fileName = fi.Name Select Case fileName.Substring(fileName.Length - 4).ToUpper Case ".RDL" PublishReport(sourceFolder, fileName, targetFolder) Case ".JPG", ".JPEG" PublishResource(sourceFolder, fileName, "image/jpeg", targetFolder) Case ".GIF", ".PNG", ".BMP" PublishResource(sourceFolder, fileName, "image/" + fileName.Substring(fileName.Length - 3).ToLower, targetFolder) End Select Next fi End Sub Public Sub PublishReport(ByVal sourceFolder As String, ByVal reportName As String, ByVal targetFolder As String) Dim definition As [Byte]() = Nothing Dim warnings As Warning() = Nothing Try Dim stream As FileStream = File.OpenRead(sourceFolder + "\" + reportName) definition = New [Byte](stream.Length) {} stream.Read(definition, 0, CInt(stream.Length)) stream.Close() Catch e As IOException Console.WriteLine(e.Message) End Try Try 'name, folder, overwrite, definition, properties warnings = rs.CreateReport(reportName.Substring(0, reportName.Length - 4), targetFolder, True, definition, Nothing) If Not (warnings Is Nothing) Then Dim warning As Warning For Each warning In warnings Console.WriteLine(warning.Message) Next warning Else Console.WriteLine("Report: {0} published successfully with no warnings", targetFolder + "/" + reportName) End If Catch e As Exception Console.WriteLine(e.Message) End Try End Sub Public Sub PublishResource(ByVal sourceFolder As String, ByVal resourceName As String, ByVal resourceMIME As String, ByVal targetFolder As String) Dim definition As [Byte]() = Nothing Dim warnings As Warning() = Nothing Try Dim stream As FileStream = File.OpenRead(sourceFolder + "\" + resourceName) definition = New [Byte](stream.Length) {} stream.Read(definition, 0, CInt(stream.Length)) stream.Close() Catch e As IOException Console.WriteLine(e.Message) End Try Try 'name, folder, overwrite, definition, MIME, properties rs.CreateResource(resourceName, targetFolder, True, definition, resourceMIME, Nothing) Console.WriteLine("Resource: {0} with MIME {1} created successfully", targetFolder + "/" + resourceName, resourceMIME) Catch e As Exception Console.WriteLine(e.Message) End Try End Sub </code></pre> <p>Here is the batch to call the rs.exe:</p> <pre><code>SET ReportServer=%1 SET DBServer=%2 SET DBName=%3 SET ReportFolder=%4 rs -i PublishReports.rss -s %ReportServer% -v dbServer="%DBServer%" -v db="%DBName%" -v parentFolder="%ReportFolder%" &gt;PublishReports.log 2&gt;&amp;1 pause </code></pre>
<p>I know you say that you're not in favor of the Business Development Studio to do this, but I've found the built-in tools to be very reliable and easy to use.</p>
11,436
<p>I mean 100+ MB big; such text files can push the envelope of editors.</p> <p>I need to look through a large XML file, but cannot if the editor is buggy.</p> <p>Any suggestions?</p>
<p>Free read-only viewers:</p> <ul> <li><a href="https://web.archive.org/web/20140908181354fw_/http://swiftgear.com/ltfviewer/features.html" rel="noreferrer"><strong>Large Text File Viewer</strong></a> (Windows) – Fully customizable theming (colors, fonts, word wrap, tab size). Supports horizontal and vertical split view. Also support file following and regex search. Very fast, simple, and has small executable size.</li> <li><a href="https://klogg.filimonov.dev/" rel="noreferrer"><strong>klogg</strong></a> (Windows, macOS, Linux) – A maintained fork of <a href="https://glogg.bonnefon.org/description.html" rel="noreferrer">glogg</a>. Its main feature is regular expression search. It supports monitoring file changes (like <code>tail</code>), bookmarks, highlighting patterns using different colors, and has serious optimizations built in. But from a UI standpoint, it's rather minimal.</li> <li><a href="https://github.com/zarunbal/LogExpert" rel="noreferrer"><strong>LogExpert</strong></a> (Windows) – &quot;A GUI replacement for <code>tail</code>.&quot; It's really a log file analyzer, not a large file viewer, and in one test it required 10 seconds and 700 MB of RAM to load a 250 MB file. But its killer features are the columnizer (parse logs that are in CSV, JSONL, etc. and display in a spreadsheet format) and the highlighter (show lines with certain words in certain colors). Also supports file following, tabs, multifiles, bookmarks, search, plugins, and external tools.</li> <li><a href="https://www.ghisler.com/lister/" rel="noreferrer"><strong>Lister</strong></a> (Windows) – Very small and minimalist. It's one executable, barely 500 KB, but it still supports searching (with regexes), printing, a hex editor mode, and settings.</li> </ul> <p>Free editors:</p> <ul> <li>Your regular editor or IDE. Modern editors can handle surprisingly large files. In particular, <a href="https://neovim.io/" rel="noreferrer"><strong>Vim</strong></a> (Windows, macOS, Linux), <a href="https://www.gnu.org/software/emacs/" rel="noreferrer"><strong>Emacs</strong></a> (Windows, macOS, Linux), <a href="https://notepad-plus-plus.org/" rel="noreferrer"><strong>Notepad++</strong></a> (Windows), <a href="https://www.sublimetext.com/" rel="noreferrer"><strong>Sublime Text</strong></a> (Windows, macOS, Linux), and <a href="https://code.visualstudio.com/" rel="noreferrer"><strong>VS Code</strong></a> (Windows, macOS, Linux) support large (~4 GB) files, assuming you have the RAM.</li> <li><a href="https://www.liquid-technologies.com/large-file-editor" rel="noreferrer"><strong>Large File Editor</strong></a> (Windows) – Opens and edits TB+ files, supports Unicode, uses little memory, has XML-specific features, and includes a binary mode.</li> <li><a href="https://heliwave.github.io/GigaEdit.html" rel="noreferrer"><strong>GigaEdit</strong></a> (Windows) – Supports searching, character statistics, and font customization. But it's buggy – with large files, it only allows overwriting characters, not inserting them; it doesn't respect LF as a line terminator, only CRLF; and it's slow.</li> </ul> <p>Builtin programs (no installation required):</p> <ul> <li><a href="https://en.wikipedia.org/wiki/Less_(Unix)" rel="noreferrer"><strong>less</strong></a> (macOS, Linux) – The traditional Unix command-line pager tool. Lets you view text files of practically any size. Can be installed on Windows, too.</li> <li><a href="https://en.wikipedia.org/wiki/Microsoft_Notepad" rel="noreferrer"><strong>Notepad</strong></a> (Windows) – Decent with large files, especially with word wrap turned off.</li> <li><a href="https://ss64.com/nt/more.html" rel="noreferrer"><strong>MORE</strong></a> (Windows) – This refers to the Windows <code>MORE</code>, not the Unix <code>more</code>. A console program that allows you to view a file, one screen at a time.</li> </ul> <p>Web viewers:</p> <ul> <li><a href="https://www.readfileonline.com/" rel="noreferrer"><strong>readfileonline.com</strong></a> – Another HTML5 large file viewer. Supports search.</li> </ul> <p>Paid editors/viewers:</p> <ul> <li><a href="https://www.sweetscape.com/010editor/" rel="noreferrer"><strong>010 Editor</strong></a> (Windows, macOS, Linux) – Opens giant (as large as 50 GB) files.</li> <li><a href="https://www.slickedit.com/products/slickedit" rel="noreferrer"><strong>SlickEdit</strong></a> (Windows, macOS, Linux) – Opens large files.</li> <li><a href="https://www.ultraedit.com/" rel="noreferrer"><strong>UltraEdit</strong></a> (Windows, macOS, Linux) – Opens files of more than 6 GB, but the configuration must be changed for this to be practical: Menu » Advanced » Configuration » File Handling » Temporary Files » Open file without temp file...</li> <li><a href="https://www.emeditor.com/" rel="noreferrer"><strong>EmEditor</strong></a> (Windows) – Handles very large text files nicely (officially up to 248 GB, but as much as 900 GB according to one report).</li> <li><a href="https://www.bergstreiser.com/bsseditor" rel="noreferrer"><strong>BssEditor</strong></a> (Windows) – Handles large files and very long lines. Don’t require an installation. Free for non commercial use.</li> <li><a href="https://www.mommos-software.com/index.php/loxx" rel="noreferrer"><strong>loxx</strong></a> (Windows) – Supports file following, highlighting, line numbers, huge files, regex, multiple files and views, and much more. The free version can not: process regex, filter files, synchronize timestamps, and save changed files.</li> </ul>
<h1>Tips and tricks</h1> <h2>less</h2> <p>Why are you using <em>editors</em> to just <em>look</em> at a (large) file?</p> <p>Under *nix or <a href="http://en.wikipedia.org/wiki/Cygwin" rel="noreferrer">Cygwin</a>, just use <a href="http://linux.die.net/man/1/less" rel="noreferrer">less</a>. (There is a famous saying – &quot;less is more, more or less&quot; – because &quot;less&quot; replaced the earlier Unix command &quot;more&quot;, with the addition that you could scroll back up.) Searching and navigating under less is very similar to Vim, but there is no swap file and little RAM used.</p> <p>There is a Win32 port of GNU less. See the &quot;less&quot; section of the answer above.</p> <h2>Perl</h2> <p>Perl is good for quick scripts, and its <code>..</code> (range flip-flop) operator makes for a nice selection mechanism to limit the crud you have to wade through.</p> <p>For example:</p> <pre><code>$ perl -n -e 'print if ( 1000000 .. 2000000)' humongo.txt | less </code></pre> <p>This will extract everything from line 1 million to line 2 million, and allow you to sift the output manually in less.</p> <p>Another example:</p> <pre><code>$ perl -n -e 'print if ( /regex one/ .. /regex two/)' humongo.txt | less </code></pre> <p>This starts printing when the &quot;regular expression one&quot; finds something, and stops when the &quot;regular expression two&quot; find the end of an interesting block. It may find multiple blocks. Sift the output...</p> <h2>logparser</h2> <p>This is another useful tool you can use. To quote <a href="https://en.wikipedia.org/wiki/Logparser" rel="noreferrer">the Wikipedia article</a>:</p> <blockquote> <p><strong>logparser</strong> is a flexible command line utility that was initially written by Gabriele Giuseppini, a Microsoft employee, to automate tests for IIS logging. It was intended for use with the Windows operating system, and was included with the IIS 6.0 Resource Kit Tools. The default behavior of logparser works like a &quot;data processing pipeline&quot;, by taking an SQL expression on the command line, and outputting the lines containing matches for the SQL expression.</p> <p>Microsoft describes Logparser as a powerful, versatile tool that provides universal query access to text-based data such as log files, XML files and CSV files, as well as key data sources on the Windows operating system such as the Event Log, the Registry, the file system, and Active Directory. The results of the input query can be custom-formatted in text based output, or they can be persisted to more specialty targets like SQL, SYSLOG, or a chart.</p> </blockquote> <p>Example usage:</p> <pre><code>C:\&gt;logparser.exe -i:textline -o:tsv &quot;select Index, Text from 'c:\path\to\file.log' where line &gt; 1000 and line &lt; 2000&quot; C:\&gt;logparser.exe -i:textline -o:tsv &quot;select Index, Text from 'c:\path\to\file.log' where line like '%pattern%'&quot; </code></pre> <h2>The relativity of sizes</h2> <p>100 MB isn't too big. 3 GB is getting kind of big. I used to work at a print &amp; mail facility that created about 2% of U.S. first class mail. One of the systems for which I was the tech lead accounted for about 15+% of the pieces of mail. We had some big files to debug here and there.</p> <h2>And more...</h2> <p>Feel free to add more tools and information here. This answer is community wiki for a reason! We all need more advice on dealing with large amounts of data...</p>
19,295
<p>So, I've been looking at <a href="http://hadoop.apache.org/" rel="noreferrer">Hadoop</a> with keen interest, and to be honest I'm fascinated, things don't get much cooler.</p> <p>My only minor issue is I'm a C# developer and it's in Java.</p> <p>It's not that I don't understand the Java as much as I'm looking for the Hadoop.net or NHadoop or the .NET project that embraces the <a href="http://en.wikipedia.org/wiki/MapReduce" rel="noreferrer">Google MapReduce</a> approach. Does anyone know of one?</p>
<p>Have you looked at using <a href="http://wiki.apache.org/hadoop/HadoopStreaming" rel="noreferrer">Hadoop's streaming?</a></p> <p>I use it in python all the time :-).</p> <p>I'm starting to see that the heterogeneous approach is often the best and it looks like other folks are doing the same.</p> <p>If you look at projects like protocol-buffers or facebook's thrift you see that sometimes it's just best to use an app written in another language and build the glue in the language of your preference.</p>
<p>There's a pretty cute MapReduce implementation for .NET at: <a href="http://mapsharp.codeplex.com/" rel="nofollow noreferrer">http://mapsharp.codeplex.com/</a></p>
44,067
<p>In our environment we have a Lib folder which contains various third party assemblies referenced by our projects. For example, Enterprise Libary and Elmah.</p> <p>Sometimes a dev doesn't do a get latest on that folder. When the dev then loads a project which can't find the assembly in the expected folder, Visual Studio automatically locates another copy and updates the project references.</p> <p>The problem occurs when the dev checks in the project and it screws everyone else up.</p> <p>Is there a way to stop visual studio 2008 from doing this?</p> <p>UPDATE: I wanted to add that we are using TFS for source control.</p>
<p>Here's how we guard against that at my company. (Your mileage will vary!)</p> <p>Any non-system (or otherwise non-GAC) references come from our dev server, which every developer has mapped to their W: drive. We have a common DLL directory, with subdirectories by client (or vendor), and further subdirectories as appropriate. No DLLs are <strong>ever</strong> stored in source control, except license.dll as needed by Infragistics occasionally.</p> <p>For vendor-provided libraries (EntLib, Infragistics, etc.), as policy we reference from the W: drive. Period. No one is authorized to reference from anywhere else. This codes the Hint in the project files to a common path. </p> <p>For in-house libraries (client and internal projects), our continuous integration process outputs the DLLs into the appropriate branch of this directory -- again, where all our references come from.</p> <p>This does slow down our local compile time (for local debugging), as VS will auto-refresh these against the server every time. It's an annoyance (sometimes a project may take 5 or 6 minutes to build locally), but it's a necessary evil to work around people using different references. The advantage here is that as soon as someone checks in code for one of those references, the CI server kicks off a build and everyone gets it pretty darned quickly.</p> <p>The trick to this is a stable, repeatable build process and a continuous integration server. We're using <a href="http://confluence.public.thoughtworks.org/display/CCNET/Welcome+to+CruiseControl.NET" rel="noreferrer">CruiseControl.NET</a>, integrated with <a href="http://nant.sourceforge.net/" rel="noreferrer">NAnt</a> builds, but insert your favorite CI server and build tool here.</p> <p>So far we've had zero issues as a result of this process, except when the build server kicks in while our source control system (also known as the Demon Spawn, see so many of my recent remarks) performs a large multi-file check-in. (As Demon Spawn doesn't support transacted check-ins.) However, this is a very rare occurrence -- perhaps once every 5 or 6 weeks. And a force rebuild immediately afterward takes care of it.</p> <p>Just some thoughts ... This technique should keep people from screwing up your source control -- and as an added bonus, reduce the size of your source control as you won't be checking in DLLs, just dll.refresh files.</p>
<p>Yes, this is ABSOLUTELY INSANE and is really painful. Here is another option for you: 1. Remove assemblies from GAC, as other posts suggested. 2. Have your dependency resolution system deliver assemblies to your BIN folder. This is where all your solution assemblies would also be compiled to. 3. Set all the references Copy Local = false AND Specific Version = False. The point of this is to cause assembly loading exception when debugging, because if it is not in BIN then there is nothing to copy it there. AND your solutions will compile faster because VS will not have to copy files around. AND this will prevent "undead" dlls sitting somewhere in obj directory, which VS would miraculously find and copy around...</p> <p>This works well on solutions that you control. We have been doing this for years. And it is very easy to figure out if something goes off track cause then you just go looking for an assembly with Copy Local = true or Specific Version = True, which happens once in a while (forget, tired, etc. ). My current problem is that I do not control the structure or settings of the solution I am working on, and so looking for a solution for this ancient problem. I hoped that VS team solved it... Alas... Team, stop this pain.</p>
28,467
<p>If I download a .gem file to a folder in my computer, can I install it later using <code>gem install</code>?</p>
<p>Yup, when you do <code>gem install</code>, it will search the current directory first, so if your .gem file is there, it will pick it up. I found it on the <a href="https://guides.rubygems.org/command-reference/#gem-install" rel="noreferrer">gem reference</a>, which you may find handy as well:</p> <blockquote> <p>gem install will install the named gem. It will attempt a local installation (i.e. a .gem file in the current directory), and if that fails, it will attempt to download and install the most recent version of the gem you want.</p> </blockquote>
<p>Well, it's this my DRY installation:</p> <ol> <li>Look into a computer with already installed gems needed in the cache directory (by default: <code>[Ruby Installation version]/lib/ruby/gems/[Ruby version]/cache</code>)</li> <li>Copy all "<code>*.gems</code> files" to a computer without gems in own gem cache place (by default the same patron path of first step: <code>[Ruby Installation version]/lib/ruby/gems/[Ruby version]/cache</code>)</li> <li>In the console be located in the gems cache (cd <code>[Ruby Installation version]/lib/ruby/gems/[Ruby version]/cache</code>) and fire the <code>gem install anygemwithdependencieshere</code> (by example <code>cucumber-2.99.0</code>)</li> </ol> <p>It's DRY because after install any gem, by default rubygems put the gem file in the cache gem directory and not make sense duplicate thats files, it's more easy if you want both computer has the same versions (or bloqued by paranoic security rules :v)</p> <blockquote> <p>Edit: In some versions of ruby or rubygems, it don't work and fire alerts or error, you can put gems in other place but not get DRY, other alternative is using launch integrated command <code>gem server</code> and add the localhost url in gem sources, more information in: <a href="https://guides.rubygems.org/run-your-own-gem-server/" rel="nofollow noreferrer">https://guides.rubygems.org/run-your-own-gem-server/</a></p> </blockquote>
27,109
<p>Environment is VS2008, .Net 3.5</p> <p>The following C# code (note the specified encoding of UTF8)</p> <pre><code>XmlWriterSettings settings = new XmlWriterSettings (); StringBuilder sb = new StringBuilder(); settings.Encoding = System.Text.Encoding.UTF8; settings.Indent = false; settings.NewLineChars = "\n"; settings.ConformanceLevel = System.Xml.ConformanceLevel.Document; XmlWriter writer = XmlWriter.Create (sb, settings); { // Write XML data. writer.WriteStartElement ("CCHEADER"); writer.WriteAttributeString ("ProtocolVersion", "1.0.0"); writer.WriteAttributeString ("ServerCapabilities", "0x0000000F"); writer.WriteEndElement (); writer.Flush (); } </code></pre> <p>Actually generates the XML (>&lt; omitted because SO barfs on them):</p> <p>?xml version="1.0" encoding="utf-16"?<br> CCHEADER ProtocolVersion="1.0.0" ServerCapabilities="0x0000000F" /</p> <p>Why do I get the wrong encoding generated here ? What am I doing wrong ?</p>
<p>I suspect it's because it's writing to a StringBuilder, which is inherently UTF-16. An alternative to get round this is to create a class derived from StringWriter, but which overrides the Encoding property.</p> <p>I believe I've got one in <a href="http://pobox.com/~skeet/csharp/miscutil" rel="noreferrer">MiscUtil</a> - but it's pretty trivial to write anyway. Something like this:</p> <pre><code>public sealed class StringWriterWithEncoding : StringWriter { private readonly Encoding encoding; public StringWriterWithEncoding (Encoding encoding) { this.encoding = encoding; } public override Encoding Encoding { get { return encoding; } } } </code></pre>
<p>A .Net String is encoded in Unicode (UTF-16). I expect this is the source of your encoding problems because you're writing to a StringBuilder.</p>
48,613
<p>I'm doing some really simple math and saving the result to a MS SQL2008 DB.</p> <p>I'm <em>averaging</em> out the some numbers, which are byte values between 1&lt;->5. I wish to record probably 2 decimal places only. I don't care about rounding for the 2nd decimal place (eg. a 1.155 == 1.5 or 1.6 .. i'm not too phased).</p> <p>So .. should i store the average result as a float, decimal or double?</p> <p>When i check what LINQ returns, it can return all three values!</p> <p>Lastly, what would be the relevant SQL datatype field, also.</p> <p>cheers!</p>
<p>What you need is the DECIMAL datatype:</p> <pre><code>declare @val decimal(10,2) select @val = 10.155 select @val </code></pre> <p>When you input values, you can either rely on the built in rounding, or explicitly decide which rounding you want:</p> <pre><code>select val = round(10.155, 2, 0) -- rounded select val = round(10.155, 2, 1) -- truncated </code></pre> <p>Decimal (10,2) means that ten digits can be used, and that two of them are to be taken as being after the decimal point. i.e. The highest number that decimal(4,2) can contain is 99.99. Trying to set it to 100 will result in arithmetic overflow.</p>
<p>Decimal - it is the simplest, however any of mentined will do the job</p>
44,203
<p>What is a good strategy for sniffing/tracing function calls between a Flex application and a ColdFusion-based backend running on ColdFusion server? I understand they use AMF protocol.</p> <p>I'm used to using <a href="http://www.fiddlertool.com/fiddler/" rel="noreferrer">Fiddler</a> to sniff transactions between HTTP clients and servers, and it works great as long as you're using plain text or XML HTTP requests and responses (including those over SSL) but it isn't much help for binary protocols like AMF over HTTP.</p> <p>In my case, I <strong>do</strong> have access to the source code for the client and server, but I'm looking for an easy way to passively sniff traffic in any Flex + ColdFusion situation, without having to tweak anything on the server.</p>
<p>Wireshark: sniffing the glue that holds the internet together</p> <p><a href="http://www.wireshark.org/" rel="nofollow noreferrer">http://www.wireshark.org/</a></p>
<p>ditto for wireshark (the artist formerly known as Ethereal). you can sniff at every protocol layer, and stitch together traffic streams.</p>
12,102
<p>I'm having problems when printing small parts over big areas.</p> <p>I'm currently printing quite big casing (~180&nbsp;mm x 100&nbsp;mm), which has hexagonal holes on the corners. On the first layer the printer prints, in order:</p> <ul> <li>Supports inside the holes, </li> <li>Borders around the holes</li> <li>Border of the whole casing and finally </li> <li>Infill (since it is first layer, infill is solid)</li> </ul> <p>When printing borders around holes, printer's head travels between all holes (so that's around 90&nbsp;% of the whole bed width), what results in filament oozing and the hole borders being underextruded (sometimes to the point, that filament doesn't stick to the bed).</p> <p>My setup is CReality3D Ender 3 with Ultimaker Cura 3. Most important settings: </p> <ul> <li>Print speed 40&nbsp;mm/s</li> <li>Nozzle temperature 215&nbsp;&deg;C</li> <li>Bed temperature 60&nbsp;&deg;C</li> <li>Retraction on travel turned on</li> <li>Retraction additional prime amount set to 0.05&nbsp;mm<sup>3</sup>.</li> <li>Outer walls printed after inner ones</li> </ul> <p>What would help (I guess) is slowing down the print after long travels or priming more filament, but proportionally to the travel distance. There are no such settings in Ultimaker Cura though.</p> <p>How can I deal with such problem?</p>
<p>it seems like retraction issue</p> <p>i would say you should experiment with </p> <ul> <li>retraction length - so it would retract more</li> <li>extra extrusion after retraction - so the printer could put some material before it will start your next hole :)</li> </ul> <p>unfortunately there is no good guide how much it should retract and how much it should additionally extrude as it depends on "all your printing circumstances" but here is my arbitrary list in order of importance</p> <ul> <li>filament (density - type and producer)</li> <li>temperature (viscosity - hotter filament flows easier)</li> <li>nozzle diam (as filament escapes easier through big hole ;)</li> <li>heat barrier (cooling efficiency - filament should be cool as long as possible up to (or down to) the nozzle)</li> <li>extruder gearing quality (good coupling makes precise retraction and extra-extrusion)</li> <li>cooling (fan and duct should cool your printing right after it sticks to the surface)</li> </ul> <p>and one more thing worth to mention</p> <p>usually the first layer is not cooled which makes whole system hotter (so filament flows easier)</p> <p>you could experiment with it too especially for big printouts </p> <p>so</p> <ul> <li>overextrude first layer AND </li> <li>turn on cooling first layer</li> </ul> <p>it seems like there is a bunch of things you can do to master it :)</p> <p>good luck - it's definitely manageable</p>
<p>Set <code>retraction_min_travel</code> to 0. The default value is 1.5 and skips retraction when moving less than 1.5 mm. This leads to serious oozing whenever your print has small travel, which seems likely between the hole walls and the supports inside the holes.</p> <p>Also, the "custom start gcode" in Cura's Ender 3 configuration seriously over-primes the extruder, possibly making retraction ineffective until the pressure drops. Lowering the <code>E15</code> and <code>E30</code> amounts to <code>E9</code> and <code>E18</code> improved things <strong>a lot</strong> for me, especially with flex filament, but also with normal PLA. Printing a skirt or brim would probably be an alternative if you don't feel up to editing that part of the config.</p> <p>Increasing the retraction amount could also help. You should <strong>not</strong> need extra prime after travel. It can only help if you've lost material to oozing during travel, and if you have oozing, that's a problem in itself that you need to solve, not paper over by extruding additional material.</p>
1,291
<p>just a quick question:</p> <p>I am a CS undergrad and have only had experience with the Eclipse, and Net Beans IDEs. I have recently acquired a Macbook and was wanting to recompile a recent school project in Xcode just to test it out. Right after the line where I declare a new instance of an ArrayList: </p> <pre><code>dictionary = new ArrayList&lt;String&gt;(); </code></pre> <p>I get the following error: <b>generics are not supported in -source 1.3</b>.</p> <p>I was just wondering if anybody could offer advice as to what the problem might be. The same project compiles in Eclipse on the same machine. I'm running OSX 10.5.4, with Java 1.5.0_13. </p> <p>Thank you.</p>
<p>Java support in Xcode is obsolete and unmaintained; it's the only bit of Xcode that still uses the "old" build system inherited from Project Builder. Even Apple suggests using Eclipse instead. For Java, both Eclipse and NetBeans work quite well on the Mac; if you want to try native Mac programming, use Objective-C and Cocoa, for which Xcode is fine.</p> <p>That said, the problem is that javac is targeting Java 1.3, which doesn't have generics. You can modify the javac reference in the Ant buildfile (build.xml) as follows:</p> <pre><code> &lt;target name="compile" depends="init" description="Compile code"&gt; &lt;mkdir dir="${bin}"/&gt; &lt;javac deprecation="on" srcdir="${src}" destdir="${bin}" source="1.3" target="1.2" </code></pre> <p>Change "source" and "target" to "1.5".</p>
<p>Generics are introduced in Java 5, so you can't use generics with -source 1.3 option.</p>
13,519
<p>If I want to send mail not via SMTP, but rather via sendmail, is there a library for python that encapsulates this process?</p> <p>Better yet, is there a good library that abstracts the whole 'sendmail -versus- smtp' choice?</p> <p>I'll be running this script on a bunch of unix hosts, only some of which are listening on localhost:25; a few of these are part of embedded systems and can't be set up to accept SMTP.</p> <p>As part of Good Practice, I'd really like to have the library take care of header injection vulnerabilities itself -- so just dumping a string to <code>popen('/usr/bin/sendmail', 'w')</code> is a little closer to the metal than I'd like.</p> <p>If the answer is 'go write a library,' so be it ;-)</p>
<p>Header injection isn't a factor in how you send the mail, it's a factor in how you construct the mail. Check the <a href="https://docs.python.org/2/library/email.html" rel="noreferrer">email</a> package, construct the mail with that, serialise it, and send it to <code>/usr/sbin/sendmail</code> using the <a href="https://docs.python.org/2/library/subprocess.html" rel="noreferrer">subprocess</a> module:</p> <pre><code>import sys from email.mime.text import MIMEText from subprocess import Popen, PIPE msg = MIMEText(&quot;Here is the body of my message&quot;) msg[&quot;From&quot;] = &quot;me@example.com&quot; msg[&quot;To&quot;] = &quot;you@example.com&quot; msg[&quot;Subject&quot;] = &quot;This is the subject.&quot; p = Popen([&quot;/usr/sbin/sendmail&quot;, &quot;-t&quot;, &quot;-oi&quot;], stdin=PIPE) # Both Python 2.X and 3.X p.communicate(msg.as_bytes() if sys.version_info &gt;= (3,0) else msg.as_string()) # Python 2.X p.communicate(msg.as_string()) # Python 3.X p.communicate(msg.as_bytes()) </code></pre>
<p>The easiest answer is the smtplib, you can find docs on it <a href="http://docs.python.org/lib/SMTP-example.html" rel="nofollow noreferrer">here</a>. </p> <p>All you need to do is configure your local sendmail to accept connection from localhost, which it probably already does by default. Sure, you're still using SMTP for the transfer, but it's the local sendmail, which is basically the same as using the commandline tool. </p>
9,948
<p>Are there any libraries, (third party is fine) that can help do network auto-discovery using SNMP and .NET?</p> <p>If not, have you ever rolled your own?</p>
<p>I've recently come across <a href="http://sharpsnmplib.codeplex.com" rel="nofollow noreferrer">Sharp SNMP Suite</a> which I think does what you're asking for. I say "think" as I've not actually used it myself yet! I've just started looking into SNMP for the first time for a forthcoming project.</p>
<p>It's a little old topic but may still be useful for someones. I use to work with <a href="http://www.oidview.com/mibbrowser.html" rel="nofollow">SNMP</a> from Oidview, they have a trial as well.</p>
15,710
<p>How can you suppress the <code>Terminated</code> message that comes up after you kill a process in a bash script?</p> <p>I tried <code>set +bm</code>, but that doesn't work.</p> <p>I know another solution involves calling <code>exec 2&gt; /dev/null</code>, but is that reliable? How do I reset it back so that I can continue to see stderr?</p>
<p>In order to silence the message, you must be redirecting <code>stderr</code> <strong>at the time the message is generated</strong>. Because the <a href="http://ss64.com/bash/kill.html" rel="noreferrer"><code>kill</code></a> command sends a signal and doesn't wait for the target process to respond, redirecting <code>stderr</code> of the <code>kill</code> command does you no good. The bash builtin <a href="http://ss64.com/bash/wait.html" rel="noreferrer"><code>wait</code></a> was made specifically for this purpose.</p> <p>Here is very simple example that kills the most recent background command. (<a href="https://stackoverflow.com/a/5163260/117471">Learn more about $! here.</a>)</p> <pre><code>kill $! wait $! 2&gt;/dev/null </code></pre> <p>Because both <code>kill</code> and <code>wait</code> accept multiple pids, you can also do batch kills. Here is an example that kills all background processes (of the current process/script of course).</p> <pre><code>kill $(jobs -rp) wait $(jobs -rp) 2&gt;/dev/null </code></pre> <p>I was led here from <a href="https://stackoverflow.com/questions/5719030/bash-silently-kill-background-function-process/5722850">bash: silently kill background function process</a>.</p>
<p>Simple:</p> <pre class="lang-sh prettyprint-override"><code>{ kill $! } 2&gt;/dev/null </code></pre> <p>Advantage? can use any signal</p> <p>ex:</p> <pre class="lang-sh prettyprint-override"><code>{ kill -9 $PID } 2&gt;/dev/null </code></pre>
10,721
<p>I'm trying to call an Antlr task in my Ant build.xml as follows:</p> <pre><code>&lt;path id="classpath.build"&gt; &lt;fileset dir="${dir.lib.build}" includes="**/*.jar" /&gt; &lt;/path&gt; ... &lt;target name="generate-lexer" depends="init"&gt; &lt;antlr target="${file.antlr.lexer}"&gt; &lt;classpath refid="classpath.build"/&gt; &lt;/antlr&gt; &lt;/target&gt; </code></pre> <p>But Ant can't find the task definition. I've put all of the following in that <code>dir.lib.build</code>:</p> <ul> <li>antlr-3.1.jar</li> <li>antlr-2.7.7.jar</li> <li>antlr-runtime-3.1.jar</li> <li>stringtemplate-3.2.jar</li> </ul> <p>But none of those seems to have the task definition. (I've also tried putting those jars in my Ant classpath; same problem.)</p>
<p>The current Antlr-task jar is available at <a href="http://www.antlr.org/share/1169924912745/antlr3-task.zip" rel="nofollow noreferrer">http://www.antlr.org/share/1169924912745/antlr3-task.zip</a></p> <p>It can be found on the <a href="http://antlr.org" rel="nofollow noreferrer">antlr.org</a> website under the "File Sharing" heading.</p>
<p>On Ubuntu this should make it available:</p> <p><code>sudo apt-get install ant-optional</code></p>
4,512
<p>At work here, we have a box serving XML feeds to business partners. Requests for our feeds are customized by specifying query string parameters and values. Some of these parameters are required, but many are not.</p> <p>For example, we've require all requests to specify a GUID to identify the partner, and a request can either be for a "get latest" or "search" action:</p> <p>For a search: <i><a href="http://services.null.ext/?id=[GUID]&amp;q=[Search" rel="nofollow noreferrer">http://services.null.ext/?id=[GUID]&amp;q=[Search</a> Keywords]</i><br/> Latest data in category: <i><a href="http://services.null.ext/?id=[GUID]&amp;category=[ID]" rel="nofollow noreferrer">http://services.null.ext/?id=[GUID]&amp;category=[ID]</a></i></p> <p>Structuring a RESTful URL scheme for these parameters is easy:</p> <p>Search: <i><a href="http://services.null.ext/[GUID]/search/[Keywords]" rel="nofollow noreferrer">http://services.null.ext/[GUID]/search/[Keywords]</a></i><br/> Latest: <i><a href="http://services.null.ext/[GUID]/latest/category/[ID]" rel="nofollow noreferrer">http://services.null.ext/[GUID]/latest/category/[ID]</a></i></p> <p>But what how should we handle the dozen or so optional parameters we have? Many of these are mutually exclusively, and many are required in combinations. Very quickly, the number of possible paths becomes overwhelmingly complex.</p> <p>What are some recommended practices for how to map URLs with complex query strings to friendlier /REST/ful/paths?</p> <p>(I'm interested in conventions, schemes, patterns, etc. Not specific technologies to implement URL-rewriting on a web server or in a framework.)</p>
<p>You should leave optional query parameters in the Query string. There is no "rule" in REST that says there cannot be a query string. Actually, it's quite the opposite. The query string should be used to alter the view of the representation you are transferring back to the client. </p> <p>Stick to "Entities with Representable State" for your URL path components. Category seems OK, but what exactly is it that you are feeding over XML? Posts? Catalog Items? Parts? </p> <p>I think a much better REST taxonomy would look like this (assuming the content of your XML feed is an "article"): </p> <ul> <li><a href="http://myhost.com/PARTNERGUID/articles/latest?criteria1=value1&amp;criteria2=value2" rel="nofollow noreferrer">http://myhost.com/PARTNERGUID/articles/latest?criteria1=value1&amp;criteria2=value2</a></li> <li><a href="http://myhost.com/PARTNERGUID/articles/search?criteria1=value1&amp;criteria2=value2" rel="nofollow noreferrer">http://myhost.com/PARTNERGUID/articles/search?criteria1=value1&amp;criteria2=value2</a></li> </ul> <p>If you're not thinking about the entities you are representing while building your REST structure, you're not doing REST. You're doing something else. </p> <p>Take a look at <a href="http://www.xml.com/pub/a/2004/08/11/rest.html" rel="nofollow noreferrer">this article on REST best practices</a>. It's old, but it may help.</p>
<p>Parameters with values? One option is the query string. Using it is not inherently non-restful. Another option is to use the semi-colon, <a href="http://www.w3.org/DesignIssues/MatrixURIs.html" rel="nofollow noreferrer">Tim Berners-Lee talks about them</a> and they might just fit the bill, allowing the URL to make sense, without having massively long paths.</p>
20,348
<p>We have a program that produces several SWF files, some CSS and XML files, all of which need to be deployed for the thing to work.</p> <p>Is there a program or technique out there for wrapping all these files together into a single SWF file?</p>
<p>If you use the Flex compiler (<code>mxmlc</code> or FlexBuilder) you can embed SWF files and create them at runtime, more or less like you would create any display object:</p> <pre><code>package { public class Assets { [Embed(source="another.swf")] public var another : Class; } } </code></pre> <p>The code above embeds the file <code>another.swf</code> and makes it possible to create it in another SWF, like this:</p> <pre><code>package { import flash.display.Sprite; public class MyFancySite extends Sprite { public function MyFancySprite( ) { var theOther : DisplayObject = new Assets.another(); addChild(theOther); } } } </code></pre> <p>CSS, XML and any other file can be embedded in a similar fashion. Here's a description: <a href="http://livedocs.adobe.com/flex/3/html/help.html?content=embed_4.html" rel="nofollow noreferrer">http://livedocs.adobe.com/flex/3/html/help.html?content=embed_4.html</a></p>
<p>I think you can just drag them into the library of your main swf and make references to them. At least the other SWFs you can, not sure about the CSS and XML.</p>
9,391
<p>How can I find out which node in a tree list the context menu has been activated? For instance right-clicking a node and selecting an option from the menu. </p> <p>I can't use the TreeViews' <code>SelectedNode</code> property because the node is only been right-clicked and not selected.</p>
<p>You can add a mouse click event to the TreeView, then select the correct node using GetNodeAt given the mouse coordinates provided by the MouseEventArgs.</p> <pre><code>void treeView1MouseUp(object sender, MouseEventArgs e) { if(e.Button == MouseButtons.Right) { // Select the clicked node treeView1.SelectedNode = treeView1.GetNodeAt(e.X, e.Y); if(treeView1.SelectedNode != null) { myContextMenuStrip.Show(treeView1, e.Location); } } } </code></pre>
<p>If you want the context menu to be dependent on the selected item you're best move I think is to use Jonesinator's code to select the clicked item. Your context menu content can then be dependent on the selected item.</p> <p>Selecting the item first as opposed to just using it for the context menu gives a few advantages. The first is that the user has a visual indication as to which he clicked and thus which item the menu is associated with. The second is that this way it's a hell of a lot easier to keep compatible with other methods of invoking the context menu (e.g. keyboard shortcuts).</p>
2,465
<p>What's the best cross platform Java Swing browser component at least able to play nicely in a swing interface (lightweight component ?) and able to run on MacOSX and Windows ?</p> <p>Things like : <a href="http://code.google.com/p/flying-saucer//" rel="noreferrer">FlyingSaucer</a>, <a href="https://jdic.dev.java.net/" rel="noreferrer">JDIC</a>, maybe others ?</p>
<p>i belive this could help:</p> <p><a href="http://djproject.sourceforge.net/ns/index.html" rel="noreferrer">http://djproject.sourceforge.net/ns/index.html</a></p>
<p>Highweight browser based <a href="http://code.google.com/p/jbrowser/" rel="nofollow">http://code.google.com/p/jbrowser/</a>. It use Canvas component.</p>
17,584
<p>I'm developing a WinForms application (.Net 3.5, no WPF) where I want to be able to display foreign key lookups in a databound DataGridView. </p> <p>An example of the sort of relationship is that I have a table of OrderLines. Orderlines have a foreign key relationship to Products and Products in turn have a foreign key relationship to ProductTypes. </p> <p>I'd like to have a databound DataGridView where each row represents an orderline, displaying the line's product and producttype.</p> <p>Users can add or edit orderlines direct to the grid and choose the product for the order line from a comboBoxColumn - this should then update the producttype column, showing the producttype for the selected product, in the same row.</p> <p>The closest to a good fit that I've found so far is to introduce a domain object representing an orderline then bind the DataGridView to a collection of these orderlines. I then add properties to the orderline object that expose the product and the producttype, and raise relevant notifypropertychanged events to keep everything up to date. In my orderline repository I can then wire up the mappings between this orderline object and the three tables in my database.</p> <p>This works for the databinding side of things, but having to hand code all that OR-mapping in the repository seems bad. I thought nHibernate would be able to help with this wiring up but am struggling with the mappings through all the foreign keys - they seem to work ok (the foreignkey lookup for an orderline's product creates the correct product object based on the foreign key) until I try to do the databinding, I can't get the databound id columns to update my product or producttype objects.</p> <p>Is my general approach even in the right ballpark? If it is, what is a good solution to the mapping problem?</p> <p>Or, is there a better solution to databinding rows including foreign key lookups that I haven't even considered?</p>
<p>I think the problem you're having is that when you are binding to a grid, it is not enough to support INotifyPropertyChanged, but you have to fire the ListChanged events in your <a href="http://msdn.microsoft.com/en-us/library/system.componentmodel.ibindinglist.aspx" rel="nofollow noreferrer">IBindingList</a> implementation and make sure that you override and return true for the <a href="http://msdn.microsoft.com/en-us/library/system.componentmodel.ibindinglist.supportschangenotification.aspx" rel="nofollow noreferrer">SupportsChangeNotification</a> property. If you don't return true for this, the grid won't look for it to know if the data has changed.</p> <p>In .NET 2.0+, you can create a generic collection using the <a href="http://msdn.microsoft.com/en-us/library/ms132679.aspx" rel="nofollow noreferrer">BindingList</a> class, this will take care of most of the nastiness (just don't forget to override and return true for the SupportsChangeNotification property).</p> <p>If the class you use for data binding has a property that is a collection (such as IBindingList or BindingList), then you can bind the foreign key grid to that property directly. When you configure the bindings in the Forms designer, just select the collection property as the data source for the grid. It should "just work". The only sneaky part is making sure that you handle empty or null collections the right way.</p>
<p>Here's a good "How Do I" video that demonstrates data binding:</p> <p><a href="http://windowsclient.net/learn/video.aspx?v=52579" rel="nofollow noreferrer">http://windowsclient.net/learn/video.aspx?v=52579</a></p>
4,933
<p>My shared host did not provide git, so I built and installed it into ~/bin. When I ran it, I got the following error on most commands, although they were successful. </p> <blockquote> <p><code>stdin: is not a tty</code></p> </blockquote> <p>I can solve that problem by adding: </p> <blockquote> <p><code>default_run_options[:pty] = true</code></p> </blockquote> <p>to my deploy.rb, but then I get this error, which blocks deployment:</p> <blockquote> <p><code>sh: git: command not found</code></p> </blockquote> <p>How can I resolve both errors?</p> <p>I tried adding a ~/.ssh/environment file with <code>"PATH=$PATH:$HOME/bin"</code> (and changing sshd_config to use it) but it did nothing.</p> <p>It seems whatever shell is being used by capistrano is not using the ~/.bashrc or ~/.bash_profile on the remote server.</p> <p>Any ideas how to set the path on the remote machine?</p> <p>other info: I'm using OS X locally, and the shared server is linux on Site5.</p>
<p>Thanks, Chu - you put me on the right path. </p> <p>just using: <code>set :scm_command, "~/bin/git"</code><br> still gave me errors, since my local git is not in that place.</p> <p>However, the following seems to work, and to solve my issues:<br> <code>set :scm_command, "~/bin/git"<br> set :local_scm_command, "/usr/local/bin/git"</code></p>
<p>The ~/.ssh/environment file is not executed by a shell. It's a hardcoded environment file. If you want to set the path this way, you'll need to hardcode it instead of appending to $PATH. The other answers are possibly more correct, but setting ~/.ssh/environment correctly is a reliable fallback if all else fails.</p>
35,357
<p>What's the easiest way to profile a PHP script?</p> <p>I'd love tacking something on that shows me a dump of all function calls and how long they took but I'm also OK with putting something around specific functions.</p> <p>I tried experimenting with the <a href="http://php.net/microtime" rel="noreferrer">microtime</a> function:</p> <pre><code>$then = microtime(); myFunc(); $now = microtime(); echo sprintf("Elapsed: %f", $now-$then); </code></pre> <p>but that sometimes gives me negative results. Plus it's a lot of trouble to sprinkle that all over my code.</p>
<p>You want <a href="http://www.xdebug.org/" rel="noreferrer">xdebug</a> I think. Install it on the server, turn it on, pump the output through <a href="http://kcachegrind.sourceforge.net/html/Home.html" rel="noreferrer">kcachegrind</a> (for linux) or <a href="http://sourceforge.net/projects/wincachegrind/" rel="noreferrer">wincachegrind</a> (for windows) and it'll show you a few pretty charts that detail the exact timings, counts and memory usage (but you'll need another extension for that).</p> <p>It rocks, seriously :D</p>
<p>XDebug is not stable and it's not always available for particular php version. For example on some servers I still run php-5.1.6, -- it's what comes with RedHat RHEL5 (and btw still receives updates for all important issues), and recent XDebug does not even compile with this php. So I ended up with switching to <a href="http://www.nusphere.com/products/php_debugger.htm" rel="nofollow">DBG debugger</a> Its <a href="http://www.nusphere.com/products/php_profiler.htm" rel="nofollow">php benchmarking</a> provides timing for functions, methods, modules and even lines.</p>
4,142
<p>I'm having a little trouble figuring out exactly how const applies in a specific case. Here's the code I have:</p> <pre><code>struct Widget { Widget():x(0), y(0), z(0){} int x, y, z; }; struct WidgetHolder //Just a simple struct to hold four Widgets. { WidgetHolder(Widget a, Widget b, Widget c, Widget d): A(a), B(b), C(c), D(d){} Widget&amp; A; Widget&amp; B; Widget&amp; C; Widget&amp; D; }; class Test //This class uses four widgets internally, and must provide access to them externally. { public: const WidgetHolder AccessWidgets() const { //This should return our four widgets, but I don't want anyone messing with them. return WidgetHolder(A, B, C, D); } WidgetHolder AccessWidgets() { //This should return our four widgets, I don't care if they get changed. return WidgetHolder(A, B, C, D); } private: Widget A, B, C, D; }; int main() { const Test unchangeable; unchangeable.AccessWidgets().A.x = 1; //Why does this compile, shouldn't the Widget&amp; be const? } </code></pre> <p>Basically, I have a class called test. It uses four widgets internally, and I need it to return these, but if test was declared const, I want the widgets returned const also.</p> <p>Can someone explain to me why the code in main() compiles?</p> <p>Thank you very much.</p>
<p>This compiles because although the WidgetHolder is a const object, this const-ness does not automatically apply to objects pointed to (referenced by) the WidgetHolder. Think of it at a machine level - if the WidgetHolder object itself were held in read-only memory, you could still write to things that were pointed to by the WidgetHolder.</p> <p>The problem appears to lie in this line:</p> <pre><code>WidgetHolder(Widget a, Widget b, Widget c, Widget d): A(a), B(b), C(c), D(d){} </code></pre> <p>As Frank mentioned, your references inside the WidgetHolder class are going to hold invalid references after the constructor returns. Therefore, you should change this to:</p> <pre><code>WidgetHolder(Widget &amp;a, Widget &amp;b, Widget &amp;c, Widget &amp;d): A(a), B(b), C(c), D(d){} </code></pre> <p>After you do that, it won't compile, and I leave it as an exercise for the reader to work out the rest of the solution.</p>
<p>EDIT: he deleted his answer, making me look a bit foolish :)</p> <p>The answer by Flame is dangerously wrong. His WidgetHolder takes a reference to a value object in the constructor. As soon as the constructor returns, that passed-by-value object will be destroyed and so you'll hold a reference to a destroyed object.</p> <p>A very simple sample app using his code clearly shows this:</p> <pre><code>#include &lt;iostream&gt; class Widget { int x; public: Widget(int inX) : x(inX){} ~Widget() { std::cout &lt;&lt; "widget " &lt;&lt; static_cast&lt; void*&gt;(this) &lt;&lt; " destroyed" &lt;&lt; std::endl; } }; struct WidgetHolder { Widget&amp; A; public: WidgetHolder(Widget a): A(a) {} const Widget&amp; a() const { std::cout &lt;&lt; "widget " &lt;&lt; static_cast&lt; void*&gt;(&amp;A) &lt;&lt; " used" &lt;&lt; std::endl; return A; } }; int main(char** argv, int argc) { Widget test(7); WidgetHolder holder(test); Widget const &amp; test2 = holder.a(); return 0; } </code></pre> <p>The output would be something like </p> <pre> widget 0xbffff7f8 destroyed widget 0xbffff7f8 used widget 0xbffff7f4 destroyed </pre> <p>To avoid this the WidgetHolder constructor should take references to the variables it wants to store as references.</p> <pre> struct WidgetHolder { Widget& A; public: WidgetHolder(Widget & a): A(a) {} /* ... */ }; </pre>
8,155
<p>Using Java, I need to encode a Map&lt;String, String&gt; of name value pairs to store into a String, and be able to decode it again. These will be stored in a database column, and will probably usually be short and simple, so the common case should produce a simple nice looking line, but shouldn't corrupt the data, even if it contains unexpected characters, etc.</p> <p>How would you choose to do it such that:</p> <ul> <li>The encoded form is a single, human readable line</li> <li>It doesn't require a big library or much context to encode / decode</li> <li>Any delimeters are properly escaped</li> </ul> <p>Url encoding? JSON? Do it yourself? Please specify any helper libraries or methods you'd use.</p> <p>(Edited to specify more context and requirements as requested.)</p>
<p>As @Uri says, additional context would be good. I think your primary concerns are less about the particular encoding scheme, as rolling your own for most encodings is pretty easy for a simple <code>Map&lt;String, String&gt;</code>.</p> <p>An interesting question is: what will this intermediate string encoding be used for?</p> <ul> <li><p>if it's purely internal, an ad-hoc format is fine eg simple concatenation: </p> <pre><code>key1|value1|key2|value2 </code></pre></li> <li><p>if humans night read it, a format like Ruby's map declaration is nice:</p> <pre><code>{ first_key =&gt; first_value, second_key =&gt; second_value } </code></pre></li> <li><p>if the encoding is to send a serialised map over the wire to another application, the XML suggestion makes a lot of sense as it's standard-ish and reasonably self-documenting, at the cost of XML's verbosity.</p> <pre><code>&lt;map&gt; &lt;entry key='foo' value='bar'/&gt; &lt;entry key='this' value='that'/&gt; &lt;/map&gt; </code></pre></li> <li><p>if the map is going to be flushed to file and read back later by another Java application, @Cletus' suggestion of the <a href="http://java.sun.com/j2se/1.5.0/docs/api/java/util/Properties.html" rel="nofollow noreferrer">Properties class</a> is a good one, and has the additional benefit of being easy to open and inspect by human beings.</p></li> </ul> <hr> <p><strong>Edit:</strong> you've added the information that this is to store in a database column - is there a reason to use a single column, rather than three columns like so:</p> <pre><code>CREATE TABLE StringMaps ( map_id NUMBER NOT NULL, -- ditch this if you only store one map... key VARCHAR2 NOT NULL, value VARCHAR2 ); </code></pre> <p>As well as letting you store more semantically meaningful data, this moves the encoding/decoding into your data access layer more formally, and allows other database readers to easily see the data without having to understand any custom encoding scheme you might use. You can also easily query by key or value if you want to.</p> <hr> <p><strong>Edit again:</strong> you've said that it really does need to fit into a single column, in which case I'd either:</p> <ul> <li><p>use the first pipe-separated encoding (or whatever exotic character you like, maybe some unprintable-in-English unicode character). Simplest thing that works. Or...</p></li> <li><p>if you're using a database like Oracle that recognises XML as a real type (and so can give you XPath evaluations against it and so on) and need to be able to read the data well from the database layer, go with XML. Writing XML parsers for decoding is never fun, but shouldn't be too painful with such a simple schema.</p></li> </ul> <p>Even if your database doesn't support XML natively, you can just throw it into any old character-like column-type...</p>
<p>Some additional context for the question would help.</p> <p>If you're going to be encoding and decoding at the entire-map granularity, why not just use XML?</p>
48,331
<p>I'm wrapping up a <code>Javascript</code> widget in a <code>Wicket</code> component. I want to let the JS side talk to the component. What I've got so far:</p> <p>Component in question goes like</p> <pre><code>talker = new GridAjaxBehavior(); this.add(talker); </code></pre> <p>in constructor</p> <p>and then, later on, puts something like</p> <pre><code>"var MyGridTalker = new talker(" + this.talker.getCallbackUrl() + ");"; </code></pre> <p>into the JS.</p> <p>where <code>GridAjaxBehavior</code> extends <code>AbstractDefaultAjaxBehavior</code>. I want GridAjaxBehavior to spit back some XML when the JS calls it. </p> <p>Am I doing this the right way? What should GridAjaxBehaviour do to spit back the XML?</p> <p>Thanks</p>
<p>Spit back some XML for what? Presumably to update the model or the view, yes?</p> <p>The strength of Wicket is that you don't have to worry about the rendered HTML. In Model-View-Controller terms, you set up the Controller to correctly modify the Model, and Wicket takes care of the View.</p> <p>The separation is not <em>entirely</em> clear: in fact you can show/hide view components, or change then, and that can be seen as altering the View.</p> <p>But what you generally don't have to do is directly manage the browser or javascript. Wicket takes care of that, if you take care of making your changes in the Java code.</p> <p>In Wicket, the Ajax will call a method on your AjaxBehavior with an AjaxRequestTarget target.</p> <p>In that method (or in methods called from it), you do whatever you need to do, updating models or views, and then you add to the target any view component that that has changed. Wicket takes care of updating the browser.</p> <hr> <p>Here's an example. It's taken from some code I did, but <strong>heavily altered</strong> just to make explication clearer. The idea is simple: "chained" dropdown choices, where the options in the child change when the select option in the parent changes, as in the series of [State] [County] [District]. </p> <p>(In the actual class, the Model change is passed to the child, which decides for itself if it has changed, and adds itself to the target if it has, then passes the target to its child. I've removed most of that to make a clearer example.)</p> <p>Here's the ctor, which just adds to itself an anonymous subclass of an AjaxBehavior:</p> <pre><code>public AjaxChildNotifyingDropDownChoice(...code elided for clarity...) { this.child = child; // Ajax won't work without this: setOutputMarkupId(true); // add( new OnChangeAjaxBehavior() { @Override public void onUpdate(final AjaxRequestTarget target) { // tell child to update its list // based on newly selected value // when the Ajax is called, // my owning component's model // is already updated // note we could just type getModel() // I'm making explicit that we're calling it // on the enclosing class // (which a non-static inner class has a hidden ref to) child.setNewModelBasedOnSelectionOf( AjaxChildNotifyingDropDownChoice.this.getModel()); // now add the child to the target // Wicket javascript will receive the new // options and re-render the child dropdown target.add(child); } }); } </code></pre> <p>We could also have hidden or un-hidden components, or added behaviors like CSS styles, or even swapped one Panel for another. As long as for each changed component we: 1) called setOutputMarkupId(true); so that the javascript can find it, and 2) added it to the AjaxRequestTarget</p> <p>Note that different types (subclases) of Ajax Behavior have different callback functions, so be sure you're overriding the right one (add an @Override annotation so the compiler can complain if you got the name wrong).</p> <p>But again, the basic wicket idea is that instead of sending raw data for the client to parse and act on, you update your model and view, and tell Wicket to re-render what you've changed, by adding the chnaged components to the target.</p> <p>The only reason I can think of to send straight XML would to be to feed it to non-Wicket javascript. Let me know if that's your aim, and I completely missed the point. ;) </p>
<p>I don't really know what Wicket is or what it does, but there is a minor bug in your code (as it appears).</p> <p>This:</p> <p><code>"var MyGridTalker = new talker(" + this.talker.getCallbackUrl();</code></p> <p>You seem to be missing your end parens:</p> <p><code>"var MyGridTalker = new talker(" + this.talker.getCallbackUrl() + ")";</code></p> <p>Anyway, not a big deal, but didn't know if it was intentional.</p>
26,836
<p>One of the main hacks for converting RAMPS 1.4 boards to use with 24 V, as stated in <a href="https://reprap.org/wiki/RAMPS_24v" rel="nofollow noreferrer">RAMPS 24V</a>, is replacing the polyfuses, principally <code>F2</code> (MF-R1100), with wire and using an inline (car blade or wire) fuse on the heatbed wire (or between PSU and RAMPS) instead<sup>1</sup>. However, that is for the RAMPS 1.4 boards.</p> <p>As <a href="https://reprap.org/wiki/RAMPS_1.5" rel="nofollow noreferrer">RAMPS 1.5</a> notes (as well as 0scar's answer to <a href="https://3dprinting.stackexchange.com/questions/5623/ramps-1-4-1-5-or-1-6">RAMPS 1.4, 1.5 or 1.6?</a>):</p> <blockquote> <p>The RAMPS 1.5 uses small surface-mounted fuses rather than the large yellow fuses prone to breakage on the RAMPS 1.4. The downside is that replacing the fuses becomes much more difficult.</p> </blockquote> <p>Are these SMD fuses rated the same voltages, or greater? Yes, this could be a bit like asking &quot;How long is a piece of string&quot; as it depends upon the manufacturer, but does anyone know what voltage <em>should</em> they be rated for?</p> <p>Ultimately, if they are both rated at greater than 24 V, then there should be no need to replace them.</p> <p>The <a href="https://discuss.toms3d.org/hardware-f6/ramps1-4-or-ramps1-5-or-ramps-1-6-t481.html#p2786" rel="nofollow noreferrer">answer</a> on this thread, <a href="https://discuss.toms3d.org/hardware-f6/ramps1-4-or-ramps1-5-or-ramps-1-6-t481.html" rel="nofollow noreferrer">Re: Ramps1.4 or Ramps1.5 or ramps 1.6???</a> states:</p> <blockquote> <p>OK the ramps 1.6 can only handle 12v OR 24V</p> </blockquote> <p>so, that would imply that the intention for 24 V support was there, although, unfortunately, the poster does not post their reference.</p> <p>However, the <a href="https://github.com/bigtreetech/ramps-1.6/blob/master/Ramps1.6/hardware/R6Schematic%20diagram.pdf" rel="nofollow noreferrer">PDF</a> of the RAMPS 1.6 schematic shows the same rated fuses as the RAMPS 1.4</p> <p><a href="https://i.stack.imgur.com/hbPML.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/hbPML.png" alt="RAMPS 1.6 Power section" /></a></p> <p>Nevertheless, that seems like a straight forward copy and paste from the RAMPS 1.4 schematic as it clearly references the MF-R500 PTC, and obviously SMD fuses have been used instead - or are the part numbers the same for the SMD fuses..? I had a google but couldn't see MF-R500 SMD fuses (maybe I didn't look hard enough?).</p> <hr /> <h3>Footnote</h3> <p><sup>1</sup> This is because the 11 A fuse is only rated to 16 V. Note that <code>F1</code> (MF-R500) is rated for 5 A at 30 V, and as such is sufficient for 24 V operation.</p>
<p>Without knowing the exact part numbers used for F1 and F2 it is impossible to say whether the fuses need to be replaced or not. However, based on the manufacturer provided schematic and BOM we can make a pretty good guess.</p> <p>Looking at the PDF you linked, it states that F1 is rated for 16V. Looking at the <a href="https://github.com/bigtreetech/ramps-1.6/blob/master/Ramps1.6/BOM%20form/BQ105-A4%20%E3%80%90RAMPS%201.6%E3%80%91Interface%20board%20R6%20%20BOM%20form.xls" rel="nofollow noreferrer">BOM spreadsheet</a> it also says F1 is 16V and 30A.</p> <p>Based on the fact that the only two reference documents available say 16V, I would strongly recommend replacing this component for 24V operation.</p>
<p>I found that at least the following two RAMPS 1.6 derived boards are 24 V capable without modifications:</p> <ul> <li>Bigtreetech RAMPS 1.6 Plus (see the PCB layout picture in <a href="https://www.roboter-bausatz.de/3080/ramps-1.6-plus-3d-drucker-steuerung" rel="nofollow noreferrer">this offer</a>)</li> <li>King Print RAMPS 1.6 Plus</li> </ul> <p>This information is so far only from webshop offers, so might not be the most reliable (and I did not test it myself yet). If somebody can find a confirmation from the manufacturer's spec documents, please let me know.</p>
1,414
<p>I have this workspace downloaded off the web and I try running it on a tomcat server from a fresh installation of Eclipse Ganymede. This particular project came with its own workspace. </p> <p>When I select Tomcat v6.0 I get a message </p> <blockquote> <p>Cannot create a server using the selected type</p> </blockquote> <p>Older tomcat versions are available, though. </p> <p>I guess I have to recreate some configuration setting. The question is which one? This seems to be some odd error as creating a new dynamic web project lets me configure tomcat for both of them</p>
<p>I had a similar problem, but my solution is a little simpler. The problem was causesd by renaming the original folder that was referenced by the server definition.</p> <p>Go to Window/Preferences/Server/Runtime Environments, remove the broken reference. Then, click 'Add' to create a new reference, select the appropriate tomcat version, click next and you'll see the incorrect path reference. Fix it. Move on.</p>
<p>What version of Eclipse? Europa? Ganymede?</p> <p>What do you mean by workspace? An Eclipse workspace is not something you deploy, it holds your projects.</p> <p>You will need to generate a WAR file (or the folder of files that would comprise the WAR file), a project would typically include an ANT or Maven build script to do this, or if the project used Eclipse's Dynamic Web Project type there might be a 'generate WAR' option somewhere. Without further details I can't help any more.</p>
11,953
<p>The application de-serializes a stream into dynamically allocated objects and then keeps base type pointers in a linked list (i.e. abstract factory). It's too slow. Profiling says all the time is spent in <code>operator new</code>.</p> <p>Notes: The application already uses a custom memory allocator that does pooling. The compiler is VC++ 6.0 and the code uses the old RogueWave collections rather than the STL.</p> <p>The only idea I have right now is to introduce Object Pooling. I'd maintain large collections of pre-allocated objects for each type and re-use them. But this will be a lot of work in this old code, and I'm not yet sure there's enough re-use that it would even help. I was hoping someone smarter than me has an idea.</p>
<p>The only way is to reduce the number of memory allocations. Have you used a profiler that will tell you exactly what is doing the allocation? Are you possibly doing some string manipulation?<br> If all the time is spent allocating the objects the factory is creating, you may need to go to a pool. </p>
<p>I'll assume that most allocations relate to the list of objects you're talking about. If you're actually allocating a bunch of other objects as part of the parsing that's too slow, then you need more information to optimize.</p> <ul> <li><p>I don't know anything about the RogueWave collections, but if their linked list allocates an external node, then you should be able to halve the number of allocations by using an intrusive list - write your own container if necessary. This assumes that you don't need to put the same objects on multiple lists at once (or in the same list more than once).</p></li> <li><p>If your app is multi-threaded, then the memory allocator will likely be doing some synchronization. But if you can arrange for these objects to be freed in the same thread they're allocated, then they could be allocated off a per-thread heap by overloading operator new. This might be faster: synchronization isn't necessarily all that slow provided there isn't contention, but it takes more time than none, and if other threads in your process are allocating at the same time then there will be contention.</p></li> <li><p>For even more limited use-cases, if you find that you allocate a whole load of these things and then always free them all at once when you're done with the list, you can write an even faster "gc-style" allocator. </p></li> </ul> <p>Operator new/delete would call functions like these (and size might be a constant rather than a parameter, if there's only one class you use the pool for):</p> <pre><code>char *alloc(POOL *pool, size_t size) { // if size is a parameter, and may be a non-multiple the max alignment // requirement on your system, and you want this to work in general: // size = (size + MAX_ALIGNMENT - 1) % ALIGNMENT; char *block = pool.current; char *next = block + size; if (next &gt; pool.limit) throw std::bad_alloc(); pool.current = next; return block; } void free(char *block) { return; } void freeAll(POOL *pool) { pool.current = pool.start; return; } </code></pre> <p>This should ensure that operator new takes trivial time compared with what you spend parsing the objects you're creating. But it does require the application to identify the times at which it should create, destroy, and clear pools, and to to use a suitable new operator taking the pool pointer as a parameter, so it's not a drop-in replacement.</p>
37,616
<p>I have UIWebView within a UIScrollView. Then as I scroll, the web view displays first two pages correctly but does draws only half of the third the page. If I tap on the web view it draws the content or if I call <code>-[UIWebView reload]</code> in <code>-scrollViewDidEndDecelerating</code>, it shows the content. </p> <p>Is there any way I can make the web view draw correctly?</p>
<p>UIWebViews cannot be loaded concurrently. You must load one, wait til it finishes, then load the next, and so on.</p> <p>You can do this on a timer, or wait until when the scrolled UIWebView has the focus before loading the data.</p>
<p>All UIViews have a size limit of 1024x1024 pixels. This is stated at the end of the Overview section of the UIView documentation.</p> <p>If your web view must have more than 1024px of content, you will have to take it out of the parent scroll view and let it manage scrolling on its own.</p>
33,531
<p>Many database systems don't allow comments or descriptions of tables and fields, so how do you go about documenting the purpose of a table/field apart from the obvious of having good naming conventions?</p> <p>(Let's assume for now that "excellent" table and field names are not enough to document the full meaning of every table, field and relationship in the database.)</p> <p>I know many people use UML diagrams to visualize the database, but I have rarely&mdash;if ever&mdash;seen a UML diagram including field comments. However, I have good experience with using comments inside <code>.sql</code> files. The downside to this approach is that it requires the <code>.sql</code> files to be manually kept up-to-date as the database structure changes over time&mdash;but if you do, you can also have it under version control.</p> <p>Some other techniques I have seen are separate document describing database structure and relationships and manually maintained comments inside ORM code or other database-mapping code.</p> <p>How have you solved this problem in the past? What methods exists and what are the various pros and cons associated with them? How you would you like this solved in "a perfect world"?</p> <p><strong>Update</strong></p> <p>As others have pointed out, most of the popular SQL engines do in fact allow comments, which is great. Oddly enough, people don't seem to be using these features much. At least not on the projects I have been involved with in the past.</p>
<p>MySQL <a href="http://dev.mysql.com/doc/refman/5.0/en/create-table.html" rel="noreferrer">allows</a> comments on tables and rows. PostgreSQL <a href="http://www.postgresql.org/docs/7.4/interactive/sql-comment.html" rel="noreferrer">does</a> as well. From other answers, Oracle and MSSQL have comments too.</p> <p>For me, a combination of UML diagram for a quick refresher on field names, types, and constraints, and an external document (TeX, but could be any format) with extended description of everything database-related - special values, field comments, access notes, whatever - works best.</p>
<p>Since we use Rational Software Architect, we use its data discovery features to document our databases and then annotate them from there.</p>
22,549
<p>I am using the dojo.io.iframe.send method to send a file to my server. I want to provide a way that the user can cancel the send once it is in progress, in case it is taking too long or the user realizes she sent the wrong file.</p> <p>I can't figure a way to do this. I could use a timeout to terminate the send if it is taking a long time (that is, the server does not respond quickly), but that is not what I want. I want to terminate any time the user makes a gesture (such as clicking a "Cancel" button.</p> <p>Thanks!</p>
<p>For security reasons JavaScript cannot even access the file you are sending up. All file uploads are done using a form and handled by the browser directly. To my best knowledge there is no direct interface to monitor the progress of upload, nor the way to affect it (e.g., cancel it).</p> <p>Navigating away may help, but it is still up to the browser to interrupt the transfer or not &mdash; there is no specification for that.</p> <p>To sum it up: not possible to do it reliable in JavaScript in the portable fashion. That means Dojo does not provide this functionality.</p>
<p>What a friend did was simply reloading the webpage when the cancel button was preseed (I think by calling document.location.refresh function). There IS also a way of monitoring the progress o an upload (having a progress bar), but it's server dependent (in the case I saw, it was an apache module, then you would poll for the progress on a specified link and the server would return the progress).</p>
37,238
<p>C++ is mostly a superset of C, but not always. In particular, while enumeration values in both C and C++ implicitly convert into int, the reverse isn't true: only in C do ints convert back into enumeration values. Thus, bitflags defined via enumeration declarations don't work correctly. Hence, this is OK in C, but not in C++:</p> <pre><code>typedef enum Foo { Foo_First = 1&lt;&lt;0, Foo_Second = 1&lt;&lt;1, } Foo; int main(void) { Foo x = Foo_First | Foo_Second; // error in C++ return 0; } </code></pre> <p>How should this problem be handled efficiently and correctly, ideally without harming the debugger-friendly nature of using Foo as the variable type (it decomposes into the component bitflags in watches etc.)?</p> <p>Consider also that there may be hundreds of such flag enumerations, and many thousands of use-points. Ideally some kind of efficient operator overloading would do the trick, but it really ought to be efficient; the application I have in mind is compute-bound and has a reputation of being fast.</p> <p>Clarification: I'm translating a large (>300K) C program into C++, so I'm looking for an efficient translation in both run-time and developer-time. Simply inserting casts in all the appropriate locations could take weeks.</p>
<p>Why not just cast the result back to a Foo?</p> <pre><code>Foo x = Foo(Foo_First | Foo_Second); </code></pre> <p>EDIT: I didn't understand the scope of your problem when I first answered this question. The above will work for doing a few spot fixes. For what you want to do, you will need to define a | operator that takes 2 Foo arguments and returns a Foo:</p> <pre><code>Foo operator|(Foo a, Foo b) { return Foo(int(a) | int(b)); } </code></pre> <p>The int casts are there to prevent undesired recursion.</p>
<p>Either leave the result as an int or static_cast:</p> <pre><code>Foo x = static_cast&lt;Foo&gt;(Foo_First | Foo_Second); // not an error in C++ </code></pre>
24,332
<p>I once knew a website where the user could generate the little W3C valid CSS tags which looked much nicer than the too large W3C official ones. It was also possible to fill the icons with whatever content and color for other stuff.</p> <p>I've lost the bookmark and wasn't able to google it, can you post it and maybe other such resources?</p> <p>EDIT: and yes I know ...</p> <p>Can I modify the existing icons to create my own?</p> <p>No. The validator's icons are distributed under the W3C document license, which allows distribution but does not allow derivative works.</p> <p>BUT I don't care, cause I don't want my design to look ugly.</p>
<p>You probably mean <a href="http://antipixel.com/blog/archives/2002/10/22/steal_these_buttons.html" rel="noreferrer">antipixel's icons</a> and <a href="http://www.lucazappa.com/brilliantMaker/buttonImage.php" rel="noreferrer">LucaZappa's Brilliant Button Maker</a>.</p> <p><a href="http://img353.imageshack.us/img353/1368/stealthesebuttonsli4.gif" rel="noreferrer">Picture of the icons http://img353.imageshack.us/img353/1368/stealthesebuttonsli4.gif</a></p> <p>From the <a href="http://antipixel.com" rel="noreferrer">antipixel website</a>:</p> <blockquote> <p><strong>If you want them, they’re yours</strong>, <strong>gratis, no strings attached.</strong></p> <p><strong>Pull them straight off the main page</strong> <strong>here if you want, and if you’d like to</strong> <strong>change anything about them, go ahead</strong> <strong>and do that.</strong> I’m posting the Photoshop files below so you can download those and change anything you want. You do not need to give me credit or provide a link back here or anything like that. (Some people are already using them and at least one kind soul has posted such a link back here. You don’t need to do that anymore, but thank you for being a more than decent person.)</p> </blockquote> <p><a href="http://www.antipixel.com/blog/archives/2002/10/23/rss_buttons.html" rel="noreferrer">RSS buttons are also available.</a></p>
<p>Be careful though, W3C is strict about their logo usage (as is any company):<br> <a href="http://www.w3.org/Consortium/Legal/logo-usage-20000308" rel="nofollow noreferrer">W3C Logo and Icon Usage</a></p>
47,286
<p>If your data change after the application is deployed, how do you keep the database up to date? </p> <p>I mean, you can add or remove table, thats a simple task. Altering an existing table can be trivial too. But if you change the structure often, how do you keep that under a control?</p> <p>I used to keep a table with a current database version in database. Then every upgrade was an SQL file that did its work - create new table, add a column or move the data. Files were named after those versions - so if my upgrade script got the database version 10, it just took all files from 11.sql to N.sql and applied each one of them incrementing database version number at the same time.</p> <p>This seems to be working all right, but I'm wondering - what's your strategy for such tasks?<br> Also this system doesn't seem perfect if I normalize a table in one "patch" and after that I denormalize it again for whatever reasons. Then it's done twice.</p> <p>But, writing a complete upgrade script each time I change something seems painful, and error-prone. At least more then such atomic changes.</p> <p>Also, I can expect that diffrent customers have diffrent database versions running at any time, so I really should have a way to go up from any point.</p>
<p>Personally I use a very similar process to what you have listed, I can see your argument about changing, but VERY rarely do I make a change, then change it back to the old way on a production site. In testing, yes, that happens, but in terms of an actual production site, I don't see it as a big deal.</p> <p>Keeping individual version scripts, IMHO are not only good for deployment, but also good for providing items that can be checked into source control.</p>
<p>Use a tool like RedGate's SQLCompare or xSQL Object from xSQL Software to generate your diff/delta T-SQL scripts on the fly.</p> <p>You can even integrate it as part of your build process if you like.</p> <p>For different customers with different databases, you simply have different reference databases for them that you compare against. Once you release an update to a customer, you update your own reference site with the same diff script.</p> <p>That's it in a nutshell.</p>
29,811
<p>I would like to distribute my .NET programs without the .NET framework. Is it possible to compile a .NET program to machine code?</p>
<p>Yes, you can precompile using Ngen.exe, however this does not remove the CLR dependence.</p> <p>You must still ship the IL assemblies as well, the only benefit of Ngen is that your application can start without invoking the JIT, so you get a real fast startup time. </p> <p>According to CLR Via C#:</p> <blockquote> <p>Also, assemblies precompiled using Ngen are usually slower than JIT'ed assemblies because the JIT compiler can optimize to the targets machine (32-bit? 64-bit? Special registers? etc), while NGEN will just produce a baseline compilation.</p> </blockquote> <p>EDIT:</p> <p>There is some debate on the above info from CLR Via C#, as some say that you are required to run Ngen on the target machine only as part of the install process.</p>
<p>I'd always thought it would be cool to compile c# to machine code directly without the CLR dependency though....</p>
17,011
<p>Since I'm not a huge fan of any of the current solutions for managing the resources and knowledge that I have, I was thinking about making my own solution, which will involve custom code as well as possible integration of FOSS solutions. I would start development on my local machine, but if I like it, how difficult would it be to migrate over to a public server and let others also use this tool? What kinds of challenges might I be facing?</p>
<p>In theory, nothing, beyond just the process of moving stuff to the new machine. You can set up your own servers, on your own ports (port 80 for example).</p> <p>You can even create your own fake domain at home, with just a tweak to the /etc/hosts files (or the equivalent on Windows).</p> <p>Now, if you're developing on Windows and hosting on unix, you'll have platform issues, so I'd suggest against that, at least for a first project.</p> <p>But other than that, it should be straightforward.</p>
<p>You didn't hard code any paths to "localhost" did you? If so, that should be the first thing to strip out. Either use relative paths, or have a configurable <strong>{AppPath}</strong> variable of some kind that you only need ever change once.</p> <p>By the way, what language/framework are you using? it would help us provide sample code.</p>
19,213
<p>The system default polygon fill mode in current device context is <code>ALTERNATE</code> (as I've learned from the Petzold book on Windows programming) and this one is used in <a href="http://msdn.microsoft.com/en-us/library/ms533274(VS.85).aspx" rel="nofollow noreferrer"><code>Polygon</code></a> Win32 function unless you change the mode with <a href="http://msdn.microsoft.com/en-us/library/ms536642(VS.85).aspx" rel="nofollow noreferrer"><code>SetPolyFillMode</code></a>.</p> <p><strong>My question is</strong>: Does the GDI+ <a href="http://msdn.microsoft.com/en-us/library/ms535958(VS.85).aspx" rel="nofollow noreferrer"><code>Graphics::FillPolygon</code></a> (without the <code>FillMode</code> parameter in its signature) method also use the current device context fill mode or sets the well-known-default and then sets back the mode set before it was called?</p> <p>Thanks!</p>
<p>I don't know the answer off the top of my head, but you could try finding out by retrieving the fill mode before and after the call. If it's not different, it's either not been changed, or was changed then changed back.</p>
<p>I looked at the reference source and FillPolygon without a fill mode simply calls FillPolygon with a fill mode of alternate.</p> <p>FillPolygone with a fill mode calls a method named GdipFillPolygonI, but I can't find anything about that method.</p>
7,454
<p>We are working with Tomcat + Axis2 + POJO for web service implementation, and we encountered some issues with POJO and Axis2 that are a showstopper for us. It seems that Axis2 and POJO implementation of SOAP parsing ignores the names of the XML elements and just assign values to the arguments according to the order of the XML elements in the SOAP message. This thing causes a lot of problems in complex APIs.</p> <p>After some swimming in the documentation swamp of Axis2 I was more confused then I came in, so I really need some help.</p> <p>I understand that JAX-WS and Axis2 doesn't have those issues (correct me if I'm wrong), but I can't seem to know how to develop and deploy such solution.</p> <p>I wrote a POJO, and annotated it with the JAX-WS annotations, I executed wsgen on the class, and packed all in an aar file along with this <em>services.xml</em> file:</p> <pre><code>&lt;service name="TESTService" &gt; &lt;description&gt; TEST web service &lt;/description&gt; &lt;messageReceivers&gt; &lt;messageReceiver mep="http://www.w3.org/2004/08/wsdl/in-only" class="org.apache.axis2.jaxws.server.JAXWSMessageReceiver" /&gt; &lt;messageReceiver mep="http://www.w3.org/2004/08/wsdl/in-out" class="org.apache.axis2.jaxws.server.JAXWSMessageReceiver"/&gt; &lt;/messageReceivers&gt; &lt;parameter name="ServiceClass"&gt;com.test.WsdlImpl&lt;/parameter&gt; &lt;/service&gt; </code></pre> <p>When I try to execute a web service call I get an exception in Tomcat:</p> <pre> [ERROR] The service class cannot be found for this AxisService. java.lang.RuntimeException: The service class cannot be found for this AxisService. at org.apache.axis2.jaxws.server.JAXWSMessageReceiver.receive(JAXWSMessageReceiver.java:95) at org.apache.axis2.engine.AxisEngine.receive(AxisEngine.java:176) at org.apache.axis2.transport.http.HTTPTransportUtils.processHTTPPostRequest(HTTPTransportUtils.java:275) at org.apache.axis2.transport.http.AxisServlet.doPost(AxisServlet.java:133) at javax.servlet.http.HttpServlet.service(HttpServlet.java:710) at javax.servlet.http.HttpServlet.service(HttpServlet.java:803) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:175) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:128) at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:286) at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:844) at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:583) at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:447) at java.lang.Thread.run(Unknown Source) </pre> <p>Please help me by explaining how to deploy a JAX-WS with Tomcat + Axis2 (if CXF works with Tomcat I can use it also), or direct me to a GOOD tutorial that covers Tomcat+Axis2.</p> <p>Thanks!!</p>
<p>Straight from Axis2 Web site, <a href="http://ws.apache.org/axis2/1_4_1/jaxws-guide.html" rel="nofollow noreferrer">this</a> is a tutorial covering Axis2 and Jax-Ws. You get the above error probably because the axis2-jaxws-1.3.jar is missing. Check your classpath.</p> <p>You can of course use CXF with Tomcat and my personal opinion is that you would be better off with it.</p>
<p>As well as CXF, another good option would be <a href="http://tuscany.apache.org" rel="nofollow noreferrer">Apache Tuscany</a> - makes turning POJOs into services extremely easy.</p>
44,134
<p>I just got hold of a PDA (Samsung Omnia i900) with an embedded motion sensor (accelerometer) and would like to code something that would exploit this feature. Any pointers?</p>
<p>You might want to take a look at the Samsung Accelerometer API for Windows Mobile devices <a href="http://innovator.samsungmobile.com/cms/cnts/knowledge.detail.view.do?platformId=2&amp;cntsId=4600" rel="nofollow noreferrer">http://innovator.samsungmobile.com/cms/cnts/knowledge.detail.view.do?platformId=2&amp;cntsId=4600</a></p>
<p>Just a suggestion. Maybe you could design a game where you have small balls that can be brought to the centre of a maze by tilting the PDA at different angles.</p>
31,536
<p>We are designing a new database and I would like some input in where to put stuff like default values. There are 3 scenarios: </p> <p>1: New values, created_date field. Should the column have a default value when you do an insert? </p> <p>2: Updated values, updated_date fiels. I've been thinkin about implementing a trigger that sets this to getdate(), other option is in code. </p> <p>3: country table with country_name, should we enforce a unique constraint directly on the table or make sure code does this?</p> <p>and last a bit of topic, but we also have an updated_by and created_by (int) in each table that refers to a user_id in the user table. Is it worth the effort to implement this a fk. constraints on all tables? </p>
<p>My best practices:</p> <ul> <li><p>For created/last updated dates, it depends on if you are going to use them as part of your business logic -- if they are for auditing only, use a timestamp on the database. If there is any chance you may want to expose them as business properties, they should be assigned in code.</p></li> <li><p>Unique constraints -- I implement them both in the database and in code. This is an example of the database backing up the validation rules, it doesn't hurt to have them defined in both places. The code definition should catch and handle them, but in the off chance the code fails to catch something, you want the safety net of having the constraint keep the data from being corrupted.</p></li> </ul>
<p>Constraints must go in the database at a minimum. If you have to replicate them in code (or infer them from the database) to provide a better user experience, so be it.</p> <p>The database must be consistent. I have wasted so much time tracking down issues that are the result of "invalid data". </p> <p>These are solved by adding the appropriate constraint and fixing whatever app created the invalid data. I would much rather have 10 tickets because someone can't save an invoice (easy to trace), than one ticket because somehow a report got a weird value which stemmed from bad invoice data.</p>
46,546
<p>A plastic gear of an older DVD player broke. I always read about being 3D printing a "repair revolution". So I looked for a template to give to some printing service, but I found none (and nothing close to it).</p> <p>Could you please explain me, what steps a layman should take to get the gear piece replaced using 3D printing?</p>
<p>If you have the remaining pieces of the gear and enough remains to determine certain measurements, one can either engineer the gear using a number of gear modeling designs, or one can take measurements directly from the parts and engineer a raw design.</p> <p>If the gear you have is not particularly peculiar, it is possible to use a gear generator plug-in, template, or library to make the "foundation" of your gear. The modeling software would then be used to add the appropriate bosses and key ways required to complete the design.</p> <p>If you are considering to create the part yourself, you have a wide selection of programs from which to choose. I'm fond of OpenSCAD, and it does have <a href="http://www.thingiverse.com/akaziuna/collections/openscad-gear-scripts" rel="noreferrer">a number of gear libraries</a>. Simple bosses and key ways are easily accomplished using <a href="http://www.openscad.org/" rel="noreferrer">OpenSCAD</a>.</p> <p><a href="https://i.stack.imgur.com/jPb52.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/jPb52.jpg" alt="Thingiverse gear image"></a></p> <p>Another package available on the internet which includes the option of using a gear generator is <a href="https://www.instructables.com/id/Gearing-up-in-TinkerCad/" rel="noreferrer">Tinkercad</a> which has a reputation of being easy to use. You'll find many tutorials for this program as well.</p> <p>Tinkercad requires an "outside" program to generate the gear design which is then imported to the model workspace. Even a program as simple as Inkscape can create gear profiles to be imported into many design packages.</p> <p>Fusion360 is available free for hobby or non-commercial use, but may not be the easiest to learn in a short time.</p> <p>So many others as well. Use your favorite search engine for "<a href="https://www.google.com/#q=gear+generator+modeling+software" rel="noreferrer">gear generator modeling software</a>" or similar wording and be overloaded with links.</p>
<p>The only 'layman's' option is to find an existing design which solves your problem. If you are lucky, and the product you have has a common failure mode, someone else might have a) solved the same problem already, and b) posted their design online.</p> <p>Sites such as <a href="http://www.thingiverse.com/search?q=dvd+gear&amp;sa=" rel="nofollow noreferrer">thingiverse</a> have plenty of designs, but finding the right thing might be hard. If you find something, you can then look for someone to print it for you. Its not clear if you tried this already, but maybe the answer helps someone else. </p>
529
<p>I have this:</p> <pre><code>template &lt;typename T&gt; class myList { ... class myIterator { ... T&amp; operator*(); } } ... template&lt;typename T&gt; T&amp; myList&lt;T&gt;::myIterator::operator*() { ... } </code></pre> <p>That is giving me the following error: "expected initializer before '&amp;' token". What exactly am I supposed to do? I already tried adding "template myList::myIterator" before it, but that didn't work.</p>
<p>How about some semicolons and publics:</p> <pre><code>template &lt;typename T&gt; class myList { public: class myIterator { public: T&amp; operator*(); }; }; </code></pre>
<p>Compiles Fine:<br> If you want to post code it should be as simple as passable, BUT it should still be compilable. If you cut stuff out will nilly then you will probably remove the real error that you want fixed and the people here are real good at finding problems if you show people the code.</p> <p>In this situation we can only put it down to some code that you have removed.</p> <pre><code>template &lt;typename T&gt; class myList { public: class myIterator { public: T&amp; operator*(); }; }; template&lt;typename T&gt; T&amp; myList&lt;T&gt;::myIterator::operator*() { static T x; return x; } int main() { myList&lt;int&gt; a; myList&lt;int&gt;::myIterator b; int&amp; c= *b; } </code></pre>
47,513
<p>I use a byte to store some flag like <code>10101010</code>, and I would like to know how to verify that a specific bit is at <code>1</code> or <code>0</code>.</p>
<p>Here's a function that can be used to test any <code>bit</code>:</p> <pre><code>bool is_bit_set(unsigned value, unsigned bitindex) { return (value &amp; (1 &lt;&lt; bitindex)) != 0; } </code></pre> <p><strong>Explanation</strong>:</p> <p>The <a href="https://learn.sparkfun.com/tutorials/binary#bitwise-operators" rel="nofollow noreferrer">left shift operator</a> <code>&lt;&lt;</code> creates a <a href="https://stackoverflow.com/questions/tagged/bitmask">bitmask</a>. To illustrate:</p> <ul> <li><code>(1 &lt;&lt; 0)</code> equals <code>00000001</code></li> <li><code>(1 &lt;&lt; 1)</code> equals <code>00000010</code></li> <li><code>(1 &lt;&lt; 3)</code> equals <code>00001000</code></li> </ul> <p>So a shift of <code>0</code> tests the rightmost bit. A shift of <code>31</code> would be the leftmost bit of a 32-bit value.</p> <p>The <a href="https://learn.microsoft.com/en-us/cpp/cpp/bitwise-and-operator-amp?view=msvc-170" rel="nofollow noreferrer">bitwise-and operator</a> (<code>&amp;</code>) gives a result where all the bits that are <code>1</code> on both sides are set. Examples:</p> <ul> <li><code>1111 &amp; 0001</code> equals <code>0001</code></li> <li><code>1111 &amp; 0010</code> equals <code>0010</code></li> <li><code>0000 &amp; 0001</code> equals <code>0000</code>.</li> </ul> <p>So, the expression:</p> <pre><code>(value &amp; (1 &lt;&lt; bitindex)) </code></pre> <p>will return the bitmask if the associated bit (<code>bitindex</code>) contains a <code>1</code> in that position, or else it will return <code>0</code> (meaning it does <strong>not</strong> contain a <code>1</code> at the assoicated <code>bitindex</code>).</p> <p>To simplify, the expression tests if the result is greater than <code>zero</code>.</p> <ul> <li>If <code>Result &gt; 0</code> returns <code>true</code>, meaning the byte has a <code>1</code> in the tested <code>bitindex</code> position.</li> <li>All else returns <code>false</code> meaning the result was zero, which means there's a <code>0</code> in tested <code>bitindex</code> position.</li> </ul> <p>Note the <code>!= 0</code> is not required in the statement since it's a <a href="https://www.geeksforgeeks.org/bool-in-c/" rel="nofollow noreferrer">bool</a>, but I like to make it explicit.</p>
<p>Use a bitwise (not logical!) AND to compare the value against a bitmask.</p> <pre><code>if (var &amp; 0x08) { /* The fourth bit is set */ } </code></pre>
15,457
<p>We have an existing add-in that we publish to users via click once. We would now like to use this as a vehicle to publish some of our existing C# methods directly into Excel so that the users can call them as a UDF.</p> <p>For example - I have an assembly called MyAssembly, that has a class called MyClass with a public method called MyMethod. I also have an excel addin which adds some item to the ribbon for some custom functionality. I would now like to publish MyAssembly with my existing addin so that a person who has the addin installed can enter =MyMethod into a cell and have my custom method run.</p> <p>How would one go about doing this?</p>
<p>I solved this quite comprehensively by using ExcelDna, an open source XLL implementation which is very simple to use, and pretty much avoids the whole COM debacle all together. So far it has matched our requirements perfectly...</p> <p><a href="http://groups.google.com/group/exceldna" rel="nofollow noreferrer">http://groups.google.com/group/exceldna</a></p>
<p>you have not been very verbose about what you want to do. What do you mean with "users can call them"? </p> <p>If you mean that add-in methods should be exposed to VBA you can find two articles on that here:</p> <ul> <li><a href="http://blogs.msdn.com/andreww/archive/2008/08/13/comaddins-race-condition.aspx" rel="nofollow noreferrer">http://blogs.msdn.com/andreww/archive/2008/08/13/comaddins-race-condition.aspx</a></li> <li><a href="http://blogs.msdn.com/andreww/archive/2008/08/11/why-your-comaddin-object-should-derive-from-standardolemarshalobject.aspx" rel="nofollow noreferrer">http://blogs.msdn.com/andreww/archive/2008/08/11/why-your-comaddin-object-should-derive-from-standardolemarshalobject.aspx</a></li> </ul>
47,353
<p>I have a Java SOAP data service which sits on top of a Sybase database which, for reasons out of my control, has unreliable performance. The database is part of a vendor package which has been modified by an internal team and most of the issues are caused by slow response times at certain times of the day. </p> <p>The SOAP service provides data to a calculation grid and when I request data, I need the response time to be both fast and <em>consistent</em>. The service provides basic CRUD functionality, but the ratio of reads to writes is approximately 100:1. </p> <p>What is the best strategy to isolate myself from the database's unreliable performance and ensure that the SOAP service is fast and reliable?</p>
<p>I have seen this issue a few times, normally with a vendor database. </p> <p>If this is on Windows, you could create a Windows service as an intermediary between the SOAP service and the database. Then put a message queue (either MSMQ or a JMS implementation such as MQ Series) between the SOAP service and Windows service for asynchronous communications. In this way the database performance issues will no longer affect the SOAP service. This solution does, however, come at the cost of increased complexity.</p> <p>Note that a .NET web service can be called by, and respond asynchronously to, its clients. I'm not sure if that's possible with a Java SOAP service. </p> <p>If this is on some flavour of Unix, I assume it has similar functionality to a Windows service - maybe a daemon.</p>
<p>How about caching the responses from the web service (either on the client invoking the WS request, or by setting up a proxy web service in between)?</p>
37,366
<p>i have a few classes that i am trying to move to using generics</p> <p>Class1: Curve</p> <p>this class has the following code:</p> <pre><code>public class Curve : IEnumerable IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); // Calls non-interface method } public RTRatePointEnumerator GetEnumerator() { return new RTRatePointEnumerator(_hash); } </code></pre> <p>Class 2:</p> <pre><code> public class CurvePointEnumerator : IEnumerator </code></pre> <p>what is the recommended conversion of these two classes to using generics</p>
<p>You didn't specify the type being returned from the enumerator. but I'm going to guess based on the names it's RTRatePoint and CurvePoint. I would change the code to be the following </p> <pre><code>class Curve: IEnumerable&lt;RTRatePoint&gt; { IEnumerator&lt;RTRatePoint&gt; IEnumerable&lt;RTRatePoint&gt;.GetEnumerator() { return GetEnumerator(); } public RTRatePointEnumerator GetEnumerator() { return new RTRatePointEnumerator(_hash); } } class CurvePointEnumerator : IEnumerator&lt;CurvePoint&gt; </code></pre> <p>One item that may trip you up is that IEnumerator&lt;T&gt; additionally implements IDisposable so CurvePointEnumerator and RTRatePointEnumerator will need to have a Dispose method added. Likely though this method can be pretty much empty. Reason being if you weren't disposing anything before, there's no need to now. </p> <pre><code>void IDispose.Dispose() { // Nothing to see here } </code></pre>
<p><code>IEnumerable&lt;T&gt; and IEnumerator&lt;T&gt;</code></p> <p>gah, it swallowed my code</p>
42,733
<p>I've been asked to create a fairly straightforward website for a friend. Essentially a user will log in, fill in a set of information, and submit it. This data will then need to written to a database (and read from/presented at a future point).</p> <p>I'm not really a web developer (I do mostly Java/C++), but about 3 years ago I worked on a project where we created a site using WAMP (Windows, Apache, MySQL and PHP), with a bit of JavaScript/AJAX thrown in for good measure. I was going to use WAMP again, but am concerned that there might be better tools available now. </p> <p>So, is the WAMP approach a good one for a straightforward site like this? </p> <p>If so, what tools would you recommend to use for the development of PHP/Javascript?</p> <p>Finally, I saw in one of the blog posts that Stack Overflow uses JQuery. Would it be worthwhile to use these libs?</p>
<p>Assuming that the website you're going to be building is hosted on a WAMP stack, then I'd say continue to use that; otherwise, you may wanna stick with Windows/IIS/PHP/MySQL or SQL Server. I always try to make sure my development environment mirrors production as much as possible.</p> <p>Secondly, if the user is simply logging in, submitting a form, and is then considered to be done, then using Ajax might be overkill; however, if you're definitely going to be going to Ajax route, then I definitely recommend using a library. <a href="http://prototypejs.org/" rel="nofollow noreferrer">Prototype</a> or <a href="http://jquery.com/" rel="nofollow noreferrer">jQuery</a> are fine - either one makes Ajax ridiculously simple.</p> <p>Finally, as far as suggested tools are concerned, find something that fits the bill for what you're developing. If this site is as simple as you claim it is, something like <a href="http://notepad-plus.sourceforge.net/uk/site.htm" rel="nofollow noreferrer">Notepad++</a> might be sufficient. Another option for the WAMP/LAMP stack is <a href="http://www.aptana.com/" rel="nofollow noreferrer">Aptana Studio</a>. If you're going the Windows/IIS/SQL Server route, then use some of the <a href="http://www.microsoft.com/Express/" rel="nofollow noreferrer">Microsoft Express</a> tools.</p> <p>I could be way off, but if you're building a really simple site, don't spend more time configuring shiny new tools for something that can be done with the existing toolbox you've got.</p>
<p>Using this as an opportunity to try out Ruby on Rails isn't bad. From you wording I assume that you have complete control on the environment. As an experience developer, it shouldn't be that difficult. The convention over configuration approach also simplifies the development.</p> <p>I am afraid that I am not helping much!</p>
30,203
<p>As compared to say:</p> <pre><code>REPLICATE(@padchar, @len - LEN(@str)) + @str </code></pre>
<p>This is simply an inefficient use of SQL, no matter how you do it. </p> <p>perhaps something like </p> <pre><code>right('XXXXXXXXXXXX'+ rtrim(@str), @n) </code></pre> <p>where X is your padding character and @n is the number of characters in the resulting string (assuming you need the padding because you are dealing with a fixed length). </p> <p>But as I said you should really avoid doing this in your database.</p>
<p>Here is how I would normally pad a varchar</p> <pre><code>WHILE Len(@String) &lt; 8 BEGIN SELECT @String = '0' + @String END </code></pre>
14,822
<p>How should I manage tables that refer to site 'events'. i.e. certain activities a user has done on a website that I use for tracking. I want to be able to do all kinds of datamining and correlation between different activities of users and what they have done.</p> <p>Today alone I added 107,000 rows to my SiteEvent table. I dont think this is sustainable!</p> <p>The database is SQL Server. I'm mainly referring to best practice activites with respect to managing large amounts of data. </p> <p>For instance :</p> <ul> <li>Should I keep these tables in a database all of their own? If i need to join with other tables this could be a problem. Currently I just have one database with everything in.</li> <li>How ought I to purge old records. I want to ensure my db file doesnt keep growing.</li> <li>Best practices for backing up and truncating logs</li> <li>Will adding additional indexes dramatically increase the size of the DB with so many records?</li> <li>Any other things i need to so in SQL Server that might come back to bite me later?</li> </ul> <p>FYI: these are the tables</p> <pre><code>CREATE TABLE [dbo].[SiteEvent]( [SiteEventId] [int] IDENTITY(1,1) NOT NULL, [SiteEventTypeId] [int] NOT NULL, [SiteVisitId] [int] NOT NULL, [SiteId] [int] NOT NULL, [Date] [datetime] NULL, [Data] [varchar](255) NULL, [Data2] [varchar](255) NULL, [Duration] [int] NULL, [StageSize] [varchar](10) NULL, </code></pre> <p>and</p> <pre><code>CREATE TABLE [dbo].[SiteVisit]( [SiteVisitId] [int] IDENTITY(1,1) NOT NULL, [SiteUserId] [int] NULL, [ClientGUID] [uniqueidentifier] ROWGUIDCOL NULL CONSTRAINT [DF_SiteVisit_ClientGUID] DEFAULT (newid()), [ServerGUID] [uniqueidentifier] NULL, [UserGUID] [uniqueidentifier] NULL, [SiteId] [int] NOT NULL, [EntryURL] [varchar](100) NULL, [CampaignId] [varchar](50) NULL, [Date] [datetime] NOT NULL, [Cookie] [varchar](50) NULL, [UserAgent] [varchar](255) NULL, [Platform] [int] NULL, [Referer] [varchar](255) NULL, [RegisteredReferer] [int] NULL, [FlashVersion] [varchar](20) NULL, [SiteURL] [varchar](100) NULL, [Email] [varchar](50) NULL, [FlexSWZVersion] [varchar](20) NULL, [HostAddress] [varchar](20) NULL, [HostName] [varchar](100) NULL, [InitialStageSize] [varchar](20) NULL, [OrderId] [varchar](50) NULL, [ScreenResolution] [varchar](50) NULL, [TotalTimeOnSite] [int] NULL, [CumulativeVisitCount] [int] NULL CONSTRAINT [DF_SiteVisit_CumulativeVisitCount] DEFAULT ((0)), [ContentActivatedTime] [int] NULL CONSTRAINT [DF_SiteVisit_ContentActivatedTime] DEFAULT ((0)), [ContentCompleteTime] [int] NULL, [MasterVersion] [int] NULL CONSTRAINT [DF_SiteVisit_MasterVersion] DEFAULT ((0)), </code></pre>
<p>You said two things that are in conflict with each other.</p> <ol> <li>I want to be able to do all kinds of datamining and correlation between different activities of users and what they have done.</li> <li>I want to ensure my db file doesnt keep growing.</li> </ol> <p>I am also a big fan of data mining, but you need data to mine. In my mind, create a scalable database design and plan for it to grow TREMENDOUSLY. Then, go grab all the data you can. Then, finally, you will be able to do all the cool data mining you are dreaming about.</p>
<p>Re-thinking the problem might be just what the doctor ordered. Can 100k records per day really be that useful? Seems like information overload to me. Maybe start by reducing the granularity of your usage tracking?</p>
28,314
<p>The title is kind of obscure. What I want to know is if this is possible:</p> <pre><code>string typeName = &lt;read type name from somwhere&gt;; Type myType = Type.GetType(typeName); MyGenericClass&lt;myType&gt; myGenericClass = new MyGenericClass&lt;myType&gt;(); </code></pre> <p>Obviously, MyGenericClass is described as:</p> <pre><code>public class MyGenericClass&lt;T&gt; </code></pre> <p>Right now, the compiler complains that 'The type or namespace 'myType' could not be found." There has got to be a way to do this.</p>
<p>You can't do this without reflection. However, you <em>can</em> do it with reflection. Here's a complete example:</p> <pre><code>using System; using System.Reflection; public class Generic&lt;T&gt; { public Generic() { Console.WriteLine("T={0}", typeof(T)); } } class Test { static void Main() { string typeName = "System.String"; Type typeArgument = Type.GetType(typeName); Type genericClass = typeof(Generic&lt;&gt;); // MakeGenericType is badly named Type constructedClass = genericClass.MakeGenericType(typeArgument); object created = Activator.CreateInstance(constructedClass); } } </code></pre> <p>Note: if your generic class accepts multiple types, you must include the commas when you omit the type names, for example:</p> <pre><code>Type genericClass = typeof(IReadOnlyDictionary&lt;,&gt;); Type constructedClass = genericClass.MakeGenericType(typeArgument1, typeArgument2); </code></pre>
<p>If you know what types will be passed you can do this without reflection. A switch statement would work. Obviously, this would only work in a limited number of cases, but it'll be much faster than reflection.</p> <pre><code>public class Type1 { } public class Type2 { } public class Generic&lt;T&gt; { } public class Program { public static void Main() { var typeName = nameof(Type1); switch (typeName) { case nameof(Type1): var type1 = new Generic&lt;Type1&gt;(); // do something break; case nameof(Type2): var type2 = new Generic&lt;Type2&gt;(); // do something break; } } } </code></pre>
33,366
<p>I have an animation that I'm displaying using a UIImageView:</p> <pre><code>imageView.animationImages = myImages; imageView.animationDuration = 3; [imageView startAnimating]; </code></pre> <p>I know I can stop it using stopAnimating, but what I want is to be able to pause it. The reason is that when you call stop, none of your animation images are displayed, whereas I would like the last one that is up at the time when I hit a button to stay up.</p> <p>I have tried setting the duration to a much larger number, but that causes all the images to disappear as well. There must be a really basic way to do this?</p>
<p>Hmmm...since no one seems to know I guess it's not possible. </p> <p>I went ahead and wrote my own <code>UIView</code>, with a <code>UIImageView</code> <code>subview</code>, that uses an <code>NSTimer</code> to switch between images. The advantage of this is that I can pause and resume the timer at my leisure, and performance doesn't seem to be an issue.</p>
<p>Maybe you can take a screenshot of the last animated image and display that?</p>
31,568
<p>How do you get all the classes in a namespace through reflection in C#?</p>
<p>Following code prints names of classes in specified <code>namespace</code> defined in current assembly.<br> As other guys pointed out, a namespace can be scattered between different modules, so you need to get a list of assemblies first.</p> <pre><code>string nspace = "..."; var q = from t in Assembly.GetExecutingAssembly().GetTypes() where t.IsClass &amp;&amp; t.Namespace == nspace select t; q.ToList().ForEach(t =&gt; Console.WriteLine(t.Name)); </code></pre>
<p>Quite simple</p> <pre><code>Type[] types = Assembly.Load(new AssemblyName("mynamespace.folder")).GetTypes(); foreach (var item in types) { } </code></pre>
10,510
<p>I have a RichTextBox where I need to update the Text property frequently, but when I do so the RichTextBox "blinks" annoyingly as it refreshes all throughout a method call.</p> <p>I was hoping to find an easy way to temporarily suppress the screen refresh until my method is done, but the only thing I've found on the web is to override the WndProc method. I've employed this approach, but with some difficulty and side effects, and it makes debugging harder, too. It just seems like there's got to be a better way of doing this. Can someone point me to a better solution?</p>
<p>I asked the original question, and the answer that worked best for me was BoltBait's use of SendMessage() with WM_SETREDRAW. It seems to have fewer side effects than the use of the WndProc method, and in my application performs twice as fast as LockWindowUpdate. </p> <p>Within my extended RichTextBox class, I just added these two methods, and I call them whenever I need to stop restart repainting while I'm doing some processing. If I were wanting to do this from outside of the RichTextBox class, I think it would work by just replacing "this" with the reference to your RichTextBox instance.</p> <pre><code> private void StopRepaint() { // Stop redrawing: SendMessage(this.Handle, WM_SETREDRAW, 0, IntPtr.Zero); // Stop sending of events: eventMask = SendMessage(this.Handle, EM_GETEVENTMASK, 0, IntPtr.Zero); } private void StartRepaint() { // turn on events SendMessage(this.Handle, EM_SETEVENTMASK, 0, eventMask); // turn on redrawing SendMessage(this.Handle, WM_SETREDRAW, 1, IntPtr.Zero); // this forces a repaint, which for some reason is necessary in some cases. this.Invalidate(); } </code></pre>
<p>Try this out:</p> <pre><code>myRichTextBox.SuspendLayout(); DoStuff(); myRichTextBox.ResumeLayout(); </code></pre>
23,383
<p>I've created an assembly and referenced it in my Reporting Services report. I've tested the report locally (works), and I then uploaded the report to a report server (doesn't work).</p> <p>Here is the error that is thrown by the custom code I've written.</p> <blockquote> <p>System.Security.SecurityException: Request for the permission of type 'System.Security.Permissions.SecurityPermission, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' failed. at System.Security.CodeAccessSecurityEngine.CheckNReturnSO(PermissionToken permToken, CodeAccessPermission demand, StackCrawlMark&amp; stackMark, Int32 unrestrictedOverride, Int32 create) at System.Security.CodeAccessSecurityEngine.Assert(CodeAccessPermission cap, StackCrawlMark&amp; stackMark) at System.Security.CodeAccessPermission.Assert() at [Snipped Method Name] at ReportExprHostImpl.CustomCodeProxy.[Snipped Method Name] The action that failed was: Demand The type of the first permission that failed was: System.Security.Permissions.SecurityPermission The Zone of the assembly that failed was: MyComputer</p> </blockquote> <p>This project is something I inherited, and I'm not intimately familiar with it. Although I do have the code (now), so I can at least work with it :)</p> <p>I believe the code that is failing is this:</p> <pre><code> Dim fio As System.Security.Permissions.FileIOPermission = New System.Security.Permissions.FileIOPermission(Security.Permissions.PermissionState.Unrestricted) fio.Assert() </code></pre> <p>However, this kind of stuff is everywhere too:</p> <pre><code>Private Declare Function CryptHashData Lib "advapi32.dll" (ByVal hhash As Integer, ByVal pbData As String, ByVal dwDataLen As Integer, ByVal dwFlags As Integer) As Integer </code></pre> <p>I can see either of these being things that Reporting Services would not accommodate out of the box.</p>
<p>This is how I was able to solve the issue:</p> <ul> <li>strongly sign the custom assembly in question</li> <li><p>modify the rssrvpolicy.config file to add permissions for the assembly</p> <pre><code> &lt;CodeGroup class="UnionCodeGroup" version="1" PermissionSetName="FullTrust" Name="Test" Description="This code group grants the Test code full trust. "&gt; &lt;IMembershipCondition class="StrongNameMembershipCondition" version="1" PublicKeyBlob="0024000004800000940100000602000000240000575341310004000001000100ab4b135615ca6dfd586aa0c5807b3e07fa7a02b3f376c131e0442607de792a346e64710e82c833b42c672680732f16193ba90b2819a77fa22ac6d41559724b9c253358614c270c651fad5afe9a0f8cbd1e5e79f35e0f04cb3e3b020162ac86f633cf0d205263280e3400d1a5b5781bf6bd12f97917dcdde3c8d03ee61ccba2c0" /&gt; &lt;/CodeGroup&gt; </code></pre></li> </ul> <p>Side note: here is a great way to get the public key blob of your assembly <a href="http://www.andrewconnell.com/blog/archive/2006/09/15/4587.aspx" rel="noreferrer">VS trick for obtaining the public key token and blob of a signed assembly</a>. </p>
<p>Run your service in administrator mode</p>
5,236
<p>How do I query an Oracle database to display the names of all tables in it?</p>
<pre><code>SELECT owner, table_name FROM dba_tables </code></pre> <p>This is assuming that you have access to the <code>DBA_TABLES</code> data dictionary view. If you do not have those privileges but need them, you can request that the DBA explicitly grants you privileges on that table, or, that the DBA grants you the <code>SELECT ANY DICTIONARY</code> privilege or the <code>SELECT_CATALOG_ROLE</code> role (either of which would allow you to query any data dictionary table). Of course, you may want to exclude certain schemas like <code>SYS</code> and <code>SYSTEM</code> which have large numbers of Oracle tables that you probably don't care about.</p> <p>Alternatively, if you do not have access to <code>DBA_TABLES</code>, you can see all the tables that your account has access to through the <code>ALL_TABLES</code> view:</p> <pre><code>SELECT owner, table_name FROM all_tables </code></pre> <p>Although, that may be a subset of the tables available in the database (<code>ALL_TABLES</code> shows you the information for all the tables that your user has been granted access to). </p> <p>If you are only concerned with the tables that you own, not those that you have access to, you could use <code>USER_TABLES</code>:</p> <pre><code>SELECT table_name FROM user_tables </code></pre> <p>Since <code>USER_TABLES</code> only has information about the tables that you own, it does not have an <code>OWNER</code> column – the owner, by definition, is you.</p> <p>Oracle also has a number of legacy data dictionary views-- <code>TAB</code>, <code>DICT</code>, <code>TABS</code>, and <code>CAT</code> for example-- that could be used. In general, I would not suggest using these legacy views unless you absolutely need to backport your scripts to Oracle 6. Oracle has not changed these views in a long time so they often have problems with newer types of objects. For example, the <code>TAB</code> and <code>CAT</code> views both show information about tables that are in the user's recycle bin while the <code>[DBA|ALL|USER]_TABLES</code> views all filter those out. <code>CAT</code> also shows information about materialized view logs with a <code>TABLE_TYPE</code> of "TABLE" which is unlikely to be what you really want. <code>DICT</code> combines tables and synonyms and doesn't tell you who owns the object.</p>
<pre><code>select * from all_all_tables </code></pre> <p>this additional 'all' at the beginning gives extra 3 columns which are:</p> <pre><code>OBJECT_ID_TYPE TABLE_TYPE_OWNER TABLE_TYPE </code></pre>
25,209
<p>I do the following in command line:</p> <p>1) wget <a href="ftp://mirrors.kernel.org/gnu/gcc/gcc-3.4.6/gcc-3.4.6.tar.bz2" rel="nofollow noreferrer">ftp://mirrors.kernel.org/gnu/gcc/gcc-3.4.6/gcc-3.4.6.tar.bz2</a></p> <p>2) tar -jxf gcc-3.4.6.tar.bz2</p> <p>3) cd gcc-3.4.6</p> <p>4) cd libstdc++-v3</p> <p>5) ./configure</p> <p>And I get the following error:</p> <p>configure: error: cannot find install-sh or install.sh in ./../..</p> <p>There is actually an "install-sh" file in the gcc-3.4.6 directory, but that's one directory up the current, not two.</p> <p>The configure script should look for install-sh in "./.." insted of "./../.." ??</p> <p>What's wrong??</p>
<ol> <li>wget <a href="ftp://mirrors.kernel.org/gnu/gcc/gcc-3.4.6/gcc-3.4.6.tar.bz2" rel="nofollow noreferrer">ftp://mirrors.kernel.org/gnu/gcc/gcc-3.4.6/gcc-3.4.6.tar.bz2</a></li> <li>tar -jxf gcc-3.4.6.tar.bz2</li> <li>cd gcc-3.4.6</li> <li>./configure</li> <li>make</li> <li>make install</li> </ol>
<p>Why are you cd:ing down into libstdc++-v3? I thought the correct way was to just run "make" from the directory you ran configure from.</p>
26,567
<p>I have 2 objects, both from different Model classes, and want to show a form containing some fields from each one. How can I do this?</p>
<p>The way I do it is by creating two <code>ModelForm</code> classes that use the <code>fields</code> Meta attribute to specify which <a href="http://docs.djangoproject.com/en/dev/topics/forms/modelforms/?from=olddocs#using-a-subset-of-fields-on-the-form" rel="noreferrer">subset of fields</a> to use to display in the form. I display both forms in the template, and handle them in the view. </p>
<p>I've never tried this but you could have two ModelForm classes defined in your code and then make a new plain <code>Form</code> class that in its <code>__init__</code> created a copy of each <code>ModelForm</code> and copied the fields into itself.</p> <p>Something like:</p> <pre><code>class DualForm(forms.Form): def __init__(self, *args, **kwargs): model1 = Model1Form(**kwargs) model2 = Model2Form(**kwargs) for f in model1.fields: self.fields[f] = model1.fields[f] for f in model2.fields: self.fields[f] = model2.fields[f] class Model1Form(forms.ModelForm): ... your model form... class Model2Form(forms.ModelForm): ... your other model form... </code></pre> <p>I can't see why it wouldn't work.</p> <p>Just make sure you pass data arguments through to the <code>ModelForms</code> and trap and bubble exceptions out... I'm also not sure what would happen if you have conflicting field names. That could be troublesome...</p>
47,576
<p>I'm using the <code>mechanize</code> module to execute some web queries from Python. I want my program to be error-resilient and handle all kinds of errors (wrong URLs, 403/404 responsese) gracefully. However, I can't find in mechanize's documentation the errors / exceptions it throws for various errors.</p> <p>I just call it with:</p> <pre><code> self.browser = mechanize.Browser() self.browser.addheaders = [('User-agent', browser_header)] self.browser.open(query_url) self.result_page = self.browser.response().read() </code></pre> <p>How can I know what errors / exceptions can be thrown here and handle them ?</p>
<pre><code>$ perl -0777 -ne'print qq($1) if /__all__ = \[(.*?)\]/s' __init__.py | grep Error 'BrowserStateError', 'ContentTooShortError', 'FormNotFoundError', 'GopherError', 'HTTPDefaultErrorHandler', 'HTTPError', 'HTTPErrorProcessor', 'LinkNotFoundError', 'LoadError', 'ParseError', 'RobotExclusionError', 'URLError', </code></pre> <p>Or:</p> <pre><code>&gt;&gt;&gt; import mechanize &gt;&gt;&gt; filter(lambda s: "Error" in s, dir(mechanize)) ['BrowserStateError', 'ContentTooShortError', 'FormNotFoundError', 'GopherError' , 'HTTPDefaultErrorHandler', 'HTTPError', 'HTTPErrorProcessor', 'LinkNotFoundErr or', 'LoadError', 'ParseError', 'RobotExclusionError', 'URLError'] </code></pre>
<p>I found this in their docs:</p> <blockquote> <p>One final thing to note is that there are some catch-all bare except: statements in the module, which are there to handle unexpected bad input without crashing your program. If this happens, it's a bug in mechanize, so please mail me the warning text.</p> </blockquote> <p>So I guess they don't raise any exceptions. You can also search the source code for Exception subclasses and see how they are used.</p>
18,314
<p>I am interested in making a Google Talk client using Python and would like to use the Twisted libraries Words module. I have looked at the examples, but they don't work with the current implementation of Google Talk.</p> <p>Has anybody had any luck with this? Would you mind documenting a brief tutorial?</p> <p>As a simple task, I'd like to create a client/bot that tracks the Online time of my various Google Talk accounts so that I can get an aggregate number. I figure I could friend the bot in each account and then use the XMPP presence information to keep track of the times that I can then aggregate.</p> <p>Thanks.</p>
<p>wokkel is the future of twisted words. <a href="http://metajack.im/" rel="noreferrer">metajack</a> wrote a really nice <a href="http://metajack.im/2008/09/25/an-xmpp-echo-bot-with-twisted-and-wokkel/" rel="noreferrer">blog post</a> on getting started.</p> <p>If you want a nice, functional sample project to start with, check out my <a href="http://github.com/dustin/whatsup" rel="noreferrer">whatsup</a> bot.</p>
<p>As the Twisted libs seem to be out of date, you have two choices: Implement your own XMPP-handler or look for another library.</p> <p>I would suggest working with the raw XML; XMPP is not that complicated and you are bound to learn something.</p>
28,121
<p>Do the clients need something else than a proper jdk and javafx compliant browser to visit javafx applets?</p>
<p>This will give you a list of all MAC addresses on your computer. It will work with all versions of Windows as well:</p> <pre><code>void getdMacAddresses(std::vector&lt;std::string&gt; &amp;vMacAddresses;) { vMacAddresses.clear(); IP_ADAPTER_INFO AdapterInfo[32]; // Allocate information for up to 32 NICs DWORD dwBufLen = sizeof(AdapterInfo); // Save memory size of buffer DWORD dwStatus = GetAdaptersInfo( // Call GetAdapterInfo AdapterInfo, // [out] buffer to receive data &amp;dwBufLen); // [in] size of receive data buffer //No network card? Other error? if(dwStatus != ERROR_SUCCESS) return; PIP_ADAPTER_INFO pAdapterInfo = AdapterInfo; char szBuffer[512]; while(pAdapterInfo) { if(pAdapterInfo-&gt;Type == MIB_IF_TYPE_ETHERNET) { sprintf_s(szBuffer, sizeof(szBuffer), "%.2x-%.2x-%.2x-%.2x-%.2x-%.2x" , pAdapterInfo-&gt;Address[0] , pAdapterInfo-&gt;Address[1] , pAdapterInfo-&gt;Address[2] , pAdapterInfo-&gt;Address[3] , pAdapterInfo-&gt;Address[4] , pAdapterInfo-&gt;Address[5] ); vMacAddresses.push_back(szBuffer); } pAdapterInfo = pAdapterInfo-&gt;Next; } } </code></pre>
<p>You can use WMI on both XP and Vista, there are a number of examples online. e.g: <a href="http://www.thescarms.com/dotnet/WMI.aspx" rel="nofollow noreferrer">Use Windows Management Instrumentation (WMI) to get a MAC Address</a></p>
27,359
<p>I wrote a program in C with Ubuntu Linux and now I need to port it over to a UNIX machine (or what I believe to be a UNIX box). It compiles fine on my Ubuntu with GCC but when I try to compile it with GCC on the UNIX box, it gives this error:</p> <pre><code>a.c: In function `goUpDir': a.c:44: parse error before `char' a.c:45: `newDir' undeclared (first use in this function) a.c:45: (Each undeclared identifier is reported only once a.c:45: for each function it appears in.) a.c: In function `goIntoDir': a.c:54: parse error before `char' a.c:57: `newDir' undeclared (first use in this function) a.c:57: `oldDir' undeclared (first use in this function) </code></pre> <p>The main problems seem to be the parse error before <code>char</code> (the others are related)</p> <pre><code>44 char newDir[50] = ""; 54 char* oldDir = (char*)get_current_dir_name(); </code></pre> <p>These are just simple C-style strings declarations. Is there a header file that I need to include to get it to work in UNIX?</p> <p>P.S. what is the command to see what version of unix and which version of gcc you are using? Knowing this will allow me to be more specific in my question.</p> <p>Thanks</p>
<p>If you are compiling pure C, variables must be declared on the beggining of the functions. I mention this because most people compile their C programs using C++ compilers, which offers then some resources not normally available to pure C compilers, the most common example being the // comment lines.</p>
<p>What UNIX is it? AIX, Ultrix, Minix, Xenix? </p> <p>GCC has a "--version" flag:</p> <pre><code>gcc --version </code></pre>
18,737
<p>This is the HTML:</p> <pre><code>&lt;div id="testBlue"&gt; &lt;span&gt;hello&lt;/span&gt; &lt;span id="testGreen" class="testGreen"&gt;hello2&lt;/span&gt; &lt;/div&gt; </code></pre> <p>If I have set in CSS:</p> <pre><code>#testBlue span { color:Blue; } .testGreen, #testGreen { color:Green; } </code></pre> <p>How can I override the general style in the second SPAN?</p> <p>I have tried both id and class selectors but it doesnt override it.</p>
<p>In CSS, selectors with higher specificity override selectors that are more general.</p> <p>In your example you defined a style for a <strong>span inside a div with id = "testBlue"</strong>. This selector is <strong>more specific</strong> than the simple selector for the class or id <strong>testGreen</strong>, so it wins. You just need a selector more specific than <strong>#testBlue span</strong>, that is not difficult to find:</p> <pre><code>#testBlue span.testGreen { color: green; } </code></pre>
<p>You could use selector </p> <pre><code>#testBlue * { color:Blue; } </code></pre>
38,208
<p>What happened to OCX's? Are they no longer possible to create with the latest tools?</p> <p>I need to create an ActiveX control that I can place in Word, PowerPoint and Excel documents. If I use VS.NET, I can only create a UserControl DLL with COM Interop, but I don't think I can add that using the "More Controls" toolbox of PowerPoint's Developer Tab.</p> <p>What would you do?</p>
<p>Yes, you can still create them. But you can't create an OCX with a .NET language. Need to be unmanaged C++ (or VB). The DLLs with COM interop you can create in C# or VB.NET are just .NET objects that are invoked via CCW.</p>
<p>Use a C++ or VB compiler which can target native code + ActiveX.</p>
47,490
<p>I want to convert a number that is in <a href="https://en.wikipedia.org/wiki/Netscape_Portable_Runtime#Time" rel="nofollow noreferrer">PRTime</a> format (a 64-bit integer representing the number of microseconds since midnight (00:00:00) 1 January 1970 Coordinated Universal Time (UTC)) to a <code>DateTime</code>.</p> <p>Note that this is slightly different than the usual &quot;number of milliseconds since 1/1/1970&quot;.</p>
<pre><code>Dim prTimeInMillis As UInt64 prTimeInMillis = prTime/1000 Dim prDateTime As New DateTime(1970, 1, 1) prDateTime = prDateTime.AddMilliseconds(prTimeInMillis) </code></pre>
<p>DateTime has a constructor that takes Ticks (which are 100 nanoseconds).</p> <p>So take your prTime, multiply it by 10 and add it to the number of ticks representing the Epoch time and you have your conversion.</p> <pre><code>private static DateTime epoch = new DateTime(1970, 1, 1); private static DateTime ConvertPrTime(long time) { return new DateTime(epoch.Ticks + (time*10), DateTimeKind.Utc); } </code></pre>
8,060
<p>List Comprehension is a very useful code mechanism that is found in several languages, such as Haskell, Python, and Ruby (just to name a few off the top of my head). I'm familiar with the construct.</p> <p>I find myself working on an Open Office Spreadsheet and I need to do something fairly common: I want to count all of the values in a range of cells that fall between a high and low bounds. I instantly thought that list comprehension would do the trick, but I can't find anything analogous in Open Office. There is a function called "COUNTIF", and it something similar, but not quite what I need.</p> <p>Is there a construct in Open Office that could be used for list comprehension?</p>
<p>CountIf can count values equal to one chosen. Unfortunately it seems that there is no good candidate for such function. Alternatively you can use additional column with If to display 1 or 0 if the value fits in range or not accordingly:</p> <pre><code>=If(AND({list_cell}&gt;=MinVal; {list_cell}&lt;=MaxVal); 1; 0) </code></pre> <p>Then only thing left is to sum up this additional column.</p>
<p>Assuming:</p> <ul> <li>your range is A1:A10</li> <li>your lower bound is at B1</li> <li>your upper bound is at B2</li> </ul> <p>then what you want can be achieved by:</p> <pre><code>=COUNTIFS(A1:A10, &quot;&gt;&quot; &amp; B1, A1:A10, &quot;&lt;&quot; &amp; B2) </code></pre> <p>(you might need to change commas into semicolons, depending on your language preference for decimal point)</p> <p>Quoting from the installed OpenOffice documentation:</p> <blockquote> <p>The logical relation between criteria can be defined as logical AND (conjunction). In other words, if and only if all given criteria are met, a value from the corresponding cell of the given Func_Range is taken into calculation.</p> </blockquote> <blockquote> <p>This function is part of the Open Document Format for Office Applications (OpenDocument) standard Version 1.2. (ISO/IEC 26300:2-2015)</p> </blockquote>
21,917
<p>What's the best way to allow a user to browse for a file in C#?</p>
<pre><code>using (OpenFileDialog dlg = new OpenFileDialog()) { dlg.Title = "Select a file"; if (dlg.ShowDialog()== DialogResult.OK) { //do something with dlg.FileName } } </code></pre>
<p>I would say use the standard "Open File" dialog box (<a href="http://msdn.microsoft.com/en-us/library/system.windows.forms.openfiledialog.aspx" rel="nofollow noreferrer">OpenFileDialog</a>), this makes it less intimidating for new users and helps with a consistant UI.</p>
5,088
<p>I'm in javascript, running this in the console </p> <pre><code>d = new Date(); d.setMonth(1); d.setFullYear(2009); d.setDate(15); d.toString(); </code></pre> <p>outputs this:</p> <pre><code>"Sun Mar 15 2009 18:05:46 GMT-0400 (EDT)" </code></pre> <p>Why would this be happening? It seems like a browser bug.</p>
<p>That's because when you initialize a new Date, it comes with today's date, so today is Oct 30 2008, then you set the month to February, so there is no February 30, so set first the day, then the month, and then the year:</p> <pre><code>d = new Date(); d.setDate(15); d.setMonth(1); d.setFullYear(2009); </code></pre> <p>But as <a href="https://stackoverflow.com/questions/251941/the-fifteenth-of-february-isnt-found#251976">@Jason W</a>, says it's better to use the Date constructor:</p> <pre><code>new Date(year, month, date [, hour, minute, second, millisecond ]); </code></pre>
<p>After a bunch of testing in FF3 on XP with Firebug, here are the things I can tell you</p> <ul> <li>Calling Date.setDate() <em>after</em> calling Date.setMonth() will generate this odd behavior.</li> <li>Date.setMonth() forces the timezone to be CST (or, some non DST-aware zone)</li> <li>Date.setDate() forces the timezone to be CDT (or, some DST-aware zone)</li> </ul> <p>So, there's definitely something wonky going on with setMonth() and setDate() in respect to the timezone.</p> <p>The only solution I can offer is this: Set the date before you set the month.</p>
31,390
<p>I'm trying to print large objects (around 1 meter squared) with polycarbonate pellets. The problem is sometimes the print cracks. It is not due to delamination as it is a shear crack across multiple layers. I know the ideal scenario is to have a heated enclosure but I cannot do that due to the size. Any suggestions?</p> <p>I am using a robotic arm (KUKA KR360) with a custom extruder. That is why I can't build the enclosure. As for the temperature, they are 230 to 260 °C. Nozzle is 10 mm.</p> <hr /> <p><em>I like the idea of directed heat. I might try that.</em></p>
<p>Printing polycarbonate requires a high end 3D printer that is suitable for the task.</p> <p>From <a href="https://www.simplify3d.com/support/materials-guide/polycarbonate/" rel="nofollow noreferrer">Simplify3d support</a> we learn that:</p> <blockquote> <p>... requires very high temperatures for printing and will <strong>exhibit layer separation if printed at too low of a temperature or with excessive cooling enabled</strong>. Polycarbonate is frequently <strong>best printed on a machine that has an enclosed build volume</strong> and is capable of handling high bed and extruder temperatures.</p> </blockquote> <p>High temperatures and enclosed build volume are key to print polycarbonate without cracking or delamination.</p> <blockquote> <p>Any suggestions?</p> </blockquote> <p>Note that NASA has successfully printed ULTEM (even higher temperatures needed) <a href="https://ntrs.nasa.gov/citations/20170000214" rel="nofollow noreferrer">using open source hardware</a>. They have used infrared lamps directed at the build plate, this may be an option if a full enclosure is not possible. Also people seem to get good results with draft shields for printing ABS on non enclosed printers. Key is that a constant elevated temperature is created near the print, whether that works for such a large size remains to be seen. Best solution would be enclosing the printer.</p>
<p>Sounds like your problem is cooling, which would be mitigated by an enclosure to eliminate draughts and hold a higher air temperature.</p> <p>I made an enclosure using parts-on-hand and some printed PLA joiners. It doesn't have to be fancy or expensive to work well.</p> <p>Details are at <a href="https://3dprinting.stackexchange.com/a/18406/12956">https://3dprinting.stackexchange.com/a/18406/12956</a></p> <p>Next step is to sew some thermal &quot;curtains&quot; as sides and top. As it is I simply hang some coats around the frame in the short term, and use a Pi camera inside to monitor the progress from remote.</p>
2,057
<p>I have a C# application that's utilizes MYSQL. I'm at a beta release point and need an installation package that includes my application, along with MYSQL. So basically, I need to install MYSQL and perform a restore from within my .NET install package.</p> <p>Any help would be greatly appreciated.</p>
<p>This question is very similar to <a href="https://stackoverflow.com/questions/49378/deploy-mysql-server-db-with-net-application">another question</a>. However, the answers don't really help.</p> <p>You can <a href="http://www.simple-talk.com/dotnet/visual-studio/visual-studio-setup---projects-and-custom-actions/" rel="nofollow noreferrer">run executables from a custom action in the .Net deployment project</a>, that's what I'd recommend. (Look under the heading "Calling an executable as a custom action")</p> <p>Hopefully everything can be taken care of by via the command line. If not, try a scripted installer like Wise or InstallShield, I think they have better support for stuff like this.</p> <p>Hope that helps!</p>
<p>Have a look at using Visual Studio's package and deployment tool. It should automatically bring in the MySQL dependencies if you connect natively (MySQL .NET components) rather than an ODBC connection. In any case it allows you to add other software to an installation program that can be automatically unpacked if you need it. I have used it to deploy C# apps using the MySQL libraries that you download from MySQL website and for CoreLab's MySQL 3rd party libraries.</p>
49,338
<p>Ok where I work we have a fairly substantial number of systems written over the last couple of decades that we maintain. </p> <p>The systems are diverse in that multiple operating systems (Linux, Solaris, Windows), Multiple Databases (Several Versions of oracle, sybase and mysql), and even multiple languages (C, C++, JSP, PHP, and a host of others) are used.</p> <p>Each system is fairly autonomous, even at the cost of entering the same data into multiple systems.</p> <p>Management recently decided that we should investigate what it will take to get all the systems happily talking to each other and sharing data.</p> <p>Keep in mind that while we can make software changes to any of the individual systems, a complete rewrite of any one system (or more) is not something management is likely to entertain.</p> <p>The first thought of several of the developers here was the straight forward: If system A needs data from system B it should just connect to system B's database and get it. Likewise if it needs to give B data it should just insert it into B's database.</p> <p>Due to the mess of databases (and versions) used, other developers were of the opinion that we should have one new database, combining the tables from all the other systems to avoid having to juggle multiple connections. By doing this they hope that we might be able to consolidate some tables and get rid of the redundant data entry.</p> <p>This is about the time I was brought in for my opinion on the whole mess.</p> <p>The whole idea of using the database as a means of system communication smells funny to me. Business logic will have to be placed into multiple systems (if System A wants to add data to System B it better understand B's rules concerning the data before doing the insert), several systems will most likely have to do some form of database polling to find any changes to their data, continuing maintenance will be a headache, as any change to a database schema now propagates several systems.</p> <p>My first thought was to take the time and write APIs/Services for the different systems, which once written could be easily used to pass/retrieve data back and forth. A lot of the other developers feel that is excessive and far more work than just using the database.</p> <p>So what would be the best way to go about getting these systems to talk to each other?</p>
<p>Integrating disparate systems is my day job.</p> <p>If I were you, I would go to great effort to avoid accessing System A's data from directly within System B. <strong>Updating</strong> System A's database from System B is extremely unwise. It is exactly the opposite of good practice to make your business logic so diffuse. You will end up regretting it.</p> <p>The idea of the central database isn't necessarily bad ... but the amount of effort involved is probably within an order of magnitude of rewriting the systems from scratch. It is certainly not something I would attempt, at least in the form you describe. It can succeed, but it is much, much harder and it takes a lot more discipline than the point-to-point integration approach. It's funny to hear it suggested in the same breath as the 'cowboy' approach of just shoving data directly into other systems.</p> <p>Overall your instincts seem pretty good. There are a couple of approaches. You mention one: implementing services. That's not a bad way to go, especially if you need updates in real time. The other is a separate integration application that is responsible for shuffling the data around. That's the approach I usually take, but usually because I can't change the systems I'm integrating to ask for the data it needs; I have to push the data in. In your case the services approach isn't a bad one.</p> <p>One thing I would like to say that might not be obvious to someone coming to system integration for the first time is that every piece of data in your system should have a single, authoritative point of truth. If the data is duplicated (and it is duplicated), and the copies disagree with each other, the copy in the point of truth for that data must be taken to be correct. There is just no other way to integrate systems without having the complexity scream skyward at an exponential rate. Spaghetti integration is like spaghetti code, and it should be avoided at all costs.</p> <p>Good luck.</p> <p>EDIT:</p> <p>Middleware addresses the problem of transport, but that is not the central problem in integration. If the systems are close enough together that one app can shove data directly in to another, they're probably close enough that a service offered by one can be called directly by another. I wouldn't recommend middleware in your case. You might get some benefit from it, but that would be outweighed by the increased complexity. You need to solve one problem at a time.</p>
<p>It seems you are looking for opinions, so I will provide mine.</p> <p>I agree with the other developers that writing an API for all the different systems is excessive. You would likely get it done faster and have much more control over it if you just take the other suggestion of creating a single database.</p>
16,203
<p>I have a .bat and inside the .bat i would like to execute a special code if there's some modification inside the svn repository (for example, compile).</p>
<p>For Win 2000 and later, this would assign the last output row from the svn status commmand to the svnOut variable and then test if the variable contains anything:</p> <pre><code>@echo off set svnOut= set svnDir=C:Your\path\to\svn\dir\to\check for /F "tokens=*" %%I in ('svn status %svnDir%') do set svnOut=%%I if "%svnOut%"=="" ( echo No changes ) else ( echo Changed files! ) </code></pre> <p>Why there is a line like this</p> <pre><code>set svnOut= </code></pre> <p>you have to figure out yourself. ;-)</p>
<p>This version is based on @tooony's but checks the server for updates instead of the client.</p> <pre><code>@echo off set svnOut= rem Check svn server status of current working directory repository and see if first or second token is an * for /F "tokens=1" %%I in ('svn status --show-updates') do if "%%I"=="*" set svnOut=%%I rem echo "%svnOut%" if "%svnOut%"=="" ( echo No changes ) else ( echo Changed files! ) </code></pre>
20,109
<p>I have a this aspx-code: (sample)</p> <pre><code>&lt;asp:DropDownList runat="server" ID="ddList1"&gt;&lt;/asp:DropDownList&gt; </code></pre> <p>With this codebehind:</p> <pre><code>List&lt;System.Web.UI.WebControls.ListItem&gt; colors = new List&lt;System.Web.UI.WebControls.ListItem&gt;(); colors.Add(new ListItem("Select Value", "0")); colors.Add(new ListItem("Red", "1")); colors.Add(new ListItem("Green", "2")); colors.Add(new ListItem("Blue", "3")); ddList1.DataSource = colors; ddList1.DataBind(); </code></pre> <p>The output looks like this:</p> <pre><code>&lt;select name="ddList1" id="ddList1"&gt; &lt;option value="Select Value"&gt;Select Value&lt;/option&gt; &lt;option value="Red"&gt;Red&lt;/option&gt; &lt;option value="Green"&gt;Green&lt;/option&gt; &lt;option value="Blue"&gt;Blue&lt;/option&gt; &lt;/select&gt; </code></pre> <p>My question is: Why did my values (numbers) disappear and the text used as the value AND the text? I know that it works if I use the <code>ddList1.Items.Add(New ListItem("text", "value"))</code> method, but I need to use a generic list as the datasource for other reasons.</p>
<p>Because DataBind method binds values only if DataValueField property is set. If you set DataValueField property to "Value" before calling DataBind, your values will appear on the markup.</p> <p>UPDATE: You will also need to set DataTextField property to "Text". It is because data binding and adding items manually do not work in the same way. Databinding does not know the existence of type ListItem and generates markup by evaluating the items in the data source.</p>
<p>"If you are building ListItems, you have no need to use DataBind() in the first place."</p> <p>Adding directly to the dropdownlist is the easy way (and given the example code the right one) but lets say you have an unordered datasource and you want the list items sorted.</p> <p>One way of achieving this would be to create a generic list of ListItem and then use the inherited sort method before databinding to the list.</p> <p>There are many wys to skin a cat...</p>
16,081
<p>How to create a WCF application without using the svcutil.exe tool?</p>
<p>What version of Visual Studio are you using?</p> <p>VS2008 incorporates the functionality of the svcutil tool. To generate the proxy, click on the Solution Explorer and select 'Add Service Reference', you can then enter the URL of the server, give the namespace a name and off you go.</p> <p>You may want to expand your question to provide some more details of what you are wanting to achieve.</p>
<p>The svcutil.exe tool (and the equivalent functionality in VS2008) are normally used like this: -</p> <p>You point it at a service description (a WSDL document) and it generates client-side code and config to help you make a client that can communicate with the services described in the WSDL. The tools can do other things as well, but this is what they're most often used for. I assume it's this use of svcutil.exe that you're referring to.</p> <p>So if you have an existing service, maybe written using some other stack (not WCF), using svcutil makes your life easier than it would otherwise be. But remember, the code and config generated could have been written by you. Normally the config looks verbose because the tool puts all the defaults in there. If you wrote the config yourself you could probably omit most of it.</p> <p>If you are writing client and service yourself, using WCF, there is almost no reason why you'd use svcutil.exe. When you define your [ServiceContract] you can use that same definition in both client and service. When you create your service config file it's a simple job to create a client config file based on it - most of the content is the same.</p> <p>In the end, there's no substitute for understanding what all the code/config generated by svcutil.exe actually means. Then you'll be in a position to work without it.</p>
38,706
<p>Is anyone successfully using the latest 64-bit Ganymede release of Eclipse on Windows XP or Vista 64-bit?</p> <p>Currently I run the normal Eclipse 3.4 distribution on a 32bit JDK and launch &amp; compile my apps with a 64bit JDK. Our previous experience has been that the 64bit Eclipse distro is unstable for us, so I'm curious if anyone is using it successfully.</p> <p>We are using JDK 1.6.0_05.</p>
<p>I'm using Eclipse with a 64bit VM. However I have to use Java 1.5, because with Java 1.6, even 1.6.0_10ea, Eclipse crashed when changing the .classpath-file. On Linux I had the same problems and could only get the 64bit Eclipse to work with 64bit Java 1.5.</p> <p>The problem seems to be with the just in time compilation, since with vmparam -Xint eclipse works -- but this is not a sollution, because it's slow then.</p> <p><strong>Edit:</strong></p> <p>With 1.6.0_11 it seems to work. </p> <p>1.6_10 final might work as well as mentioned in the comment, but I've not tested that.</p>
<p>I've been successfully using it on Vista x64 for some light Java work. Nothing too involved and no extra plugins, but basic Java coding has been working without any issues. I'm using the 3.4M7 build but it looks like the <a href="http://download.eclipse.org/eclipse/downloads/drops/R-3.4-200806172000/index.php" rel="nofollow noreferrer">3.4 stable build</a> supports Vista x64 now.</p>
2,804
<p>I need to be able to GZip compress a file in an Excel VBA function. Specifically I need to be able to use the 'deflate' algorithm.</p> <p>Is there a way to do this without having to exec a command line application? With no dependency on external tools the code will be more robust.</p> <p>Ideally the code would make use of pre-installed VBA or COM library functions - I don't want to have to implement this logic myself or install DLLs etc.</p> <p>If possible, I want installation of the function to be as simple as adding a .xla to the available Excel Add-Ins. No DLLs, EXEs, registry entries etc. required.</p> <p><strong>Edit</strong> Can I make use of the .NET GZipStream to do this?</p>
<p>VBA (which is really a dialect of VB6) is slow for these kind of applications. I remember I once implemented Shannon-Fano algorithm on VB6 and on C, the C version was about 10 times faster, even after being turned into a DLLMain and called from there rather than on a command-line executable.</p> <p>There are lots of COM DLLs that provide compression services, both open source and shareware, and some of them implement GZIP's deflate algorithm. It'd be really simple to just call one function from such a DLL from your VBA code to do the compression on your behalf.</p> <p>I understand your being reluctant on using something external to your application, though in this case you might have to apply an exception for performance's sake.</p> <p>In an effort to completely spoil your fun, examine file ZIPFLDR.DLL on windows\system32. you may also like to take a look at these links:</p> <ul> <li>This has an example of how to do what you want (zipping using windows built-in ZIP capabilities) from VB.NET, it shouldn't be much different from VBA or VB6: <a href="http://www.autohotkey.com/forum/topic15135.html" rel="nofollow noreferrer">Transparent ZIP with DLL call</a></li> <li>This one has a sample application on VB6 using windows built-in capabilities to zip (in ZIP rather than GZIP format, of course): <a href="http://www.mvps.org/emorcillo/en/code/vb6/index.shtml" rel="nofollow noreferrer">Using Windows XP &quot;Compressed Folder&quot; shell extension to work with .zip files</a></li> </ul> <p>Found both thru googling, you should be able to find more/better examples.</p>
<p>If you want to implement the algorithm in VBA, you would need to (in VBA) save the spreadsheet and then use VB's I/O functions to open the file, deflate it, and save it again. For all intents and purposes it's identical to writing an ordinary VB application that works on a file. You might need to put the VBA macro in a separate workbook to avoid "file in use" types of errors, but if you reopen the file as read-only and save it with a different filename you should be OK keeping everything in one workbook.</p> <p>But I'm almost certain that shelling out to gzip from within the VBA would be functionally identical and infinitely easier.</p> <p><strong>EDIT:</strong> Some code. It didn't fail when I ran it, so it's OK to keep everything in the same workbook.</p> <pre><code>Sub main() ActiveWorkbook.Save Open "macrotest.xls" For Binary Access Read As #1 Open "newfile.zip" For Binary Access Write As #2 'do your stuff here Close #2 Close #1 End Sub </code></pre>
20,278
<p>Say I have an ASMX web service, MyService. The service has a method, MyMethod. I could execute MyMethod on the server side as follows:</p> <pre><code>MyService service = new MyService(); service.MyMethod(); </code></pre> <p>I need to do similar, with service and method not known until runtime. </p> <p>I'm assuming that reflection is the way to go about that. Unfortunately, I'm having a hard time making it work. When I execute this code:</p> <pre><code>Type.GetType("MyService", true); </code></pre> <p>It throws this error:</p> <blockquote> <p>Could not load type 'MyService' from assembly 'App_Web__ktsp_r0, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'.</p> </blockquote> <p>Any guidance would be appreciated.</p>
<p>I'm not sure if this would be the best way to go about it. The most obvious way to me, would be to make an HTTP Request, and call the webservice using an actual HTTP GET or POST. Using your method, I'm not entirely sure how you'd set up the data you are sending to the web service. I've added some sample code in VB.Net</p> <pre><code>Dim HTTPRequest As HttpWebRequest Dim HTTPResponse As HttpWebResponse Dim ResponseReader As StreamReader Dim URL AS String Dim ResponseText As String URL = "http://www.example.com/MyWebSerivce/MyMethod?arg1=A&amp;arg2=B" HTTPRequest = HttpWebRequest.Create(URL) HTTPRequest.Method = "GET" HTTPResponse = HTTPRequest.GetResponse() ResponseReader = New StreamReader(HTTPResponse.GetResponseStream()) ResponseText = ResponseReader.ReadToEnd() </code></pre>
<p>@Kibbee: I need to avoid the HTTP performance hit. It won't be a remote call, so all of that added overhead <em>should</em> be unnecessary.</p> <p>@Daren: I definitely agree with that design philosophy. The issue here is that I'm not going to be in control of the service or its underlying business logic.</p> <p>This is for <a href="http://codeplex.com/UsernameAvailability" rel="nofollow noreferrer">a server control</a> that will need to execute against an arbitrary service/method, orthogonally to how the web service itself is implemented.</p>
8,775
<p>On top of my head, especially for C/Linux developer:</p> <ul> <li><a href="http://petdance.com/ack/" rel="nofollow noreferrer">ack</a></li> <li><a href="http://git.fishsoup.net/cgit/git-bz/plain/git-bz" rel="nofollow noreferrer">git-bz</a></li> <li><a href="http://schlueters.de/colorgcc.html" rel="nofollow noreferrer">colorgcc</a></li> <li><a href="http://colordiff.sourceforge.net/" rel="nofollow noreferrer">colordiff</a></li> <li><a href="https://thomas.apestaart.org/moap/trac" rel="nofollow noreferrer">moap</a> and <a href="http://svn.gnome.org/svn/releng/trunk/tools/prepare-ChangeLog.pl" rel="nofollow noreferrer">prepare-ChangeLog</a></li> </ul> <p>Is there some tool/script you couldn't work without, but that you feel others don't know so much?</p> <p>For instance, I just found:</p> <ul> <li><a href="http://cppcheck.wiki.sourceforge.net/" rel="nofollow noreferrer">cppcheck</a></li> </ul>
<p>I don't use it that often, but the <strong>tool with the highest ratio of awesomeness to being little known</strong> has to be <a href="http://www.graphviz.org/pdf/dotguide.pdf" rel="nofollow noreferrer">dot</a>, which is the tool for drawing directed graphs that is part of the <a href="http://www.graphviz.org" rel="nofollow noreferrer">AT&amp;T Graph Visualization</a> suite. A nice example output is their <a href="http://www.graphviz.org/Gallery/directed/unix.html" rel="nofollow noreferrer">Unix family tree</a>.</p>
<pre><code>- ANT - Mylyn - TortoiseSVN - firebug (think console too!) - TextMate </code></pre>
49,323
<p>I want to convert an XML document containing many elements within a node (around 150) into another XML document with a slightly different schema but mostly with the same element names. Now do I have to manually map each element/node between the 2 documents. For that I will have to hardcode 150 lines of mapping and element names. Something like this: </p> <pre><code>XElement newOrder = new XElement("Order"); newOrder.Add(new XElement("OrderId", (string)oldOrder.Element("OrderId")), newOrder.Add(new XElement("OrderName", (string)oldOrder.Element("OrderName")), ............... ............... ...............and so on </code></pre> <p>The newOrder document may contain additional nodes which will be set to null if nothing is found for them in the oldOrder. So do I have any other choice than to hardcode 150 element names like orderId, orderName and so on... Or is there some better more maintainable way?</p>
<p>Use an <a href="http://www.w3schools.com/xsl/xsl_transformation.asp" rel="noreferrer">XSLT transform</a> instead. You can use the built-in .NET <a href="http://msdn.microsoft.com/en-us/library/system.xml.xsl.xslcompiledtransform.aspx" rel="noreferrer">XslCompiledTransform</a> to do the transformation. Saves you from having to type out stacks of code. If you don't already know XSL/XSLT, then learning it is something that'll bank you CV :)</p> <p>Good luck!</p>
<p>Use an XSLT transformation to translate your old xml document into the new format. </p>
29,632
<p>Using C#, when a user types a text in a normal textbox, how can you see the Hebrew equivalent of that text?</p> <p>I want to use this feature on a data entry form, when the secretary puts in the customer name using English characters to have it converted automatically in another textbox to the hebrew representation.</p> <p>Maybe something with CultureInfo("he-IL")...</p>
<p>I didn't even know there was such a thing as <a href="http://en.wikipedia.org/wiki/Hebraization_of_English" rel="nofollow noreferrer">Hebraization</a> &mdash; thanks for asking this question :-)</p> <p>This functionality is not provided by the .NET Framework, so I'm afraid you'd have to build it yourself. You'd have to know how the English is pronounced to provide the correct Hebrew transliteration &mdash; not an easy task, I think.</p>
<p>You would be able to solve this problem using the IPA (International Phonetic Alphabet) in the middle. So, for example you can get the IPA from an english name through an API translator and then making an IPA to hebrew translation through this table: <a href="https://en.wikipedia.org/wiki/Help:IPA/Hebrew" rel="nofollow noreferrer">https://en.wikipedia.org/wiki/Help:IPA/Hebrew</a></p>
44,280
<p>At work we have two competing theories for salts. The products I work on use something like a user name or phone number to salt the hash. Essentially something that is different for each user but is readily available to us. The other product randomly generates a salt for each user and changes each time the user changes the password. The salt is then encrypted in the database.</p> <p>My question is if the second approach is really necessary? I can understand from a purely theoretical perspective that it is more secure than the first approach, but what about from a practicality point of view. Right now to authenticate a user, the salt must be unencrypted and applied to the login information. </p> <p>After thinking about it, I just don't see a real security gain from this approach. Changing the salt from account to account, still makes it extremely difficult for someone to attempt to brute force the hashing algorithm even if the attacker was aware of how to quickly determine what it was for each account. This is going on the assumption that the passwords are sufficiently strong. (Obviously finding the correct hash for a set of passwords where they are all two digits is significantly easier than finding the correct hash of passwords which are 8 digits). Am I incorrect in my logic, or is there something that I am missing?</p> <p><strong>EDIT:</strong> Okay so here's the reason why I think it's really moot to encrypt the salt. (lemme know if I'm on the right track). </p> <p>For the following explanation, we'll assume that the passwords are always 8 characters and the salt is 5 and all passwords are comprised of lowercase letters (it just makes the math easier).</p> <p>Having a different salt for each entry means that I can't use the same rainbow table (actually technically I could if I had one of sufficient size, but let's ignore that for the moment). This is the real key to the salt from what I understand, because to crack every account I have to reinvent the wheel so to speak for each one. Now if I know how to apply the correct salt to a password to generate the hash, I'd do it because a salt really just extends the length/complexity of the hashed phrase. So I would be cutting the number of possible combinations I would need to generate to "know" I have the password + salt from 13^26 to 8^26 because I know what the salt is. Now that makes it easier, but still really hard. </p> <p>So onto encrypting the salt. If I know the salt is encrypted, I wouldn't try and decrypt (assuming I know it has a sufficient level of encryption) it first. I would ignore it. Instead of trying to figure out how to decrypt it, going back to the previous example I would just generate a larger rainbow table containing all keys for the 13^26. Not knowing the salt would definitely slow me down, but I don't think it would add the monumental task of trying to crack the salt encryption first. That's why I don't think it's worth it. Thoughts?</p> <p>Here is a link describing how long passwords will hold up under a brute force attack: <a href="http://www.lockdown.co.uk/?pg=combi" rel="noreferrer">http://www.lockdown.co.uk/?pg=combi</a></p>
<p>The answer here is to ask yourself what you're really trying to protect from? If someone has access to your database, then they have access to the encrypted salts, and they probably have access to your code as well. With all that could they decrypt the encrypted salts? If so then the encryption is pretty much useless anyway. The salt really is there to make it so it isn't possible to form a rainbow table to crack your entire password database in one go if it gets broken into. From that point of view, so long as each salt is unique there is no difference, a brute force attack would be required with your salts or the encrypted salts for each password individually.</p>
<p>Really, it depends on from what type of attack you're trying to protect your data.</p> <p>The purpose of a unique salt for each password is to prevent a dictionary attack against the entire password database.</p> <p>Encrypting the unique salt for each password would make it more difficult to crack an individual password, yes, but you must weigh whether there's really much of a benefit. If the attacker, by brute force, finds that this string:</p> <pre><code>Marianne2ae85fb5d </code></pre> <p>hashes to a hash stored in the DB, is it really that hard to figure out what which part is the pass and which part is the salt?</p>
26,229
<p>Two table:</p> <pre><code>StoreInfo: UserId uniqueidentifier StoreNo nvarchar UserName nvarchar Password nvarchar UserInfo: UserId uniqueidentifier UserName nvarchar Password nvarchar </code></pre> <p>the UserId on StoreInfo is currently null. How do i update StoreInfo's UserId with UserInfo's UserId based on StoreInfo's UserName and Password is match to the UserName and Password from UserInfo. </p> <p>the following is the query that i wrote which update the entire UserId in StoreInfo with the first UserId from UserInfo so i know it's wrong.</p> <pre><code>declare @UserName nvarchar(255) declare @Password nvarchar(25) declare @UserId uniqueidentifier select @UserName = UserName, @Password = Password, @UserId = UserId from UserInfo select UserId, Password from FranchiseInfo where UserID = @UserName and Password = @Password update FranchiseInfo set UserI = @UserId </code></pre>
<p>The update would look like this</p> <pre><code>update storeinfo set userid = u.userid from userinfo u inner join storeinfo s on (s.username = u.username and s.password = u.password) where userid is null </code></pre>
<pre><code>UPDATE StoreInfo set UserId = ui.UserId from StoreInfo si inner join UserInfo ui on ui.UserName = si.UserName and ui.Password = si.Password where si.UserId is null </code></pre> <p>This will update all rows in the table where UserId is not set. Build out the where clause if you only want to update selected rows. (I haven't tested this, so watch for typos!)</p>
30,851
<p>We could also include IFrames as well.</p>
<p>With standard frames/frameset:</p> <ol> <li>Bookmarking can be difficult to accomplish.</li> <li>The Back button can be broken.</li> <li>Arrival from search engines could be into an inner frame.</li> <li>Printing won't work the same across browsers.</li> <li>Scrollbars could be in non-standard/unexpected places.</li> </ol> <p><a href="http://en.wikipedia.org/wiki/Framing_(World_Wide_Web)#Criticism" rel="nofollow noreferrer">More here.</a></p>
<p>I'd like to rephrase your question: what are the advantages of using Html frames for templating? A detailed read about the subject:</p> <p><a href="http://www.yourhtmlsource.com/frames/goodorbad.html" rel="nofollow noreferrer">http://www.yourhtmlsource.com/frames/goodorbad.html</a></p> <blockquote> <p><strong>Quote from that article:</strong></p> <p>So, in conclusion, frames violate too many accepted web standards to be a worthy information delivery system. A well-designed navigation structure using tables or layers is infinitely preferable.</p> <p>Too many people use frames as a way to change their navigation bars by only modifying one page. This is much better accomplished through includes.</p> <p>A well-designed framed page can still be produced, but it happens so rarely that I would advise all coders to stay away from the thought. Tests have also shown that users do not like framed navigation. It might seem sexy to the coder, but if the users don't like it then you're doing a bad job. Frames confuse and irritate people. Avoid them.</p> </blockquote>
19,121
<p>I wanted to grep for java process and then find the max heap memory used. I tried this</p> <pre><code>def ex =['sh','-c','ps -aef | grep Xmx'] String str = ex.execute().text </code></pre> <p>while <code>str</code> has something like <em>java -Xmx1024M /kv/classes/bebo/ -Xms512M</em> How do I extract the value <em>1024M</em>? I was planning to user java regex but thought someone might know a cool way in groovy.</p>
<p>Here's a groovy version that doesn't need the grep (or the sed :) :</p> <pre><code>("ps -aef".execute().text =~ /.*-Xmx([0-9]+M).*/).each { full, match -&gt; println match } </code></pre>
<p>In Java:</p> <pre><code>String ResultString = null; Pattern regex = Pattern.compile("-Xmx(\\d+M)"); Matcher regexMatcher = regex.matcher(str); if (regexMatcher.find()) { ResultString = regexMatcher.group(1); } </code></pre>
37,268