instruction
stringlengths 21
27.8k
| chosen
stringlengths 18
28.2k
| rejected
stringlengths 18
33.6k
| __index_level_0__
int64 0
50k
|
|---|---|---|---|
<p>What are the essential vim commands? What does a new-user need to know to keep themselves from getting into trouble? One command per comment, please.</p>
|
<p>What I find irreplaceable (because it works in vi also, unlike vim's visual mode) are marks. You can mark various spots with <code>m</code> (lower case) and then a letter of your choice (eg x). Then you go elsewhere, and can go back with ``x<code>(backquote letter) to the exact spot, or with</code>'x` (apostrophe letter) to go to the line.</p>
<p>These movements can be used as arguments to commands (yank, delete, etc). For example, you want to delete 10 lines; instead of counting and then moving to the topmost line and entering <code>10dd</code>, you go to either the start or the end of the block, press <code>mm</code> (mark m), then go to the other end of the block, and press <code>d'm</code> (delete apostrophe m). If you use backquote instead of apostrophe in this example, then the deletion will work character-wise, not line-wise. Try marking in the middle of the line with "mark m", moving to the middle of another line, then entering "d backquote m" and you will see what I mean.</p>
|
<p>One of my favourite commands is %G which takes to directly to the end of a file. Especially useful in log-files.</p>
| 9,527
|
<p>I've got a lot of mysql data that I need to generate reports from. It's mostly historic data so it won't be changing much, but it weighs in at 20-30 gigabytes easily and is expected to grow. I currently have a collection of php scripts that will do some complex queries and output csv and excel files. I also use phpMyAdmin with bookmarked queries. I manually edit them to change the parameters. The amount of data is growing and the number of people who need access to it is also growing, so I'm making the time to improve this situation.</p>
<p>I started reading about data warehousing the other day and it seems that this an area that relates to what I need to do. I've read <a href="http://philip.greenspun.com/wtr/data-warehousing.html" rel="nofollow noreferrer">some</a> <a href="http://www.meansandends.com/mysql-data-warehouse/?link_body/body=%7Bincl:Aggregation%7D" rel="nofollow noreferrer">good</a> <a href="http://en.wikipedia.org/wiki/Data_warehouse" rel="nofollow noreferrer">articles</a> and am even waiting on a book. I think I'm getting a handle on what these sorts of systems do and what's possible.</p>
<p>Creating a reporting system for my data has always been on a todo list, but until recently I figured it would be a highly niche programing venture. Since I now know data warehousing is a common thing, I figure there must be some sort of reporting/warehousing frames available to ease in the development. I'd gladly skip writing interfaces and scripts to schedule and email reports and the like and stick to writing queries and setting up relations.</p>
<p>I've mostly been a lamp guy, but I'm not above switching languages or platforms. I just need a more robust solution as my one off scripts don't scale well.</p>
<p>So where's a good place to get started?</p>
|
<p>I'll discuss a few points on the {budget, business utility function, time frame} spectrum out there. For convenience, let's follow the architecture conceptualization you linked to at</p>
<p> <a href="http://en.wikipedia.org/wiki/Data_warehouse#Data_warehouse_architecture" rel="noreferrer" title="WikipediaDataWarehouseArticle">WikipediaDataWarehouseArticle</a></p>
<ul>
<li><p>Operational database layer
<br/>The source data for the data warehouse - Normalized for In One Place Only data maintenance</p></li>
<li><p>Data access layer
<br/>The transformation of your source data into your informational access layer.<br/> ETL tools to extract, transform, load data into the warehouse fall into this layer. </p></li>
<li><p>Informational access layer
<br/> • Report-facilitating Data Structure
<br/> <i>Data is not maintained here. It is merely a reflection of your source data</i>
<br/> Hence, denormalized structures (containing duplicate, but systematically derived data)
<br/> are usually most effective here
<br/> • Reporting tools
<br/> How do you actually allow your users access to the data
<br/> • pre-canned reports (simple)
<br/> • more dynamic slice-and-dice access methods</p></li>
</ul>
<p> The data accessed for reporting and analyzing and the tools for reporting and analyzing data
<br/> fall into this layer. And the Inmon-Kimball differences about design methodology,
<br/> discussed later in the Wikipedia article, have to do with this layer. </p>
<ul>
<li>Metadata layer (facilitates automation, organization, etc) </li>
</ul>
<p><b>Roll your own (low-end)</b>
<br/> For very little out-of-pocket cost, just recognizing the need for the denormalized structures can buy those that are not using it some efficiencies</p>
<p><b>Get in the ballgame</b> (some outlays required)
<br/>You don't need to use all the functionality of a platform right off the bat.
<br/>IMO, however, you want to be on a platform that you know will grow, and in the highly competitive and consolidating BI environment, that seems to be one of the four enterprise mega-vendors (my opinion)</p>
<ul>
<li>Microsoft (the platform of our 110 employee firm)</li>
<li>SAP</li>
<li>Oracle</li>
<li>IBM</li>
</ul>
<p> <a href="http://searchdatamanagement.techtarget.com/news/article/0,289142,sid91_gci1298642,00.html" rel="noreferrer" title="BiMarketStateArticle">BiMarketStateArticle</a></p>
<p>My firm is at this stage, using some of the ETL capability offered by SQL Server Integration Services (SSIS) and some alternate usage of the open source, but in practice license requiring Talend product in the "Data Access Layer", a denormalized reporting structure (implemented completely in the basic SQL Server database), and SQL Server Reporting Services (SSRS) to largely automate (based on your skill) the production of pre-specified reports. Note that an SSRS "report" is merely a (scalable) XML configuration/specification that gets rendered at runtime via the SSRS engine. Choices such as export to an excel file are simple options.</p>
<p><b>Serious Commitment</b> (some significant human commitment required)
<br/>Notice above that we have yet to utilize the data mining/dynamic slicing/dicing
capabilities of SQL Server Analysis Services. We are working toward that,
but now focused on improving the quality of our data cleansing in the "Data Access Layer".</p>
<p>I hope this helps you to get a sense of where to start looking.</p>
|
<p>Kimball is the simpler method for data warehousing.</p>
<p>We use Informatica for moving data around, but it doesn't do DW things like indexing by default.<br>
I like the idea of Wherescape RED, as a DW tool and using MS SQL's Linked Servers to obviate the need for an ETL tool.</p>
| 19,206
|
<p>This may seem like a stupid question, so here goes:</p>
<p>Other than parsing the string of FileInfo.FullPath for the drive letter to then use DriveInfo("c") etc to see if there is enough space to write this file. Is there a way to get the drive letter from FileInfo?</p>
|
<pre><code>FileInfo f = new FileInfo(path);
string drive = Path.GetPathRoot(f.FullName);
</code></pre>
<p>This will return "C:\". That's really the only other way.</p>
|
<p>Nothing wrong with a little string parsing :-)</p>
<pre><code>FullPath.Substring(0,1);
</code></pre>
| 48,367
|
<p>Could someone explain to me in simple terms the easiest way to change the indentation behavior of Vim based on the file type? For instance, if I open a Python file it should indent with 2 spaces, but if I open a Powershell script it should use 4 spaces.</p>
|
<p>You can add <code>.vim</code> files to be executed whenever vim switches to a particular filetype.</p>
<p>For example, I have a file <code>~/.vim/after/ftplugin/html.vim</code> with this contents:</p>
<pre><code>setlocal shiftwidth=2
setlocal tabstop=2
</code></pre>
<p>Which causes vim to use tabs with a width of 2 characters for indenting (the <code>noexpandtab</code> option is set globally elsewhere in my configuration).</p>
<p>This is described here: <a href="http://vimdoc.sourceforge.net/htmldoc/usr_05.html#05.4" rel="noreferrer">http://vimdoc.sourceforge.net/htmldoc/usr_05.html#05.4</a>, scroll down to the section on filetype plugins.</p>
|
<p>I use a utility that I wrote in C called <a href="http://www.kylheku.com/cgit/c-snippets/tree/autotab.c" rel="nofollow"><code>autotab</code></a>. It analyzes the first few thousand lines of a file which you load and determines values for the Vim parameters <code>shiftwidth</code>, <code>tabstop</code> and <code>expandtab</code>.</p>
<p>This is compiled using, for instance, <code>gcc -O autotab.c -o autotab</code>. Instructions for integrating with Vim are in the comment header at the top.</p>
<p>Autotab is fairly clever, but can get confused from time to time, in particular by that have been inconsistently maintained using different indentation styles.</p>
<p>If a file evidently uses tabs, or a combination of tabs and spaces, for indentation, Autotab will figure out what tab size is being used by considering factors like alignment of internal elements across successive lines, such as comments. </p>
<p>It works for a variety of programming languages, and is forgiving for "out of band" elements which do not obey indentation increments, such as C preprocessing directives, C statement labels, not to mention the obvious blank lines.</p>
| 19,232
|
<p>Here's what I'd like to do: </p>
<p>I want to create a library project that contains my Resource files (ie, UI Labels and whatnot). I'd like to then use the resource library both in my UI and in my Tests. (Ie, basically have a common place for my resources that I reference from multiple projects.)</p>
<p>Unfortunately, because the StronglyTypedResourceBuilder (the .Net class which generates the code for Resources) makes resource files internal by default, I can't reference my strongly typed resources in the library from another project (ie, my UI or tests), without jumping through hoops (ie, something similar to what is described <a href="http://www.codeproject.com/KB/dotnet/Localization.aspx" rel="noreferrer">here</a>, or writing a public wrapper class/function).</p>
<p>Unfortunately, both those solutions remove my ability to keep the references strongly-typed.</p>
<p>Has anyone found a straight-forward way to create strongly typed .Net resources that can be referenced from multiple projects?</p>
<p>I'd prefer to avoid having to use a build event in order to accomplish this (ie, to do something like replace all instances of 'internal' with 'public', but that's basically my fall-back plan if I can't find an answer..</p>
|
<p>Not sure which version of Visual Studio you are using, so I will put steps for either one:</p>
<p>VS 2008 - When you open the resx file in design view, there is an option at the top beside Add Resource and Remove Resource, called Access Modifier, it is a drop down where you can change the generated code from internal to public.</p>
<p>VS 2005 - You don't have the option to generate the code like in VS 2008. It was a feature that was added, because of this headache. There are work around's though. You could use a third party generator like this <a href="http://altinoren.com/CommentView,guid,5b69e6d6-86b0-4717-889a-94db78ff04b2.aspx" rel="noreferrer">tool</a> or you could use the <a href="http://msdn.microsoft.com/en-us/library/system.runtime.compilerservices.internalsvisibletoattribute.aspx" rel="noreferrer">InternalsVisibleTo</a> attribute in your AssemblyInfo.cs to add the projects that will have access to the internal classes of your resource library.</p>
|
<p>From the dataset designer and with the properties window visible, there is a "Modifier" property. For your datasets, it is likely saying internal.</p>
<p>I don't know if there is a setting to default all new datasets to public.</p>
| 17,029
|
<p>I have a Monoprice Maker Select v2. It is the kind where the moving plate (heat bed) provides the Y-axis and the moving extruder provides the X-axis. It has a fairly rigid sheet metal frame. In addition, I added steel rods has Z-braces.</p>
<p>I see some pretty obvious ghosting. This happens for an inch or so right after every sharp turn. Clearly, vibration is to be blamed. I found two simple techniques that improves the situation:</p>
<ol>
<li>soft floor mats under the feet (allowing the machine to move freely)</li>
<li>bolt the machine to the desk (preventing the machine from moving)</li>
</ol>
<p>Surprisingly, these two opposites provided exact same level of improvement for ghosting. My question is: <em>which approach is better</em>? Moreover, to further improvement, should I use...</p>
<ul>
<li>(extreme version of 1) hanging the printer from the ceiling using bungee cords (maximize the freedom to move); or...</li>
<li>(extreme version of 2) bolt the printer to garage floor (0 freedom to move) ?</li>
</ul>
|
<p>Ghosting is caused by differential movement between the bed and the head when the head undergoes acceleration. The forces add energy to a resonance in that differential vibration mode.</p>
<p>By changing how you mount the base, you will change the mode and probably change the frequency. </p>
<p>With the soft mounting, the bed can move more easily. It will tend to follow the head acceleration better. The whole system will still ring (you can't get rid of the momentum change), but you can cause the energy to go somewhere else and not excite that mode.</p>
<p>With the base bolted down tight, the base gets stiffer, increasing resonant frequencies. You also may be making the base more resistant against racking or twisting motions. </p>
<p>It is completely credible that both interventions reduce the problem. Of the two, I would prefer any intervention that increases the stiffness.</p>
<p>If you know your movement speed (perhaps from your configuration file) and can measure the linear frequency of the ringing, you can determine the resonant frequency that is being excited. Depending on the frequency, you may be able to excite that frequency with an audio generator and transducer (maybe even just a speaker), such as with one of these: <a href="https://www.parts-express.com/dayton-audio-tt25-8-puck-tactile-transducer-mini-bass-shaker-8-ohm--300-386" rel="noreferrer">Dayton Audio Transducers</a>.</p>
<p>With the system shaking at the right frequency, you can use your finger to find portions of the frame which are vibrating strongly, or maybe even your phone camera to make a high-speed video of the movement.</p>
|
<p>I'm missing something here. How about damping the movement of table and head by placing a tuned mass damper on table and head? Something like a mass that is mounted in the top of a skyscraper...</p>
| 933
|
<p>What is the best way to include data in an HTML page? The data is not human-readable and will be processed by a script once the page has loaded. The options I can think of are:</p>
<ul>
<li><p>Using class and title attributes on hidden/empty <code><div></code> or <code><span></code> elements within the page</p></li>
<li><p>JSON in a <code><script></code> element at the bottom of the page</p></li>
<li><p>Load the data via an XMLHttpRequest after the page has loaded</p></li>
<li><p>XML Data Islands</p></li>
</ul>
<p>All of these methods seem to come with drawbacks so I would like to know what your thoughts are.</p>
|
<p>And help here? <a href="http://www.geocities.com/yongweiwu/multibyte.htm" rel="nofollow noreferrer">Multibyte Functions in Microsoft C Run-time</a></p>
|
<p>There is actually a very simple (but weird) way of force the OnChar function to send unicode characters to the application even if it's configured in multi-byte character set:</p>
<pre><code>SetWindowLongW( m_hWnd, GWL_WNDPROC, GetWindowLong( m_hWnd, GWL_WNDPROC ) );
</code></pre>
<p>Simply by calling the unicode version of "SetWindowLong", it forces the application to receive unicode characters.</p>
| 42,036
|
<p>I'm working on a time sheet application, where I'd like the user to be able to enter times in TextBoxes, e.g.: 8 a or 8:00 a or the like, just like you can in Excel.</p>
<p>Now if you enter a <em>date</em> in a TextBox and then use DateTime.TryParse, you can enter it in several formats (Jan 31, 2007; 1/31/2007; 31/1/2007; January 31, 2007; etc.) and .NET will figure it out and turn it into a DateTime.</p>
<p>But when I use DateTime.TryParse on a string like "8 a" or "8:00 a", it doesn't understand it.</p>
<p>I know I can use ParseExact, but I'm wondering if there's a more flexible solution. I want .NET to get 8:00a from "8 a" or "8:00 a", and to leave the date component at the default 1/1/0001.</p>
|
<p>Come to think of it, never mind. I just noticed that if I use "am" and "pm" instead of "a" and "p", it works fine. It assumes today's date, instead of the default 1/1/0001, but that's not a problem for my purposes.</p>
<p>(Still, any reasonably easy solution to get the "a" and "p" to work is welcome.)</p>
|
<p>You may be able to use the validating or validated event to capture the text and add the 'm'.</p>
| 35,739
|
<p>Here's a scenario I'm sure you're all familiar with. </p>
<ol>
<li><p>You have a fairly "hands off" customer, who really doesn't want to get too involved in the decision making despite your best efforts. </p></li>
<li><p>An experienced development team spend hours discussing the pros and cons of a particular approach to a problem and come up with an elegant solution which avoids the pitfalls of the more obvious approaches. </p></li>
<li><p>The customer casually mentions after a quick glance that they want it changed. They have no understanding of all the usability / consistency issues you were trying to avoid in your very carefully thought out approach. </p></li>
<li><p>Despite explanations, customer isn't interested, they just want it changed. </p></li>
<li><p>You sigh and do what they ask, knowing full well what will happen next...</p></li>
<li><p>3 weeks later, customer says it isn't working well this way, could you change it? You suggest again your original solution, and they seize on it with enthusiasm. They invariably seem to have had a form of selective amnesia and blocked out their role in messing this up in the first place. </p></li>
</ol>
<p>I'm sure many of you have gone through this. The thing which gets me is always when we know the time and effort that reasonably bright and able people have put in to really understanding the problem and trying to come up with a good solution. The frustration comes in contrasting this with the knowledge that the customer's choice is made in 3 minutes in a casual glance (or worse, by their managers who often don't even know what the project is really about). The icing on the cake is that it's usually made very late in the day. </p>
<p>I know that the agile methodologies are designed to solve exactly this kind of problem, but it requires a level of customer buy in that certain types of customers (people spending other peoples money usually) are just not willing to give. </p>
<p>Anyone any clever insight into how you deal with this?</p>
<p>EDIT: Oops - by the way, I'm not talking about any current or recent customer in this. It's purely hypothetical...</p>
|
<p>Make your customer pay by the effort you are putting into designing and developing the solution to their problem.</p>
<p>The more you work, the more you get. The customer will have to pay for his mistakes.</p>
<p>Customer will eventually learn to appreciate your experience and insight in the programming field.</p>
|
<p>Or else, <em>if they won't pay for the effort</em>, just avoid putting that much resources into the solution of the problem, and just give them exactly what they've asked for and then think about it after the three weeks have passed.</p>
<p>Somewhat frustrating, yes, but that's the way it'll always be with that kind of customers. At least you won't be losing money.</p>
| 7,715
|
<p>I am running a number of SSL-encrypted websites, and need to generate certificates to run on these. They are all internal applications, so I don't need to purchase a certificate, I can create my own.</p>
<p>I have found it quite tedious to do everything using openssl all the time, and figure this is the kind of thing that has probably been done before and software exists for it.</p>
<p>My preference is for linux-based systems, and I would prefer a command-line system rather than a GUI.</p>
<p>Does anyone have some suggestions?</p>
|
<p>An option that doesn't require your own CA is to get certificates from <a href="http://www.cacert.org/" rel="noreferrer">CAcert</a> (they're free).</p>
<p>I find it convenient to add the two CAcert root certificates to my client machines, then I can manage all the SSL certificates through CAcert.</p>
|
<p>I created <a href="https://github.com/brianclements/pkictl" rel="nofollow">a wrapper script</a>, written in Bash, for OpenSSL that might be useful to you here. To me, the easiest sources of user error when using OpenSSL were:</p>
<ol>
<li>Keeping a consistent and logical naming scheme for configuration/certs/keys so that I can see how every artifact fits into the entire PKI by just looking at the file name/extension</li>
<li>Enforcing a folder structure thats consistent across all CA machines that use the script.</li>
<li>Specifying too many configuration options via CLI and loosing track of some of the details</li>
</ol>
<p>The strategy is to push all configuration into their own files, saving only execution of a particular action for the CLI. The script also strongly enforces the use of a particular naming scheme for folders/files here which is helpful when looking at any single file.</p>
<p>Use/Fork/PR away! Hope it helps.</p>
| 3,836
|
<p>Is there a way to do gradients in css/html/javascript only that will work across all the major browsers? (MS IE 5+, Firefox, Opera, Safari)?</p>
<p>Edit: I would like to do this for backgrounds (header, main panel, side panels). Also, would like to have vertical line gradients as well.</p>
<p>Edit: after reading the responses, let's open this up to Javascript solutions as well, since HTML/CSS by itself makes it tougher to achieve.</p>
|
<p>I'm unclear on the implementation details you are seeking (such as background, or just a border along the side of the window, etc); however, it's possible albeit a little tedious.</p>
<p>One example that comes to mind would be to have n-block level elements, such as divs, and then give them each a small height (a couple of pixels, for example) and then gradually change the background color of each subsequent element.</p>
|
<p>I think the short answer is no.</p>
<p>You can create something that looks like a gradient using only css, but to then use it like an image background... I think that is pushing it a bit.</p>
<p><strong>EDIT (feeling silly)</strong> </p>
<p>I found the solution: <a href="http://en.wikipedia.org/wiki/JPEG" rel="nofollow noreferrer">http://en.wikipedia.org/wiki/JPEG</a></p>
| 47,071
|
<p>Our app encrypts a value using RC2 in C++ code and I wrote a decryption routine in .NET </p>
<p>The problem is that it works fine on our dev server, which is Windows 2003 but fails on the Windows 2000 one. It's running the same code and I checked everything else and it seems there are differences in the way the 2 encrypt. </p>
<p>Has anyone had any experience with that?</p>
|
<ol>
<li>Make sure Windows 2000 has SP3, or encryption is far less likely to work, particularly if using Capicom (or the api it wraps).</li>
<li>Not all of the encryption algorithms and keylengths are supported on Windows 2000 if using Capicom (or the api it wraps).</li>
</ol>
|
<p>There's an <a href="http://support.microsoft.com/kb/841715" rel="nofollow noreferrer">obscure issue</a> with win2000/winxp encryption/decryption. The Cryptography Service Provider on win2000 has 40 for the effective key length and that's used by default even if you use a 128 bit key. So to fix that you have to manually reset the effective key length on 2000 or you can set it to 40 before you decrypt on the winxp (or win2003 in my case). </p>
<p>If you're using <a href="http://www.eggheadcafe.com/forumarchives/platformsdksecurity/Jul2005/post23356686.asp" rel="nofollow noreferrer">C# to decrypt</a> you can't set the effective key size to something different than the key size if you use the RC2CryptoServiceProvider class.</p>
| 40,683
|
<p>I am building a web application that uses the database for Users, Security/roles, and to store content.</p>
<p>It seems a little daunting to me to begin on the road of unit testing because I have to make sure my database has been initialized properly for my tests to run.</p>
<p>What are common practices to help in this regard?</p>
<p>i.e. while developing/testing, I might delete a user, but for my test to pass that user has to be in the database, along with his profile, security settings etc.</p>
<p>I know I can create a setup script, something to recreat the databas etc. </p>
<p><b>I don't want to end up spending my entire time maintaining my tests and ensuring my database is in sych</b></p>
<p>Or is that the cost of Unit Testing/TDD?</p>
|
<p>It's not a unit test if you are testing more than one unit. </p>
<p>Usually you'll have one component (your page, or the business layer) talking to a data layer object that is responsible for actually connecting and querying the database. My recommendation is to develop a unit test for the first component, using dependency injection to pass in a <em>mock</em> version of the DataLayer (which acts on hardcoded data, or a List you pass in, etc). This way you are testing your higher level code in <strong>isolation</strong> from the other components.</p>
<p>Then you are free to develop other unit tests (and integration tests) for the data layer to ensure that it is handling it's job (writing to the database) correctly.</p>
|
<p>The cost of unit testing/TDD is that you have to alter your design so that you have a clean separation between the database and the domain layer, so that you can create a fake that will allow you to create tests that don't hit the database.</p>
<p>But that cleaner design is just the beginning of the cost. After that you have to create tests that both help you make the code work right the first time and alert you when anyone breaks something that used to work.</p>
<p>And after you have a good fundamental design with tests that protect your existing functionality, you'll find yourself cleaning up code to make it easier to work with, with confidence you aren't breaking things along the way.</p>
<p>And so on and so on... The costs of unit testing/TDD just keep piling up over time.</p>
| 44,291
|
<p>I'd like to add a method <code>AddDefaultNamespace()</code> to the String class in Java so that I can type <code>"myString".AddDefaultNamespace()</code> instead of <code>DEFAULTNAMESPACE + "myString"</code>, to obtain something like <code>"MyDefaultNameSpace.myString"</code>. I don't want to add another derived class either (<code>PrefixedString</code> for example).</p>
<p>Maybe the approach is not good for you but I personally hate using <code>+</code>. But, anyway, is it possible to add new methods to the String class in Java?</p>
<p>Thanks and regards.</p>
|
<p><code>String</code> is a final class which means it cannot be extended to work on your own implementation.</p>
|
<p>You can create your own version of String class and add a method :-)</p>
| 10,753
|
<p>What is the best way to handle user account management in a system, without having your employees who have access to a database, to have access to the accounts.</p>
<p>Examples:</p>
<ol>
<li><p>Storing username/password in the database. This is a bad idea because anyone that has access to a database can see the username and password. And hence use it.</p></li>
<li><p>Storing username/password hash. This is a better method, but the account can be accessed by replacing the password hash in the database with the hash of another account that you know the auth info for. Then after access is granted reverting it back in the database. </p></li>
</ol>
<p>How does windows/*nix handle this?</p>
|
<blockquote>
<p>This is a better method, but the account can be accessed by replacing the password hash in the database with the hash of another account that you know the auth info for.</p>
</blockquote>
<p>There's really no way around this. Anyone who as write access to the password file has complete control of the computer. </p>
|
<p>You could store the <em>salt</em> for the hashed password in another table, of course each user would have their own salt. You could then limit access to that table.</p>
| 8,574
|
<p>I am programming an iPhone app, and I need to force it to exit due to certain user actions. After cleaning up memory the app allocated, what's the appropriate method to call to terminate the application?</p>
|
<p>Have you tried <code>exit(0)</code>?</p>
<p>Alternatively, <code>[[NSThread mainThread] exit]</code>, although I have not tried that it seems like the more appropriate solution.</p>
|
<p>The user should decide when an app exits.
I don't think it is a good user interaction when an app quits. Therefore there is no nice API for it, only the home button has one.</p>
<p>If there is an error: Implement it better or Notify the user.
If there have to be a restart: Implement it better of Notify the user.</p>
<p>It sounds dumb, but it's bad practice to exit the app without letting the user decide and not notifying him. And since there is a home button for the user interaction, Apple states, there should not be 2 things for the same function (exiting an app).</p>
| 46,289
|
<p>I am looking for a way to get a function in excel to retrieve the distance form one zip to another. Lets say i have a list of 100,000 possible recruits and I want to sort by nearest. Id have the conference zip code and then 100,000 recruit zip codes. I'm looking to be able to just write a function =ZipCodeDistance(a2,d1) and then sort by that column. I have found a program for $65 that claims to do this, but I was wondering if there was a free way. </p>
|
<p>If you have the latitude and longitude for each zip code, you can use trigonometry to calculate the distance as the crow flies.</p>
<p>There is a free database <a href="http://www.populardata.com/downloads.html" rel="nofollow noreferrer">here</a> that you can download.</p>
<p>To do the calculation, see the info <a href="http://www.movable-type.co.uk/scripts/latlong.html" rel="nofollow noreferrer">here</a>. And some actual Excel-specific calc examples are <a href="http://www.cpearson.com/excel/latlong.htm" rel="nofollow noreferrer">here</a>.</p>
|
<p>How to get the data and the algorithm are explained <a href="https://web.archive.org/web/1/http://blogs.techrepublic%2ecom%2ecom/programming-and-development/?p=634" rel="nofollow noreferrer">here</a>, but in C#. If your Excel VBA is OK, it shouldn't be too difficult to translate?</p>
| 47,429
|
<p>I need to deploy a web application on several laptops (although it is a web application, it is intended to run via <code>localhost</code> only - thus the need to deploy on several different machines).</p>
<p>Normally I would go to IIS and right click a directory to create a web application, but I would very much like to automate this leg of the installation. Can it be done?</p>
<p><strong>I want to use IIS, but I want to create the web application automatically without opening the IIS Microsoft Management Console (MMC).</strong></p>
|
<p>I can suggest you to take a <a href="http://www.microsoft.com/technet/prodtechnol/WindowsServer2003/Library/IIS/1805162e-6ac5-4a98-9a08-919c4c10827d.mspx?mfr=true" rel="nofollow noreferrer">look at this link</a> if you are deploying on IIS 6 <a href="http://learn.iis.net/page.aspx/114/getting-started-with-appcmdexe/" rel="nofollow noreferrer">or at this one</a> if it is IIS 7 (I could recommend <a href="http://mvolo.com/blogs/serverside/default.aspx" rel="nofollow noreferrer">Mike Volodarsky's blog</a> for any information on IIS 7 in general).</p>
<p>It should be quite simple for you to write some batch file to automate a site creation.</p>
<p>Example:</p>
<ul>
<li>IIS6 : iisweb /create C:\Rome "My Vacations" /d www.reskit.com /dontstart</li>
<li>IIS7 : %windir%\system32\inetsrv\AppCmd ADD SITE /name:MyNewSite /bindings:http/*:81: /physicalPath:c:\inetpub\mynewsite</li>
</ul>
|
<p>Have look at <a href="http://weblogs.asp.net/rmclaws/archive/2005/10/25/428422.aspx" rel="nofollow noreferrer">this post</a>. It explains how to start <a href="https://www.developer.com/net/deciding-on-a-microsoft-web-server-cassini-iis-and-iis-express.html" rel="nofollow noreferrer">Cassini web server</a> from the command line and add it as a shell extension.</p>
<p>CarlosAg's blog has some great posts about <a href="http://blogs.msdn.com/carlosag/archive/2008/02/11/MicrosoftWebAdministrationInPowershell.aspx" rel="nofollow noreferrer">IIS administration throw PowerShell</a> and <a href="http://blogs.msdn.com/carlosag/archive/2008/06/12/FasterIISProvisioningUsingMWA.aspx" rel="nofollow noreferrer">managed code</a>.</p>
| 40,477
|
<p>I need a <a href="http://www.codeproject.com/KB/dotnet/regextutorial.aspx" rel="nofollow noreferrer">Regular Expressions</a> to get the text within 2 tags.</p>
<p>Lets say I want an array returned containing <strong>any text within <code><data</code>> and <code></data</code>> tags.</strong>
Or any text <strong>within "(" and ")" tags.</strong></p>
<p>How can I do that with RegEx's in C#?</p>
<hr>
<p>An advanced question would be:</p>
<ol>
<li>The input string is <strong>"color=rgb(50,20,30)"</strong></li>
<li>How can I get the 3 numbers in 3 seperate array slots as returned by the RegEx processor in C#?</li>
</ol>
|
<p>Since you specifically mentioned C#, here's how I'm doing that exact parsing:</p>
<pre><code>private static readonly Regex RgbValuePattern = new Regex(@"(?<r>\d{1,3}) ?, ?(?<g>\d{1,3}) ?, ?(?<b>\d{1,3})",
RegexOptions.Compiled | RegexOptions.ExplicitCapture);
</code></pre>
<p>Then later on...</p>
<pre><code>var match = RgbValuePattern.Match(value);
if (match.Success)
{
int r = Int32.Parse(match.Groups["r"].Value, NumberFormatInfo.InvariantInfo);
int g = Int32.Parse(match.Groups["g"].Value, NumberFormatInfo.InvariantInfo);
int b = Int32.Parse(match.Groups["b"].Value, NumberFormatInfo.InvariantInfo);
return Color.FromArgb(r, g, b);
}
</code></pre>
|
<p>I believe real problems will arise when you want to parse nesting constructs. For example, when you want to examine XML like this
<code><data><data>123</data><data>456</data></data></code>
to extract data included in outermost <code><data></code> tags one RegEx alone would not be enough. Just warn you to not use RegEx where some more (powerful and specific) methods exist. Real XML parsers should be considered when doing more complex tasks on XML. My 2 cents...</p>
| 46,012
|
<p>I am looking for an open source project that uses EJB3 as backend and JSF as frontend. It should <em>not</em> be a tutorial but a real application that real people are using.</p>
<p>The application should be data-driven, i.e. the following aspects are fundamental and make 80% or more of the application.</p>
<ul>
<li>form-based (many input forms)</li>
<li>table views, master/detail, etc.</li>
<li>CRUD (create/read/update/delete)-Operations have been implemented</li>
<li>support for relations: 1:1, 1:n</li>
<li>JPA Entity Beans + EJB 3 Stateless Session Beans for Facade</li>
<li>no JBoss Seam</li>
</ul>
<p>Typical applications are CRM / ERP projects where people work a lot with lists, tables, and forms. But any other "administrative" application should be OK, too.</p>
<p>I know petstore, but that application isn't form-based. petstore is a end-user application. I am looking for backend-user applications.</p>
<p>Something like Microsofts AdventureWorks series, but with EJB3+JSF...
Something like SugarCRM, but with EJB3+JSF...</p>
<p>I've googled <em>a lot</em>... with no results :-(</p>
<ul>
<li>@Matthew: the samples provided with NetBeans are too simple.</li>
<li>@JB: It should be a real application. Not a "how to do EJB+JSF" application.</li>
<li>@50-50: voted down because of seam</li>
<li>@Kariem: I can't use seam, AppFuse hasn't EJB Session Beans</li>
</ul>
|
<p>Seam examples are quite good. They are stand-alone projects, that you may deploy out of the box. </p>
|
<p>I am not sure is it 100% what your looking for, <strong>but check out the built in example that comes packaged with NetBeans 6.1</strong>. It uses JSF/EJB3/ApacheDerby. I played around with it for like 20 minutes and thought it was pretty cool as a simple/starter JavaEE application to learn from.</p>
| 5,908
|
<p>I know there is a tool that enables me to see what actually gets sent/received in my WCF application, that is it let's me see the actual SOAP messages being passed down the wire.
The problem is I don't remember what that tool was called, and my Google skills are not of much help either. Anyone?</p>
|
<p>I believe your looking for the Service Trace Viewier.
<a href="http://msdn.microsoft.com/en-us/library/ms732023.aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/ms732023.aspx</a></p>
|
<p>I enable tracing for the service and use Microsoft Service Trace Viewer to look at them.</p>
| 26,196
|
<p>On a CentOS LAMP box, trying to get require_once to work inside a script in PHP5. If the file to be included is not a in symlinked directory, it works fine, but if the file to be required is in a directory found via a symbolic link, it fails to find it.</p>
<p>Is this a limitation of require_once and symbolic links?</p>
<p>EDIT - Thanks for the input, all. I think it's most likely a permissions thing after reading those</p>
|
<p>To my knowledge, require_once can use symbolic links just fine. I'm using include_once with some symbolic links in a WordPress MU install and it works just fine - I can't imagine why require_once would function differently than include_once in that respect.</p>
<p>Any chance you've got <a href="http://php.net/manual/en/ini.core.php#ini.open-basedir" rel="nofollow noreferrer">open_basedir</a> restrictions set?</p>
|
<p>As far as I know there aren't. Are the permissions the same as when you don't use the sym link?</p>
| 23,778
|
<p>We have multiple MFC apps, which use CMutex( false, "blah" ), where "blah" allows the mutex to work across process boundaries.</p>
<p>One of these apps was re-written without MFC (using Qt instead). How can I simulate the CMutex using Win32 calls? (Qt's QMutex is not inter-process.) I prefer not to modify the MFC apps.</p>
|
<p>For inter-process mutexes you want these calls:</p>
<blockquote>
<p><a href="http://msdn.microsoft.com/en-us/library/ms682411(VS.85).aspx" rel="nofollow noreferrer">CreateMutex</a></p>
<p><a href="http://msdn.microsoft.com/en-us/library/ms687032(VS.85).aspx" rel="nofollow noreferrer">WaitForSingleObject</a></p>
<p><a href="http://msdn.microsoft.com/en-us/library/ms685066(VS.85).aspx" rel="nofollow noreferrer">ReleaseMutex</a></p>
<p><a href="http://msdn.microsoft.com/en-us/library/ms724211(VS.85).aspx" rel="nofollow noreferrer">CloseHandle</a></p>
</blockquote>
<p>These are the underlying Win32 API calls that CMutex is a wrapper around.</p>
<p>For in-process only mutexes you can also use these calls, which are faster:</p>
<blockquote>
<p><a href="http://msdn.microsoft.com/en-us/library/ms683472(VS.85).aspx" rel="nofollow noreferrer">InitializeCriticalSection</a></p>
<p><a href="http://msdn.microsoft.com/en-us/library/ms683472(VS.85).aspx" rel="nofollow noreferrer">EnterCriticalSection</a></p>
<p><a href="http://msdn.microsoft.com/en-us/library/ms683472(VS.85).aspx" rel="nofollow noreferrer">LeaveCriticalSection</a></p>
<p><a href="http://msdn.microsoft.com/en-us/library/ms682552(VS.85).aspx" rel="nofollow noreferrer">DeleteCriticalSection</a></p>
</blockquote>
|
<p>The following funcs will probably be what you want, they are all documented on MSDN.</p>
<pre><code>CreateMutex(...)
WaitForSingleObject(...)
ReleaseMutex(...)
</code></pre>
| 12,212
|
<p>I am trying to build a function in C/C++ to sort an array and replace each value with its "score" or rank. It takes in a double pointer array to an array of ints, and sorts the double pointers based on the dereferenced value of the integers. I have tried quite a few times to make it work, but can't get it down. Once again, it must sort the double pointers based on the values they point to. This is what I have:</p>
<pre><code>void SortArray( int ** pArray, int ArrayLength )
{
int i, j, flag = 1; // set flag to 1 to begin initial pass
int * temp; // holding variable orig with no *
for(i = 1; (i <= ArrayLength) && flag; i++)
{
flag = 0;
for (j = 0; j < (ArrayLength -1); j++)
{
if (*pArray[j+1] > *pArray[j]) // ascending order simply changes to <
{
temp = &pArray[j]; // swap elements
pArray[j] = &pArray[j+1];
pArray[j+1] = &temp;
flag = 1; // indicates that a swap occurred.
}
}
}
}
</code></pre>
|
<p>You're close. You're referencing the address of the array items when you swap, which isn't necessary. The items in the array are pointers, and that's what needs to be swapped.</p>
<p>See below:</p>
<pre><code>void SortArray( int ** pArray, int ArrayLength )
{
int i, j, flag = 1; // set flag to 1 to begin initial pass
int * temp; // holding variable orig with no *
for(i = ArrayLength - 1; i > 0 && flag; i--)
{
flag = 0;
for (j = 0; j < i; j++)
{
if (*pArray[j] > *pArray[j+1]) // ascending order simply changes to <
{
temp = pArray[j]; // swap elements
pArray[j] = pArray[j+1];
pArray[j+1] = temp;
flag = 1; // indicates that a swap occurred.
}
}
}
}
</code></pre>
<p>Also, check out <a href="http://rant.blackapache.net/2008/08/14/sorting-algorithms-the-bubble-sort/" rel="nofollow noreferrer">this lovely blog post on Bubble Sorting</a> in case you're interested (sorry, shameless plug :)). Hope that helps you with your homework ;)</p>
<hr>
<p>Edit: Note the subtle "optimisation" where you count back from the array length and only increment up until 'i' in the inner loop. This saves you from needlessly reparsing items that have already been sorted.</p>
|
<p>To complete Brian Ensink's post, you'll find the STL full of surprises. For example, the std::sort algorithm:</p>
<pre><code>#include <iostream>
#include <vector>
#include <algorithm>
void printArray(const std::vector<int *> & p_aInt)
{
for(std::vector<int *>::size_type i = 0, iMax = p_aInt.size(); i < iMax; ++i)
{
std::cout << "i[" << static_cast<int>(i) << "] = " << reinterpret_cast<unsigned int>(p_aInt[i]) << std::endl ;
}
std::cout << std::endl ;
}
int main(int argc, char **argv)
{
int a = 1 ;
int b = 2 ;
int c = 3 ;
int d = 4 ;
int e = 5 ;
std::vector<int *> aInt ;
// We fill the vector with variables in an unordered way
aInt.push_back(&c) ;
aInt.push_back(&b) ;
aInt.push_back(&e) ;
aInt.push_back(&d) ;
aInt.push_back(&a) ;
printArray(aInt) ; // We see the addresses are NOT ordered
std::sort(aInt.begin(), aInt.end()) ; // DO THE SORTING
printArray(aInt) ; // We see the addresses are ORDERED
return EXIT_SUCCESS;
}
</code></pre>
<p>The first printing of the array will show unordered addresses. The second, after the sort, will show ordered adresses. On my compiler, we have:</p>
<pre><code>i[0] = 3216087168
i[1] = 3216087172
i[2] = 3216087160
i[3] = 3216087164
i[4] = 3216087176
i[0] = 3216087160
i[1] = 3216087164
i[2] = 3216087168
i[3] = 3216087172
i[4] = 3216087176
</code></pre>
<p>Give STL's <algorithm> header a look <a href="http://www.cplusplus.com/reference/algorithm/" rel="nofollow noreferrer">http://www.cplusplus.com/reference/algorithm/</a>
You'll find a lot of utilities. Note that you have other implementation of containers that could suit you better (std::list? std::map?).</p>
| 3,798
|
<p>How can I start writing a plugin for <a href="http://en.wikipedia.org/wiki/Eclipse_%28software%29" rel="noreferrer">Eclipse</a>?</p>
<p>I've looked for documentation, but unfortunately there is very little or it's poor, so what articles can recommended?</p>
|
<p>There are some pretty good resources and tutorials on the main Eclipse and IBM's site. One of the best ways is to pick an open source plug-in that has some similar features to what you want to do and start to dissect it.</p>
<ul>
<li><em><a href="http://www.eclipse.org/articles/Article-PDE-does-plugins/PDE-intro.html" rel="noreferrer">PDE Does Plug-ins</a></em></li>
<li><em><a href="http://www.ibm.com/developerworks/library/os-eclipse-plugindev1/index.html" rel="noreferrer">Plug-in development 101, Part 1: The fundamentals</a></em></li>
<li><em><a href="http://www.onjava.com/pub/a/onjava/2005/02/09/eclipse.html" rel="noreferrer">Eclipse Plugins Exposed, Part 1: A First Glimpse</a></em></li>
<li><em><a href="http://www.ibm.com/developerworks/opensource/library/os-ecplug/" rel="noreferrer">Developing Eclipse plug-ins</a></em></li>
</ul>
|
<p>I think a very good resource is also to look at the examples that are available via the new Plug-In Project wizard.</p>
<p>Depending on what you want to provide with your plug-in, you can choose from editor plug-ins, view plug-ins, plug-ins that provide a property page (just to name a few) and see how they're built and what extension points they implement.</p>
| 38,335
|
<p>A couple of months ago I've coded a tiny tool that we needed at work for a specific task, and I've decided to share it on CodePlex. It's written in C# and honestly it's not big deal but since it's the first project I've ever built from scratch in that language and with the goal of opening it from the very beginning, one ends getting sort of emotionally attached to it, I mean you'd wish that the people will actually participate, be it criticism, bug reporting, or what have you.</p>
<p>So my question is, what can I do to actually encourage participation, stimulate curiosity or just recieve more feedback about it?</p>
<p>By the way this is the project I'm talking about: <a href="http://www.codeplex.com/winxmlcook/" rel="nofollow noreferrer">http://www.codeplex.com/winxmlcook/</a></p>
|
<p>You should:</p>
<ul>
<li>Promote it where you think it would be relevant (forums,mailing lists etc.). Try not to spam though - it will create a backlash.</li>
<li>continue to provide updates as to create the appearance of an active project until more people pick it up.</li>
<li>Find project leaders, they are the sort of contributors that encourage others to contribute as well. </li>
<li>Blog about it and link to relevant blogs (creating ping-backs). Also leave comments at relevant blog posts.</li>
</ul>
<p>Basically, your generic Internet marketing tactics ;)</p>
|
<p>You should:</p>
<ul>
<li>Promote it where you think it would be relevant (forums,mailing lists etc.). Try not to spam though - it will create a backlash.</li>
<li>continue to provide updates as to create the appearance of an active project until more people pick it up.</li>
<li>Find project leaders, they are the sort of contributors that encourage others to contribute as well. </li>
<li>Blog about it and link to relevant blogs (creating ping-backs). Also leave comments at relevant blog posts.</li>
</ul>
<p>Basically, your generic Internet marketing tactics ;)</p>
| 16,613
|
<p>Our testers are in the process of evaluating Visual Studio Team System 2008 Test Edition. As they are unfamiliar with the use of Visual Studio, I would like to give them as much help as I can.</p>
<p>I have had a look on Amazon for books on the Test edition of VS.Net, but there is only one VS.Net 2005 test edition book.</p>
<p>Does anyone know of any good books, or online training resources with a particular focus on the features of the Test Edition of Visual Studio Team System 2008?</p>
|
<p>For someone evaluating features who isn't that familiar with Visual Studio, I'd recommend the videos from a few places:</p>
<ul>
<li><a href="http://msdn.microsoft.com/en-us/vsts2008/bb507749.aspx?wt.slv=topsectionsee" rel="nofollow noreferrer">"How Do I?" Videos for Team System</a></li>
<li><a href="http://www.asp.net/learn/vsts-videos/" rel="nofollow noreferrer">ASP.net's Learn section</a></li>
<li><a href="http://teamsystemrocks.com/tutorials/default.aspx" rel="nofollow noreferrer">Video tutorials at TeamSystemRocks.com</a></li>
</ul>
<p>Plenty of videos between those sites on the various VSTS Test Edition features. Note that many are about VS2005, but the fundamental concepts don't change when moving to 2008. </p>
<p>Once they get the basic features, here's a summary of <a href="http://msdn.microsoft.com/en-us/vsts2008/products/bb933755.aspx" rel="nofollow noreferrer">What's New in VS2008 Test Edition</a>.</p>
<p>See also:</p>
<ul>
<li><a href="http://msdn.microsoft.com/en-us/vsts2008/test/default.aspx" rel="nofollow noreferrer">VSTS 2008 Test Edition Home</a> (BTW, there's a link to a trial VPC w/TFS & VSTS Suite on the right-hand side)</li>
<li><a href="http://www.microsoft.com/downloads/details.aspx?familyid=8BDAA836-0BBA-4393-94DB-6C3C4A0C98A1&displaylang=en" rel="nofollow noreferrer">Visual Studio 2008 Training Kit</a> - Not a lot on VSTS in here, but there are a few demos and resources that touch on the Test features, and it's a good general resource to have, anyway.</li>
</ul>
|
<p>Also, have a look at msdn:</p>
<p>Walkthroughs for Test Edition<br/>
<a href="http://msdn.microsoft.com/en-us/library/ms182417.aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/ms182417.aspx</a></p>
<p>Web Test Walkthroughs<br/>
<a href="http://msdn.microsoft.com/en-us/library/aa337591.aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/aa337591.aspx</a></p>
| 29,903
|
<p>What effect does a field name length has on the performance of a database? Is it negligible? Should I go with long descriptive names?</p>
|
<p>I haven't measured the time, but I would imagine negligible. The field names are going to be sent back and forth over the network, both in your SQL statements TO the database and in the metadata that comes back FROM the database, but I think the incremental difference that a few bytes makes in those packets is below the threshold of caring.</p>
<p>Pity the poor humans that have to read your code, and make the names descriptive. Let the computer to a tiny bit of extra work.</p>
|
<p>Internally, the query processor uses numbers for field names once the tokens in the query are parsed,
There are no sensible performance gains in short names on database objects. </p>
| 30,581
|
<p>A basic problem I run into quite often, but ever found a clean solution to, is one where you want to code behaviour for interaction between different objects of a common base class or interface. To make it a bit concrete, I'll throw in an example;</p>
<p><em>Bob has been coding on a strategy game which supports "cool geographical effects". These round up to simple constraints such as if troops are walking in water, they are slowed 25%. If they are walking on grass, they are slowed 5%, and if they are walking on pavement they are slowed by 0%.</em></p>
<p><em>Now, management told Bob that they needed new sorts of troops. There would be jeeps, boats and also hovercrafts. Also, they wanted jeeps to take damage if they went drove into water, and hovercrafts would ignore all three of the terrain types. Rumor has it also that they might add another terrain type with even more features than slowing units down and taking damage.</em></p>
<p>A very rough pseudo code example follows:</p>
<pre><code>public interface ITerrain
{
void AffectUnit(IUnit unit);
}
public class Water : ITerrain
{
public void AffectUnit(IUnit unit)
{
if (unit is HoverCraft)
{
// Don't affect it anyhow
}
if (unit is FootSoldier)
{
unit.SpeedMultiplier = 0.75f;
}
if (unit is Jeep)
{
unit.SpeedMultiplier = 0.70f;
unit.Health -= 5.0f;
}
if (unit is Boat)
{
// Don't affect it anyhow
}
/*
* List grows larger each day...
*/
}
}
public class Grass : ITerrain
{
public void AffectUnit(IUnit unit)
{
if (unit is HoverCraft)
{
// Don't affect it anyhow
}
if (unit is FootSoldier)
{
unit.SpeedMultiplier = 0.95f;
}
if (unit is Jeep)
{
unit.SpeedMultiplier = 0.85f;
}
if (unit is Boat)
{
unit.SpeedMultiplier = 0.0f;
unit.Health = 0.0f;
Boat boat = unit as Boat;
boat.DamagePropeller();
// Perhaps throw in an explosion aswell?
}
/*
* List grows larger each day...
*/
}
}
</code></pre>
<p>As you can see, things would have been better if Bob had a solid design document from the beginning. As the number of units and terrain types grow, so does code complexity. Not only does Bob have to worry about figuring out which members might need to be added to the unit interface, but he also has to repeat alot of code. It's very likely that new terrain types require additional information from what can be obtained from the basic IUnit interface. </p>
<p>Each time we add another unit into the game, each terrain must be updated to handle the new unit. Clearly, this makes for a lot of repetition, not to mention the ugly runtime check which determines the type of unit being dealt with. I've opted out calls to the specific subtypes in this example, but those kinds of calls are neccessary to make. <em>An example would be that when a boat hits land, its propeller should be damaged. Not all units have propellers.</em></p>
<p>I am unsure what this kind of problem is called, but it is a many-to-many dependence which I have a hard time decoupling. I don't fancy having 100's of overloads for each IUnit subclass on ITerrain as I would want to come clean with coupling.</p>
<p>Any light on this problem is highly sought after. Perhaps I'm thinking way out of orbit all together?</p>
|
<p>Terrain has-a Terrain Attribute </p>
<p>Terrain Attributes are multidimensional. </p>
<p>Units has-a Propulsion.</p>
<p>Propulsion is compatible able with Terrain Attributes.</p>
<p>Units move by a Terrain visit with Propulsion as an argument.
That gets delegated to the Propulsion.</p>
<p>Units <em>may</em> get affected by terrain as part of the visit.</p>
<p>Unit code knows nothing about propulsion.
Terrain types can change w/o changing anything except Terrain Attributes and Propulsion.
Propuslion's constructors protect existing units from new methods of travel.</p>
|
<p>Old idea:</p>
<blockquote>
<p>Make a class iTerrain and another
class iUnit which accepts an argument
which is the terrain type including a
method for affecting each unit type</p>
<p>example:</p>
<pre> <code> boat = new
iUnit("watercraft") field = new
iTerrain("grass")
field.effects(boat)</code></pre>
</blockquote>
<p>ok forget all that I have a better idea:</p>
<p>Make the effects of each terrain a property of each unit</p>
<p>Example:</p>
<pre><code>
public class hovercraft : unit {
#You make a base class for defaults and redefine as necessary
speed_multiplier.water = 1
}
public class boat : unit {
speed_multiplier.land = 0
}
</code></pre>
| 9,401
|
<p>I need to encode a 100KB+ string as base64 in VBA. Are there any built-in functions or COM objects available which will do this as a pure VBA approach is either complex or doesn't scale well at these volumes (see links from <a href="http://www.vbforums.com/showthread.php?t=379072" rel="noreferrer">dbb</a> and <a href="http://www.motobit.com/tips/detpg_Base64Encode/" rel="noreferrer">marxidad</a>)?</p>
|
<p>You can use the MSXML Base64 encoding functionality as described at <a href="http://web.archive.org/web/20060527094535/http://www.nonhostile.com/howto-encode-decode-base64-vb6.asp" rel="nofollow noreferrer">www.nonhostile.com/howto-encode-decode-base64-vb6.asp</a>:</p>
<pre><code>Function EncodeBase64(text As String) As String
Dim arrData() As Byte
arrData = StrConv(text, vbFromUnicode)
Dim objXML As MSXML2.DOMDocument
Dim objNode As MSXML2.IXMLDOMElement
Set objXML = New MSXML2.DOMDocument
Set objNode = objXML.createElement("b64")
objNode.dataType = "bin.base64"
objNode.nodeTypedValue = arrData
EncodeBase64 = Replace(objNode.Text, vbLf, "")
Set objNode = Nothing
Set objXML = Nothing
End Function
</code></pre>
|
<p>As Mark C points out, you can use the MSXML Base64 encoding functionality as described <a href="http://www.nonhostile.com/howto-encode-decode-base64-vb6.asp" rel="nofollow noreferrer">here</a>.</p>
<p>I prefer late binding because it's easier to deploy, so here's the same function that will work without any VBA references:</p>
<pre><code>Function EncodeBase64(text As String) As String
Dim arrData() As Byte
arrData = StrConv(text, vbFromUnicode)
Dim objXML As Variant
Dim objNode As Variant
Set objXML = CreateObject("MSXML2.DOMDocument")
Set objNode = objXML.createElement("b64")
objNode.dataType = "bin.base64"
objNode.nodeTypedValue = arrData
EncodeBase64 = Replace(objNode.Text, vbLf, "")
Set objNode = Nothing
Set objXML = Nothing
End Function
</code></pre>
| 20,509
|
<p>In many C/C++ macros I'm seeing the code of the macro wrapped in what seems like a meaningless <code>do while</code> loop. Here are examples.</p>
<pre><code>#define FOO(X) do { f(X); g(X); } while (0)
#define FOO(X) if (1) { f(X); g(X); } else
</code></pre>
<p>I can't see what the <code>do while</code> is doing. Why not just write this without it?</p>
<pre><code>#define FOO(X) f(X); g(X)
</code></pre>
|
<p>The <code>do ... while</code> and <code>if ... else</code> are there to make it so that a
semicolon after your macro always means the same thing. Let's say you
had something like your second macro.</p>
<pre><code>#define BAR(X) f(x); g(x)
</code></pre>
<p>Now if you were to use <code>BAR(X);</code> in an <code>if ... else</code> statement, where the bodies of the if statement were not wrapped in curly brackets, you'd get a bad surprise.</p>
<pre><code>if (corge)
BAR(corge);
else
gralt();
</code></pre>
<p>The above code would expand into</p>
<pre><code>if (corge)
f(corge); g(corge);
else
gralt();
</code></pre>
<p>which is syntactically incorrect, as the else is no longer associated with the if. It doesn't help to wrap things in curly braces within the macro, because a semicolon after the braces is syntactically incorrect.</p>
<pre><code>if (corge)
{f(corge); g(corge);};
else
gralt();
</code></pre>
<p>There are two ways of fixing the problem. The first is to use a comma to sequence statements within the macro without robbing it of its ability to act like an expression.</p>
<pre><code>#define BAR(X) f(X), g(X)
</code></pre>
<p>The above version of bar <code>BAR</code> expands the above code into what follows, which is syntactically correct.</p>
<pre><code>if (corge)
f(corge), g(corge);
else
gralt();
</code></pre>
<p>This doesn't work if instead of <code>f(X)</code> you have a more complicated body of code that needs to go in its own block, say for example to declare local variables. In the most general case the solution is to use something like <code>do ... while</code> to cause the macro to be a single statement that takes a semicolon without confusion.</p>
<pre><code>#define BAR(X) do { \
int i = f(X); \
if (i > 4) g(i); \
} while (0)
</code></pre>
<p>You don't have to use <code>do ... while</code>, you could cook up something with <code>if ... else</code> as well, although when <code>if ... else</code> expands inside of an <code>if ... else</code> it leads to a "<a href="http://en.wikipedia.org/wiki/Dangling_else" rel="noreferrer">dangling else</a>", which could make an existing dangling else problem even harder to find, as in the following code.</p>
<pre><code>if (corge)
if (1) { f(corge); g(corge); } else;
else
gralt();
</code></pre>
<p>The point is to use up the semicolon in contexts where a dangling semicolon is erroneous. Of course, it could (and probably should) be argued at this point that it would be better to declare <code>BAR</code> as an actual function, not a macro.</p>
<p>In summary, the <code>do ... while</code> is there to work around the shortcomings of the C preprocessor. When those C style guides tell you to lay off the C preprocessor, this is the kind of thing they're worried about.</p>
|
<p>I don't think it was mentioned so consider this</p>
<pre><code>while(i<100)
FOO(i++);
</code></pre>
<p>would be translated into</p>
<pre><code>while(i<100)
do { f(i++); g(i++); } while (0)
</code></pre>
<p>notice how <code>i++</code> is evaluated twice by the macro. This can lead to some interesting errors.</p>
| 18,624
|
<p>I have a form showing progress messages as a fairly long process runs. It's a call to a web service so I can't really show a percentage complete figure on a progress bar meaningfully. (I don't particularly like the Marquee property of the progress bar)</p>
<p>I would like to show an animated GIF to give the process the feel of some activity (e.g. files flying from one computer to another like Windows copy process).</p>
<p>How do you do this?</p>
|
<p>It's not too hard.</p>
<ol>
<li>Drop a picturebox onto your form.</li>
<li>Add the .gif file as the image in the picturebox</li>
<li>Show the picturebox when you are loading.</li>
</ol>
<p><strong>Things to take into consideration:</strong></p>
<ul>
<li>Disabling the picturebox will prevent the gif from being animated.</li>
</ul>
<p><strong>Another way of doing it:</strong></p>
<p>Another way that I have found that works quite well is the async dialog control that I found on the <a href="http://www.codeproject.com/KB/dialog/asyncdialog.aspx" rel="nofollow noreferrer">code project</a></p>
|
<p>I had the same issue and came across different solutions by implementing which I used to face several different issues. Finally, below is what I put some pieces from different posts together which worked for me as expected.</p>
<pre><code>private void btnCompare_Click(object sender, EventArgs e)
{
ThreadStart threadStart = new ThreadStart(Execution);
Thread thread = new Thread(threadStart);
thread.SetApartmentState(ApartmentState.STA);
thread.Start();
}
</code></pre>
<p>Here is the Execution method that also carries invoking the PictureBox control:</p>
<pre><code>private void Execution()
{
btnCompare.Invoke((MethodInvoker)delegate { pictureBox1.Visible = true; });
Application.DoEvents();
// Your main code comes here . . .
btnCompare.Invoke((MethodInvoker)delegate { pictureBox1.Visible = false; });
}
</code></pre>
<p>Keep in mind, the PictureBox is invisible from Properties Window or do below:</p>
<pre><code>private void ComparerForm_Load(object sender, EventArgs e)
{
pictureBox1.Visible = false;
}
</code></pre>
| 20,015
|
<p>Is there a maximum number of characters that can be written to a file using a StreamWriter? Or is there a maximum number of characters that <code>WriteLine()</code> can output? I am trying to write some data to a file but all of the data does not seem to make it. This is the current state of my code:</p>
<pre><code>StreamWriter sw = new StreamWriter(pathToFile);
foreach (GridViewRow record in gv_Records.Rows)
{
string recordInfo = "recordInformation";
sw.WriteLine(recordInfo);
}
</code></pre>
|
<p>Are you calling StreamWriter.Close() or Flush()?</p>
|
<p>Make sure that you are calling .Flush()</p>
| 19,772
|
<p>Is there explicit support for Single Table Inheritance in Django? Last I heard, the feature was still under development and debate. </p>
<p>Are there libraries/hacks I can use in the meantime to capture the basic behavior? I have a hierarchy that mixes different objects. The canonical example of a corporation structure with an Employee class, subclasses for types of employees, and a manager_id (parent_id) would be a good approximation of the problem I am solving. </p>
<p>In my case, I would like to represent the idea that an employee can manage other employees while being managed by a different employee. There are not separate classes for Manager and Worker, which makes this hard to spread across tables. Sub-classes would represent types of employees-programmers, accountants, sales, etc and would be independent of who supervises who (OK, I guess it's no longer a typical corporation in some respect). </p>
|
<p>There are currently two forms of inheritance in Django - MTI (model table inheritance) and ABC (abstract base classes).</p>
<p>I wrote a <a href="http://web.archive.org/web/20090227074910/http://thisweekindjango.com/articles/2008/jun/17/abstract-base-classes-vs-model-tab/" rel="noreferrer">tutorial</a> on what's going on under the hood.</p>
<p>You can also reference the official docs on <a href="http://docs.djangoproject.com/en/dev/topics/db/models/#model-inheritance" rel="noreferrer">model inheritance</a>.</p>
|
<p>I think you can do something akin to this.</p>
<p>I have to implement a solution for this problem myself, and here was how I solved it:</p>
<pre class="lang-py prettyprint-override"><code>class Citrus(models.Model):
how_acidic = models.PositiveIntegerField(max_value=100)
skin_color = models.CharField()
type = models.CharField()
class TangeloManager(models.Manager):
def get_query_set(self):
return super(TangeloManager, self).get_query_set().filter(type='Tangelo')
class Tangelo(models.Model):
how_acidic = models.PositiveIntegerField(max_value=100)
skin_color = models.CharField()
type = models.CharField()
objects = TangeloManager()
class Meta:
# 'appname' below is going to vary with the name of your app
db_table = u'appname_citrus'
</code></pre>
<p>This may have some locking issues... I'm not really sure how django handles that off the top of my head. Also, I didn't really test the above code, it's strictly for entertainment purposes, to hopefully put you on the right track.</p>
| 29,862
|
<p>I'd like to write a plugin that does something with the currently edited file in Eclipse. But I'm not sure how to properly get the file's full path.</p>
<p>This is what I do now:</p>
<pre><code>IFile file = (IFile) window.getActivePage().getActiveEditor.getEditorInput().
getAdapter(IFile.class);
</code></pre>
<p>Now I have an IFile object, and I can retrieve it's path:</p>
<pre><code>file.getFullPath().toOSString();
</code></pre>
<p>However this still only gives me the path relative to the workspace. How can I get the absolute path from that?</p>
|
<p>Looks like you want <a href="http://help.eclipse.org/helios/index.jsp?topic=%2Forg.eclipse.platform.doc.isv%2Freference%2Fapi%2Forg%2Feclipse%2Fcore%2Fresources%2FIResource.html" rel="noreferrer"><code>IResource.getRawLocation()</code></a>. That returns an <code>IPath</code>, which also has a <code>makeAbsolute()</code> method if you want to be doubly sure you've got an absolute path.</p>
|
<p>For me, this run ok.</p>
<p>IWorkspaceRoot workSpaceRoot = ResourcesPlugin.getWorkspace().getRoot();</p>
<p>File file = workSpaceRoot.getRawLocation().makeAbsolute().toFile();</p>
<p>file list from this location:</p>
<p>File[] files = file.listFiles();</p>
| 38,398
|
<p>In a custom module for drupal 4.7 I hacked together a node object and passed it to node_save($node) to create nodes. This hack appears to no longer work in drupal 6. While I'm sure this hack could be fixed I'm curious if there is a standard solution to create nodes without a form. In this case the data is pulled in from a custom feed on another website.</p>
|
<p>I don't know of a standard API for creating a node pragmatically. But this is what I've gleaned from building a module that does what you're trying to do.</p>
<ol>
<li>Make sure the important fields are set: uid, name, type, language, title, body, filter (see <code>node_add()</code> and <code>node_form()</code>)</li>
<li>Pass the node through <code>node_object_prepare()</code> so other modules can add to the $node object.</li>
</ol>
|
<p>One more answer I discovered was to use <a href="http://api.drupal.org/api/function/blogapi_blogger_new_post/6" rel="nofollow noreferrer">the example</a> from the blogapi module in drupal core. The fact that it is in core gives me a bit more confidence that it will continue to work in future versions.</p>
| 11,422
|
<p>I have a windows service connecting to a SqlServer database on the local box. This works fine most all the time. At a large customer, however, the database connectivity gets corrupted for some rare and unknown reason. When this happens, calls to DbDataAdapter.Fill return a DataSet with a different number of columns than in the select command passed in (validated by trace logs showing the sql expected, and the number of columns returned). For the first few errored DataSets it appears the adapter instance is returning results from the previous query. This is happening even though the adapter objects are unique instances, and the connection/adapter creation calls are thread protected (as DbProviderFactory is not thread safe).</p>
<p>Has anyone experience this or something similar? Does anyone know what could cause this? At this moment in time, I'm having a hard time thinking up new ideas for a cause of this.</p>
|
<p>I've got the following in my <code>.emacs</code></p>
<pre><code>(add-hook 'shell-mode-hook 'ansi-color-for-comint-mode-on)
</code></pre>
|
<p>The following should work in your .bash_profile or .bashrc</p>
<pre><code>case $TERM in
xterm-color)
export PS1='\[\e]0;\W\007\]\[\e[34;1m\]\W\[\e[0m\]\$ '
;;
*)
export PS1='\W\$ '
;;
esac
</code></pre>
| 31,979
|
<p>In logging frameworks like log4j & log4net you have the ability to log various levels of information. Most of the levels have obvious intentions (such as what a "Debug" log is vs. a "Error"). However, one thing that I have always been timid on was classifying my logging as "Fatal".</p>
<p>What type of errors are so severe that they should be classified as fatal? While this is slightly case driven, what are some of the rules-of-thumb that you use when deciding between logging an exception as fatal or just simply error?</p>
|
<p>I consider fatal errors to be when your application can't do any more useful work. Non-fatal errors are when there's a problem but your application can still continue to function, even at a reduced level of functionality or performance.</p>
<p>Examples of fatal errors include:</p>
<ul>
<li>Running out of disk space on the logging device and you're required to keep logging.</li>
<li>Total loss of network connectivity in a client application.</li>
<li>Missing configuration information if no default can be used.</li>
</ul>
<p>Non-fatal errors would include:</p>
<ul>
<li>A server where a single session fails for some reason but you can still service other clients.</li>
<li>An intermittent error, such as lost session, if a new session can be established.</li>
<li>Missing configuration information if a default value can be used.</li>
</ul>
|
<p>To make this answer short and sweet, if your application crashes, I would consider that fatal. If you cannot connect to an important resource such as a database or a required service, that would be fatal. Overall, I would say that if it keeps your application from running correctly and affects the user, I would classify it as a fatal error. </p>
<p>But the most important way to classify errors is to consistently follow a rule of thumb such as rule 69 in <a href="http://www.gotw.ca/publications/c++cs.htm" rel="nofollow noreferrer">C++ Coding Standards</a>: </p>
<blockquote>
<p>"Develop a practical, consistent, and rational error handling policy early in design, and then stick to it."</p>
</blockquote>
| 40,395
|
<p>What are the best SNMP libraries to use with .NET? Specifically for listening for traps or sending set or get requests.</p>
|
<p>I am using the <a href="http://www.codeplex.com/sharpsnmplib" rel="noreferrer">Sharp SNMP Suite (#SNMP)</a> : LGPL, Mono compatible, developed in C# 3.0, has very good API.</p>
|
<p>I've personally used Adventnet's <a href="http://www.webnms.com/net-snmp/index.html" rel="nofollow noreferrer">.NET SNMP API</a> for snmp work. It's now been renamed to WebNMS. I have code running based on this API several places, that has just worked and keeps on working 24/7.</p>
<p>Recommended for lots of examples and stability. Also it's fast. Seems though that there are several other .NET SNMP libraries that have come since I used SNMP last that might be worth checking out. ex: #SNMP, which has been referenced to in other replies.</p>
| 17,668
|
<p>I have some scripts that ought to have stopped running but hang around forever. Is there some way I can figure out what they're writing to STDOUT and STDERR in a readable way?</p>
<p>I tried, for example, to do:</p>
<pre><code>$ tail -f /proc/(pid)/fd/1
</code></pre>
<p>but that doesn't really work. It was a long shot anyway.</p>
<p>Any other ideas? </p>
<p><code>strace</code> on its own is quite verbose and unreadable for seeing this.</p>
<p>Note: I am <em>only</em> interested in their output, not in anything else. I'm capable of figuring out the other things on my own; this question is only focused on getting access to stdout and stderr of the running process <em>after</em> starting it.</p>
|
<p>Since I'm not allowed to edit Jauco's answer, I'll give the full answer that worked for me (Russell's page relies on un-guaranteed behaviour that, if you close file descriptor 1 for STDOUT, the next <code>creat</code> call will open FD 1.</p>
<p>So, run a simple endless script like this:</p>
<pre><code>import time
while True:
print 'test'
time.sleep(1)
</code></pre>
<p>Save it to test.py, run with</p>
<pre><code>$ python test.py
</code></pre>
<p>Get the PID:</p>
<pre><code>$ ps auxw | grep test.py
</code></pre>
<p>Now, attach <code>gdb</code>:</p>
<pre><code>$ gdb -p (pid)
</code></pre>
<p>and do the <code>fd</code> magic:</p>
<pre><code>(gdb) call creat("/tmp/stdout", 0600)
$1 = 3
(gdb) call dup2(3, 1)
$2 = 1
</code></pre>
<p>Now you can <code>tail /tmp/stdout</code> and see the output that used to go to STDOUT.</p>
|
<p>You don't state your operating system, but I'm going to take a stab and say "Linux".</p>
<p>Seeing what is being written to stderr and stdout is probably not going to help. If it is useful, you could use tee(1) before you start the script to take a copy of stderr and stdout.</p>
<p>You can use ps(1) to look for wchan. This tells you what the process is waiting for. If you look at the strace output, you can ignore the bulk of the output and identify the last (blocked) system call. If it is an operation on a file handle, you can go backwards in the output and identify the underlying object (file, socket, pipe, etc.) From there the answer is likely to be clear.</p>
<p>You can also send the process a signal that causes it to dump core, and then use the debugger and the core file to get a stack trace.</p>
| 31,050
|
<p>How do I access a page's HTTP response headers via JavaScript?</p>
<p>Related to <a href="https://stackoverflow.com/questions/220149/how-do-i-access-the-http-request-header-fields-via-javascript"><strong>this question</strong></a>, which was modified to ask about accessing two specific HTTP headers.</p>
<blockquote>
<p><strong>Related:</strong><br>
<a href="https://stackoverflow.com/questions/220149/how-do-i-access-the-http-request-header-fields-via-javascript">How do I access the HTTP request header fields via JavaScript?</a></p>
</blockquote>
|
<p>Unfortunately, there isn't an API to give you the HTTP response headers for your initial page request. That was the original question posted here. It has been <a href="https://stackoverflow.com/questions/12258705/how-can-i-read-the-current-headers-without-making-a-new-request-with-js">repeatedly asked</a>, too, because some people would like to get the actual response headers of the original page request without issuing another one.</p>
<h1><br/>For AJAX Requests:</h1>
<p>If an HTTP request is made over AJAX, it is possible to get the response headers with the <strong><code>getAllResponseHeaders()</code></strong> method. It's part of the XMLHttpRequest API. To see how this can be applied, check out the <em><code>fetchSimilarHeaders()</code></em> function below. Note that this is a work-around to the problem that won't be reliable for some applications.</p>
<pre><code>myXMLHttpRequest.getAllResponseHeaders();
</code></pre>
<ul>
<li><p>The API was specified in the following candidate recommendation for XMLHttpRequest: <a href="http://www.w3.org/TR/XMLHttpRequest/#the-getresponseheader-method" rel="noreferrer">XMLHttpRequest - W3C Candidate Recommendation 3 August 2010</a></p>
</li>
<li><p>Specifically, the <code>getAllResponseHeaders()</code> method was specified in the following section: <a href="http://www.w3.org/TR/XMLHttpRequest/#the-getallresponseheaders()-method" rel="noreferrer">w3.org: <code>XMLHttpRequest</code>: the <code>getallresponseheaders()</code> method</a></p>
</li>
<li><p>The MDN documentation is good, too: <a href="https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest" rel="noreferrer">developer.mozilla.org: <code>XMLHttpRequest</code></a>.</p>
</li>
</ul>
<p>This will not give you information about the original page request's HTTP response headers, but it could be used to make educated guesses about what those headers were. More on that is described next.</p>
<h1><br/>Getting header values from the Initial Page Request:</h1>
<p>This question was first asked several years ago, asking specifically about how to get at the original HTTP response headers for the <em>current page</em> (i.e. the same page inside of which the javascript was running). This is quite a different question than simply getting the response headers for any HTTP request. For the initial page request, the headers aren't readily available to javascript. Whether the header values you need will be reliably and sufficiently consistent if you request the same page again via AJAX will depend on your particular application.</p>
<p>The following are a few suggestions for getting around that problem.</p>
<h2><br/>1. Requests on Resources which are largely static</h2>
<p>If the response is largely static and the headers are not expected to change much between requests, you could make an AJAX request for the same page you're currently on and assume that they're they are the same values which were part of the page's HTTP response. This could allow you to access the headers you need using the nice XMLHttpRequest API described above.</p>
<pre><code>function fetchSimilarHeaders (callback) {
var request = new XMLHttpRequest();
request.onreadystatechange = function () {
if (request.readyState === XMLHttpRequest.DONE) {
//
// The following headers may often be similar
// to those of the original page request...
//
if (callback && typeof callback === 'function') {
callback(request.getAllResponseHeaders());
}
}
};
//
// Re-request the same page (document.location)
// We hope to get the same or similar response headers to those which
// came with the current page, but we have no guarantee.
// Since we are only after the headers, a HEAD request may be sufficient.
//
request.open('HEAD', document.location, true);
request.send(null);
}
</code></pre>
<p>This approach will be problematic if you truly have to rely on the values being consistent between requests, since you can't fully guarantee that they are the same. It's going to depend on your specific application and whether you know that the value you need is something that won't be changing from one request to the next.</p>
<h2><br/>2. Make Inferences</h2>
<p>There are <strong>some BOM properties</strong> (Browser Object Model) which the browser determines by looking at the headers. Some of these properties reflect HTTP headers directly (e.g. <code>navigator.userAgent</code> is set to the value of the HTTP <code>User-Agent</code> header field). By sniffing around the available properties you might be able to find what you need, or some clues to indicate what the HTTP response contained.</p>
<h2><br/>3. Stash them</h2>
<p>If you control the server side, you can access any header you like as you construct the full response. Values could be passed to the client with the page, stashed in some markup or perhaps in an inlined JSON structure. If you wanted to have every HTTP request header available to your javascript, you could iterate through them on the server and send them back as hidden values in the markup. It's probably not ideal to send header values this way, but you could certainly do it for the specific value you need. This solution is arguably inefficient, too, but it would do the job if you needed it.</p>
|
<p>This is an old question. Not sure when support became more broad, but <code>getAllResponseHeaders()</code> and <code>getResponseHeader()</code> appear to now be fairly standard: <a href="http://www.w3schools.com/xml/dom_http.asp" rel="nofollow">http://www.w3schools.com/xml/dom_http.asp</a></p>
| 27,116
|
<p>I find the autoindent style of Notepad++ a little weird: when I am typing on an indented line, I <em>do</em> want it to indent the next line after I press Enter (this it does properly). However, when I am on an empty line (no indentation, no characters) and I press Enter, it indents the next line, using the same indentation as the last non-empty line. I find this extremely annoying; have you ever encountered this problem and do you know how to fix it?</p>
<p>(Note: I'm editing HTML/PHP files.)</p>
|
<p>1) First install NppAutoIndent plugin if you don't have it.</p>
<blockquote>
<p>Plugins > Plugin Manager > Show Plugin Manager, then <strong>install NppAutoIndent</strong> from the "Available" tab of that menu.</p>
</blockquote>
<p>2) This behavior can be turned off by doing:</p>
<blockquote>
<p>Plugins > NppAutoIndent > Previous line</p>
</blockquote>
<p>3) If this option is disabled, you may need to first check this option:</p>
<blockquote>
<p>Plugins > NppAutoIndent > Ignore language</p>
</blockquote>
|
<p>To be honest, this to me seems expected behaviour. Blank lines are used a lot by myself to break up the code to make it more readable, having the program make me have to tab out again would be VERY annoying. </p>
<p>I can understand this as a frustration with something like Python, but not with PHP... Though, before braces etc etc this might be annoying.</p>
<p>Try out <a href="http://www.activestate.com/Products/komodo_ide/komodo_edit.mhtml" rel="nofollow noreferrer">Komodo Edit</a> however, it's free, and I've found that it generally has been the best for auto-indenting for me. It seems to have learnt my coding style (or have the options in it for all coding styles and it picks up what you're using) and automatically indents everything correctly.</p>
<p>Edit: As you've noted in your reply, the issue is with "trailing whitespace" - I don't know Notepad++ too well, but most modern editors designed for coding have a "strip trailing whitespace on save" option (I know Komodo does!)</p>
| 14,457
|
<p>I need to update a <code>combobox</code> with a new value so it changes the reflected text in it. The cleanest way to do this is after the <code>combobox</code>has been initialised and with a message.</p>
<p>So I am trying to craft a <code>postmessage</code> to the hwnd that contains the <code>combobox</code>.</p>
<p>So if I want to send a message to it, changing the currently selected item to the nth item, what would the <code>postmessage</code> look like?</p>
<p>I am guessing that it would involve <code>ON_CBN_SELCHANGE</code>, but I can't get it to work right.</p>
|
<p>You want <a href="http://msdn.microsoft.com/en-us/library/bb856484(VS.85).aspx" rel="nofollow noreferrer">ComboBox_SetCurSel</a>:</p>
<pre><code>ComboBox_SetCurSel(hWndCombo, n);
</code></pre>
<p>or if it's an MFC CComboBox control you can probably do:</p>
<pre><code>m_combo.SetCurSel(2);
</code></pre>
<p>I would imagine if you're doing it manually you would also want SendMessage rather than PostMessage. CBN_SELCHANGE is the notification that the control sends <em>back to you</em> when the selection is changed.</p>
<p>Finally, you might want to add the c++ tag to this question.</p>
|
<p>if you fx want to change the title - which is the line shown when combobox is closed, then you can do following:</p>
<p>m_ComboBox.DeleteString(0); // first delete previous if any, 0 = visual string
m_ComboBox.AddString(_T("Hello there"));</p>
<p>put this in fx. in OnCloseupCombo - when event close a dropdownbox fires </p>
<pre><code>ON_CBN_CLOSEUP(IDC_COMBO1, OnCloseupCombo)
</code></pre>
<p>This change is a new string not a selection of already assigned combobox elements</p>
| 8,382
|
<p>I am trying to use the <a href="http://www.javac.info/" rel="nofollow noreferrer">BGGA closures prototype</a> with an existing JDK 6 (standard on Mac OS X Leopard). The sample code I'm compiling is from a BGGA tutorial:</p>
<pre><code>public static void main(String[] args) {
// function with no arguments; return value is always 42
int answer = { => 42 }.invoke();
System.out.println(answer);
}
</code></pre>
<p>I have tried the following, and none work:</p>
<ol>
<li>Copied closures.jar to /System/Library/Frameworks/JavaVM.framework/Versions/1.6/Home/lib</li>
<li>Ran javac with -Xbootclasspath/a:/path/to/closures.jar</li>
<li>Ran javac with -J-Xbootclasspath/a:/path/to/closures.jar</li>
<li>Tried from eclipse ganymede by defining my own system library and attaching it to my project with code utilizing BGGA.</li>
</ol>
<p>In all four cases, I get compilation errors, indicating that the compiler did not pick up closures.jar on the bootstrap classpath. I'd really like to get this working from eclipse, or at the very least maven. Thanks!</p>
|
<p>The TAR file distribution includes a modified javac.bat with a complete command line, including "-source 7", which is probably what you are missing here.</p>
|
<p>Have you tried javac with -J-Xbootclasspath instead? That's used for passing -X arguments to the VM itself, which may be necessary for a change as low-level as this.</p>
<p>I very much doubt this will work with Eclipse, though. System libraries are for APIs, not language changes. You'd need to patch the Eclipse compiler.</p>
| 20,778
|
<p>I would like to use the task-list in Visual Studio but it really lacks almost any useful feature a task-list should provide. So I use <a href="http://www.abstractspoon.com/" rel="noreferrer">Todo-List</a> externally, to keep track of the things I need to get done. Would be nice to have it all in one place.</p>
<p>So does anyone know of a cool replacement Add-On for the tasklist in Visual Studio?</p>
<p>Thanks in advance!</p>
|
<p>For semi-immediate programming tasks I use TODO comments in code and ReSharper for Visual Studio to view them.</p>
<p>For longer-term tasks I use Team Foundation Server to record work items.</p>
<p>For non-programming tasks I use Google Calendar.</p>
|
<p>I don't know of an add-on (I use <a href="http://www.rememberthemilk.com/" rel="nofollow noreferrer">Remember The Milk</a> externally), but I think you are onto a good idea there.</p>
| 12,044
|
<p>I am trying to insert an image (jpg) in to a word document and the Selection.InlineShapes.AddPicture does not seem to be supported by win32old or I am doing something wrong. Has anyone had any luck inserting images. </p>
|
<p>You can do this by calling the Document.InlineShapes.AddPicture() method.</p>
<p>The following example inserts an image into the active document, before the second sentence.</p>
<pre><code> require 'win32ole'
word = WIN32OLE.connect('Word.Application')
doc = word.ActiveDocument
image = 'C:\MyImage.jpg'
range = doc.Sentences(2)
params = { 'FileName' => image, 'LinkToFile' => false,
'SaveWithDocument' => true, 'Range' => range }
pic = doc.InlineShapes.AddPicture( params )
</code></pre>
<p>Documentation on the AddPicture() method can be found <a href="http://msdn.microsoft.com/en-us/library/bb148763.aspx" rel="nofollow noreferrer">here</a>.</p>
<p>Additional details on automating Word with Ruby can be found <a href="http://rubyonwindows.blogspot.com/search/label/word" rel="nofollow noreferrer">here</a>.<br></p>
<p>This is the answer by David Mullet and can be found <a href="https://stackoverflow.com/questions/1316162/insert-image-in-doc-using-win32ole-library-of-ruby">here</a></p>
|
<p>Running on WinXP, Ruby 1.8.6, Word 2002/XP SP3, I recorded macros and translated them, as far as I could understand them, into this:</p>
<pre><code>require 'win32ole'
begin
word = WIN32OLE::new('Word.Application') # create winole Object
doc = word.Documents.Add
word.Selection.InlineShapes.AddPicture "C:\\pictures\\some_picture.jpg", false, true
word.ChangeFileOpenDirectory "C:\\docs\\"
doc.SaveAs "doc_with_pic.doc"
word.Quit
rescue Exception => e
puts e
word.Quit
ensure
word.Quit unless word.nil?
end
</code></pre>
<p>It seems to work. Any use?</p>
| 31,926
|
<p>I am thinking along the lines of replicating a web hosts PHP setup environment for offline local development. The idea is to parse the output of phpinfo() and write any setup values it contains into a local php.ini. I would imagine everything ism included in phpinfo and that certain things would only be specific to the environment it is running on (paths).</p>
|
<p>You will probably get more usable results from ini_get_all()</p>
<p><a href="http://us.php.net/manual/en/function.ini-get-all.php" rel="nofollow noreferrer">http://us.php.net/manual/en/function.ini-get-all.php</a></p>
<p>You could then traverse the associated array to reconstruct an ini file without the hassle of interpreting the output of phpinfo()</p>
|
<p>It's quite likely to just be a stock install. Even then, I'd still want to make the local development environment subtly different to the live php.ini, to ensure that it showed all errors that were being produced (as opposed to hiding, or just logging them on the live site).</p>
| 12,502
|
<p>I want to create a component that allows us to have compound keyboard shortcuts associated with an arbitrary command, like the Visual Studio IDE and Microsoft Office do.</p>
<p>That is, keyboard shortcuts consisting of a sequence of multiple keystrokes, such as <kbd>Ctrl</kbd> + <kbd>W</kbd> + <kbd>C</kbd>. In Visual Studio this opens the class-view. When the first set of the keys is pressed (<kbd>Ctrl</kbd> + <kbd>W</kbd>) the message "(Ctrl + W) was pressed. Waiting for the second key of the chord..." appears in the status bar.</p>
|
<p>In answer to the question of <strong>keyboard chords</strong> specifically, I do not believe there is a ready-made option available to you at this point.</p>
<p>However, it should be simple enough to model. I would create a single class, perhaps <code>KeyboardChordProvider</code>. It will need to know about keyboard events at the form level. As stated elsewhere, the <code>Form.KeyPreview</code> property must be <code>true</code>. It may be enough for this provider to subscribe to the <code>Form.KeyPress</code> event. You could do all of this in the provider's constructor if you passed in the form.</p>
<p>You would need to register the potential keystrokes with the provider.</p>
<p>Internally this instance will track the current state. Whenever a keystroke is observed that represents the first key of the chord, you would update the provider's state and raise an event so that a subscriber could set text: <em>(CTRL+W) was pressed. Waiting for second key of chord...</em></p>
<p>If the next keystroke matches a potential secondary option, then you have a match and could raise a <code>ChordPressed</code> event containing the details of the strokes entered. Alternatively, you might just call a particular callback that was given to the provider at the time the chord was registered (to avoid having a switch statement or some other dispatch in the <code>ChordPressed</code> event handler).</p>
<p>If, at any time, a keystroke does not match a potential <em>next</em> option, then you would reset the state of the provider.</p>
<p>Internal to the provider you might model the possible keystrokes using a tree structure. The current state of the provider is just a particular tree node. At the beginning, the root node would be active. If a child matches a keystroke then it becomes the current node in anticipation of the next stroke. If the child was a leaf node, then an entire chord has matched and you would raise <code>ChordPressed</code> event (passing the chain of strokes that got you to that point) or invoke the callback stored in the leaf. Whenever no keystroke matches a child, reset back to making the root node active.</p>
<p>I think this design would achieve what you want.</p>
|
<p>Use the form's OnKeyPressed event and check if the desired key combination was pressed in the eventArgs argument </p>
| 23,334
|
<p>An application I am working on reads information from files to populate a database. Some of the characters in the files are non-English, for example accented French characters.</p>
<p>The application is working fine in Windows but on our Solaris machine it is failing to recognise the special characters and is throwing an exception. For example when it encounters the accented e in "Gérer" it says :-</p>
<pre> Encountered: "\u0161" (353), after : "\'G\u00c3\u00a9rer les mod\u00c3"</pre>
<p>(an exception which is thrown from our application)</p>
<p>I suspect that in order to stop this from happening I need to change the file.encoding property of the JVM. I tried to do this via System.setProperty() but it has not stopped the error from occurring.</p>
<p>Are there any suggestions for what I could do? I was thinking about setting the basic locale of the solaris platform in /etc/default/init to be UTF-8. Does anyone think this might help?</p>
<p>Any thoughts are much appreciated.</p>
|
<p>Try to use</p>
<pre><code>java -Dfile.encoding=UTF-8 ...
</code></pre>
<p>when starting the application in both systems.</p>
<p>Another way to solve the problem is to change the encoding from both system to UTF-8, but i prefer the first option (less intrusive on the system).</p>
<p>EDIT:</p>
<p>Check this answer on stackoverflow, It might help either:</p>
<p><a href="https://stackoverflow.com/questions/81323/changing-the-default-encoding-for-stringbyte">Changing the default encoding for String(byte[])</a></p>
|
<p>You can also set the encoding at the command line, like so <code>java -Dfile.encoding=utf-8</code>.</p>
| 31,234
|
<p>How can I deploy a custom authentication provider in MOSS 2007?</p>
<p>Is there any provided functionality to do this (like a Sharepoint feature)?</p>
<p>Or do I have to install it in the GAC on each box in the farm manually? </p>
|
<p>The usual approach for installing extensions like this is to use a feature, yes. However, you won't be using any specialized XML as this kind of extension is not catered for explicitly. So how can you do it? By using an essentially empty feature project that contains an Event Receiver assembly. The event receiver assembly is called automatically by sharepoint for 4 different events: install, uninstall, activate and deactivate. I suggest you hook the install and uninstall events to deploy your provider.</p>
<p><a href="http://msdn.microsoft.com/en-us/library/bb862634.aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/bb862634.aspx</a></p>
<p>Make sense?</p>
<p>-Oisin</p>
|
<p>The <a href="http://www.codeplex.com/Release/ProjectReleases.aspx?ProjectName=CKS&ReleaseId=7746" rel="nofollow noreferrer">Windows Live Authentication</a> feature of the Community Kit for Sharepoint provides a nice example (with source code) of creating a solution package with a custom authentication provider. A solution package can be deployed to all servers in the farm without manually touching them</p>
| 33,899
|
<p>I want to have a class which implements an interface, which specifies the specific subclass as a parameter.</p>
<pre><code>public abstract Task implements TaskStatus<Task> {
TaskStatus<T> listener;
protected complete() {
// ugly, unsafe cast
callback.complete((T) this);
}
}
public interface TaskStatus<T> {
public void complete(T task);
}
</code></pre>
<p>But instead of just task, or , I want to guarantee the type-arg used is that of the specific class extending this one.</p>
<p>So the best I've come up with is:</p>
<pre><code>public abstract Task<T extends Task> implements TaskStatus<T> {
}
</code></pre>
<p>You'd extend that by writing:</p>
<pre><code>public class MyTask extends Task<MyTask> {
}
</code></pre>
<p>But this would also be valid:</p>
<pre><code>public class MyTask extends Task<SomeOtherTask> {
}
</code></pre>
<p>And the invocation of callback will blow up with ClassCastException. So, is this approach just wrong and broken, or is there a right way to do this I've somehow missed?</p>
|
<p>It is not clear what you are trying to do inside of <code>Task</code>. However, if you define the generic class <code>Task<T></code> as follows:</p>
<pre><code>class Task<T extends Task<T>> { ... }
</code></pre>
<p>The following two are possible:</p>
<pre><code>class MyTask extends Task<MyTask> { ... }
class YourTask extends Task<MyTask> { ... }
</code></pre>
<p>But the following is prohibited:</p>
<pre><code>class MyTask extends Task<String> { ... }
</code></pre>
<p>The above definition of <code>Task</code> uses F-bounded polymorphism, a rather advanced feature. You can check the research paper "<a href="http://www.cs.utexas.edu/~wcook/papers/FBound89/CookFBound89.pdf" rel="nofollow noreferrer">F-bounded polymorphism for object-oriented programming</a>" for more information.</p>
|
<p>I'm having a little trouble understanding what you're trying to accomplish through this. Could you provide some more details?</p>
<p>My read of the code says you have these tasks which will be sub-classed and after the tasks are complete, the executing thread will call complete() on the task. At this point you want to call a callback and pass it the sub-class object. I think this is the problem. You are trying to put knowledge of the potential sub-classes into your abstract class which is a no-no.</p>
<p>This also raises the question of, if you could make this call, what is the callback going to do with the sub-class that would be different from the superclass?</p>
| 18,605
|
<p>I've been told that code such as:</p>
<pre><code>for (int i = 0; i < x.length(); i++) {
// blah
}
</code></pre>
<p>is actually O(n^2) because of the repeated calls to <code>x.length()</code>. Instead I should use:</p>
<pre><code>int l = x.length();
for (int i = 0; i < l; i++) {
// blah
}
</code></pre>
<p>Is this true? Is string length stored as a private integer attribute of the String class? Or does <code>String.length()</code> really walk the whole string just to determine its length?</p>
|
<p>No, the length of a java string is O(1) because java's string class stores the length as a field.</p>
<p>The advice you've received is true of C, amongst other languages, but not java. C's strlen walks the char array looking for the end-of-string character. Joel's talked about it on the podcast, but in the context of C.</p>
|
<p>According to <a href="http://www.docjar.com/html/api/java/lang/String.java.html" rel="nofollow noreferrer">this</a>, the length is a field of the String object.</p>
| 31,778
|
<p>I've read the documentation on <a href="http://msdn.microsoft.com/en-us/library/ms776420(VS.85).aspx" rel="noreferrer">WideCharToMultiByte</a>, but I'm stuck on this parameter:</p>
<pre><code>lpMultiByteStr
[out] Pointer to a buffer that receives the converted string.
</code></pre>
<p>I'm not quite sure how to properly initialize the variable and feed it into the function</p>
|
<p>Here's a couple of functions (based on Brian Bondy's example) that use WideCharToMultiByte and MultiByteToWideChar to convert between std::wstring and std::string using utf8 to not lose any data.</p>
<pre><code>// Convert a wide Unicode string to an UTF8 string
std::string utf8_encode(const std::wstring &wstr)
{
if( wstr.empty() ) return std::string();
int size_needed = WideCharToMultiByte(CP_UTF8, 0, &wstr[0], (int)wstr.size(), NULL, 0, NULL, NULL);
std::string strTo( size_needed, 0 );
WideCharToMultiByte (CP_UTF8, 0, &wstr[0], (int)wstr.size(), &strTo[0], size_needed, NULL, NULL);
return strTo;
}
// Convert an UTF8 string to a wide Unicode String
std::wstring utf8_decode(const std::string &str)
{
if( str.empty() ) return std::wstring();
int size_needed = MultiByteToWideChar(CP_UTF8, 0, &str[0], (int)str.size(), NULL, 0);
std::wstring wstrTo( size_needed, 0 );
MultiByteToWideChar (CP_UTF8, 0, &str[0], (int)str.size(), &wstrTo[0], size_needed);
return wstrTo;
}
</code></pre>
|
<p>Here is a <code>C</code> implementation of both <code>WideCharToMultiByte</code> and <code>MultiByteToWideChar</code>.
In both cases I ensure to tack a <code>null</code> character to the end of the destination buffers.</p>
<blockquote>
<p>MultiByteToWideChar does not null-terminate an output string if the input string length is explicitly specified without a terminating null character.</p>
</blockquote>
<p>And</p>
<blockquote>
<p>WideCharToMultiByte does not null-terminate an output string if the input string length is explicitly specified without a terminating null character.</p>
</blockquote>
<p>Even if someone specifies <code>-1</code> and passes in a <code>null</code> terminated string I still allocate enough space for an additional <code>null</code> character because for my use case this was not an issue.</p>
<pre><code>wchar_t* utf8_decode( const char* str, int nbytes ) {
int nchars = 0;
if ( ( nchars = MultiByteToWideChar( CP_UTF8,
MB_ERR_INVALID_CHARS, str, nbytes, NULL, 0 ) ) == 0 ) {
return NULL;
}
wchar_t* wstr = NULL;
if ( !( wstr = malloc( ( ( size_t )nchars + 1 ) * sizeof( wchar_t ) ) ) ) {
return NULL;
}
wstr[ nchars ] = L'\0';
if ( MultiByteToWideChar( CP_UTF8, MB_ERR_INVALID_CHARS,
str, nbytes, wstr, ( size_t )nchars ) == 0 ) {
free( wstr );
return NULL;
}
return wstr;
}
char* utf8_encode( const wchar_t* wstr, int nchars ) {
int nbytes = 0;
if ( ( nbytes = WideCharToMultiByte( CP_UTF8, WC_ERR_INVALID_CHARS,
wstr, nchars, NULL, 0, NULL, NULL ) ) == 0 ) {
return NULL;
}
char* str = NULL;
if ( !( str = malloc( ( size_t )nbytes + 1 ) ) ) {
return NULL;
}
str[ nbytes ] = '\0';
if ( WideCharToMultiByte( CP_UTF8, WC_ERR_INVALID_CHARS,
wstr, nchars, str, nbytes, NULL, NULL ) == 0 ) {
free( str );
return NULL;
}
return str;
}
</code></pre>
| 26,547
|
<p>Does anyone have experience with developing for Sharepoint 2003 using Visual Studio 2008?</p>
<p>I need to upgrade to VS2008 because of Vista issues but need to support Sharepoint 2003 webparts. The webparts are all pretty simple. Will I be able to support those webparts using VS2008?</p>
|
<p>AFAIK VS2008 only allows you to build .NET 2.0/3.0 out of the box, but...</p>
<p>I have VS2005 projects spitting out .NET 1.1 assemblies for WSSv2/SPS2003 and .NET 2.0 for WSSv3/MOSS2007 using MSBEE and I would think that this is possible in VS2008 also.</p>
<p>You will need to use MSBEE
<a href="http://www.codeplex.com/Wiki/View.aspx?ProjectName=MSBee" rel="nofollow noreferrer">http://www.codeplex.com/Wiki/View.aspx?ProjectName=MSBee</a></p>
<p><a href="http://devlicio.us/blogs/ziemowit_skowronski/archive/2008/08/22/working-with-net-1-1-in-visual-studio-2008-and-team-server.aspx" rel="nofollow noreferrer">Working with .NET 1.1 with Visual Studio 2008</a></p>
<p>You will also need to master some MSBUILD ninja moves to keep a 1 step build process and keep yourself sane
<a href="http://brennan.offwhite.net/blog/2006/11/30/7-steps-to-msbuild/" rel="nofollow noreferrer">http://brennan.offwhite.net/blog/2006/11/30/7-steps-to-msbuild/</a></p>
<p>I will be upgrading to VS2008 in the next few weeks and will post an update here.</p>
|
<p>SharePoint 2003 is built on top of .NET 1.1 and only Visual Studio 2003 supports it. I would recommend you not to use anything else. </p>
<p>I would advise you to create a virtual machine with SharePoint 2003 and Visual Studio 2003 and develop everything inside VM. This approach can be helpful if you are working on a project for a customer you can use this machine as replica of your customers environment.</p>
| 30,124
|
<p>Is there anyone who has used or looked into using Jitterbit as well as BizTalk? If so, what are some pros and cons of each, and which one did you go with as your final solution?</p>
<p>Specifically, I'm looking for SAP integration, but any input would be appreciated.</p>
|
<p>I've done a fair bit of integration with SAP, starting with the old SAP DCOM connector. More recently I've been involved in the selection of an integration platform to serve in an Enterprise Service Bus pattern.</p>
<p>We did web service samples to connect to SAP on a number of platforms, including BizTalk, Mule, Netweaver, Webmethods and Tibco. Webmethods won out based on licensing and capability, though BizTalk and Netweaver both had very high marks.</p>
<p>Jitterbit was not part of the evaluation - in fact I had to look it up to be sure I understood your question.</p>
<p>If your goal is just to be able to call an RFC, the .NET SAP connector works well.</p>
<p>If your goal is to expose a web service to wrapper a process in SAP, then BizTalk is good, but I recommend you see if your organization already has netweaver licensed as there are many web services available directly from SAP with no coding.</p>
<p>My recommendation is to avoid Jitterbug and Mule for the enterprise for now - unless Open Source is actually a popular thing at your place of employment. Netweaver and BizTalk are very robust, polished products.</p>
<p>If you are looking for something you can ship easily, then Jitterbug may make more sense. Though generally I'd recommend you define it as a web service call, and look to your customers technology stack for the most appropriate integration technique.</p>
<p>More context of what you are looking to achieve will enable a more accurate answer. </p>
|
<p>I will say it simply, I have been using biztalk and was one of the people that helped validate the 2006 training course. Biztalk by far one the best server applications for Business process that is available today. You do also have to factor in the price point is ridiculously low compared to what else is out there.</p>
| 49,513
|
<p>I understand the overall meaning of pointers and references(or at least I think i do), I also understand that when I use <b>new</b> I am dynamically allocating memory.</p>
<p>My question is the following:</p>
<p>If i were to use <code>cout << &p</code>, it would display the "virtual memory location" of <code>p</code>.
Is there a way in which I could manipulate this "virtual memory location?"</p>
<p>For example, the following code shows an array of <code>int</code>s.</p>
<p>If I wanted to show the value of <code>p[1]</code> and I knew the "virtual memory location" of <code>p</code>, could I somehow do "<code>&p + 1</code>" and obtain the value of <code>p[1]</code> with <code>cout << *p</code>, which will now point to the second element in the array?</p>
<pre><code>int *p;
p = new int[3];
p[0] = 13;
p[1] = 54;
p[2] = 42;
</code></pre>
|
<p>Sure, you can manipulate the pointer to access the different elements in the array, but you will need to manipulate the content of the pointer (i.e. the address of what p is pointing to), rather than the address of the pointer itself.</p>
<pre><code>int *p = new int[3];
p[0] = 13;
p[1] = 54;
p[2] = 42;
cout << *p << ' ' << *(p+1) << ' ' << *(p+2);
</code></pre>
<p>Each addition (or subtraction) mean the subsequent (prior) element in the array. If p points to a 4 byte variable (e.g. <em>int</em> on typical 32-bits PCs) at address say 12345, p+1 will point to 12349, and not 12346. Note you want to change the value of what p contains before dereferencing it to access what it points to.</p>
|
<p>Think of "pointer types" in C and C++ as laying down a very long, logical <strong>row of cells</strong> superimposed on the bytes in the memory space of the CPU, starting at byte 0. The width of each cell, in bytes, depends on the "type" of the pointer. Each pointer type lays downs a row with differing cell widths. A <code>"int *"</code> pointer lays down a row of 4-byte cells, since the storage width of an int is 4 bytes. A <code>"double *"</code> lays down a 8-byte per-cell row; a <code>"struct foo *"</code> pointer lays down a row with each cell the width of a single <code>"struct foo"</code>, whatever that is. The "address" of any "thing" is the byte offset, starting at 0, of the cell in the row holding the "thing".<br><br><strong>Pointer arithmetic is based on cells in the row, not bytes.</strong> "<code>*(p+10)</code>" is a reference to the 10th cell past "p", where the cell size is determined by the type of p. If the type of "p" is "int", the address of "p+10" is 40 bytes past p; if p is a pointer to a struct 1000 bytes long, "p+10" is 10,000 bytes past p. (Note that the compiler gets to choose an optimal size for a struct that may be larger than what you'd think; this is due to "padding" and "alignment". The 1000 byte struct discussed might actually take 1024 bytes per cell, for example, so "p+10" would actually be 10,240 bytes past p.)</p>
| 13,282
|
<p>I'm building a basic search functionality, using LIKE (I'd be using fulltext but can't at the moment) and I'm wondering if MySQL can, on searching for a keyword (e.g. WHERE field LIKE '%word%') return 20 words either side of the keyword, as well?</p>
|
<p>You can do it all in the query using SUBSTRING_INDEX</p>
<pre><code>CONCAT_WS(
' ',
-- 20 words before
TRIM(
SUBSTRING_INDEX(
SUBSTRING(field, 1, INSTR(field, 'word') - 1 ),
' ',
-20
)
),
-- your word
'word',
-- 20 words after
TRIM(
SUBSTRING_INDEX(
SUBSTRING(field, INSTR(field, 'word') + LENGTH('word') ),
' ',
20
)
)
</code></pre>
<p>)</p>
|
<p>Use the INSTR() function to find the position of the word in the string, and then use SUBSTRING() function to select a portion of characters before and after the position.</p>
<p>You'd have to look out that your SUBSTRING instruction don't use negative values or you'll get weird results.</p>
<p>Try that, and report back.</p>
| 5,895
|
<p>I'm wondering if there's any way to write CSS specifically for Safari using only CSS. I know there has to be something out there, but I haven't found it yet.</p>
|
<p>I think the question is valid. I agree with the other responses, but it doesn't mean it's a terrible question. I've only ever had to use a Safari CSS hack once as a temporary solution and later got rid of it. I agree that you shouldn't have to target just Safari, but no harm in knowing how to do it.</p>
<p>FYI, this hack only targets Safari 3, and also targets Opera 9.</p>
<pre><code>@media screen and (-webkit-min-device-pixel-ratio:0) {
/* Safari 3.0 and Opera 9 rules here */
}
</code></pre>
|
<p>This really depends on what you are trying to do. Are you trying to do something special just in safari using some of the CSS3 features included or are you trying to make a site cross browser compliant?</p>
<p>If you are trying to make a site cross browser compliant I'd recommend writing the site to look good in safari/firefox/opera using correct CSS and then making changes for IE using conditional CSS includes in IE. This should (hopefully) give you compatibility for the future of browsers, which are getting better at following the CSS rules, and provide cross browser compatibility. <a href="http://creativebits.org/webdev/ie_conditional_css" rel="nofollow noreferrer">This is an example.</a></p>
<p>By using conditional stylesheets you can avoid hacks all together and target browsers.</p>
<p>If you are looking to do something special in safari check out <a href="http://trac.webkit.org/wiki/WebDevelopers" rel="nofollow noreferrer">this</a>.</p>
| 9,481
|
<p>When using a subdomain and trying to view anything related to current_user. user is sent to a new session page, the page shows the session is created and gives the option to logout. I can use no subdomain and it works fine.</p>
|
<p>Set it in your environment.rb (or environments/*.rb if you'll use different domains for each environment):</p>
<pre><code>ActionController::CgiRequest::DEFAULT_SESSION_OPTIONS.update( :session_domain => '.domain.com')
</code></pre>
|
<p>@jkrall - to add to that, the whole options hash moved to :key, :secret, and :domain vs :session_key, :session_domain, etc.</p>
| 40,054
|
<p>I have looked at the ability to use tabs in Vim (with <code>:tabe</code>, <code>:tabnew</code>, etc.) as a replacement for my current practice of having many files open in the same window in hidden buffers.</p>
<p>I would like every distinct file that I have open to always be in its own tab. However, there are some things that get in the way of this. How do I fix these:</p>
<ol>
<li><p>When commands like <code>gf</code> and <code>^]</code> jump to a location in another file, the file opens in a new buffer in the current tab. Is there a way to have all of these sorts of commands open the file in a new tab, or switch to the existing tab with the file if it is already open?</p></li>
<li><p>When switching buffers I can use
<code>:b <part of filename><tab></code>
and it will complete the names of files in existing buffers. <code><part of filename></code> can even be the middle of a filename instead of the beginning. Is there an equivalent for switching tabs?</p></li>
</ol>
|
<p>Stop, stop, stop.</p>
<p>This is not how Vim's tabs are designed to be used. In fact, they're misnamed. A better name would be "viewport" or "layout", because that's what a tab is—it's a different layout of windows of <em>all</em> of your existing buffers.</p>
<p>Trying to beat Vim into 1 tab == 1 buffer is an exercise in futility. Vim doesn't know or care and it will not respect it on all commands—in particular, anything that uses the quickfix buffer (<code>:make</code>, <code>:grep</code>, and <code>:helpgrep</code> are the ones that spring to mind) will happily ignore tabs and there's nothing you can do to stop that.</p>
<p>Instead: </p>
<ul>
<li><code>:set hidden</code><br>
If you don't have this set already, then do so. It makes vim work like every other multiple-file editor on the planet. You can have edited buffers that aren't visible in a window somewhere.</li>
<li>Use <code>:bn</code>, <code>:bp</code>, <code>:b #</code>, <code>:b name</code>, and <code>ctrl-6</code> to switch between buffers. I like <code>ctrl-6</code> myself (alone it switches to the previously used buffer, or <code>#ctrl-6</code> switches to buffer number <code>#</code>).</li>
<li>Use <code>:ls</code> to list buffers, or a plugin like <a href="https://github.com/fholgado/minibufexpl.vim" rel="noreferrer">MiniBufExpl</a> or <a href="http://www.vim.org/scripts/script.php?script_id=42" rel="noreferrer">BufExplorer</a>.</li>
</ul>
|
<p>relevant:
<a href="https://stackoverflow.com/questions/3297156/vim-can-global-marks-switch-tabs-instead-of-the-file-in-the-current-tab/71923358#71923358">Vim: can global marks switch tabs instead of the file in the current tab?</a></p>
<p>maybe useful to solve a little part of OP's problem:</p>
<pre><code> nno \ <Cmd>call To_global_mark()<cr>
fun! To_global_mark()
-tab drop /tmp/useless.md
exe 'normal! `' .. toupper(input("To global mark: "))
endf
</code></pre>
| 12,792
|
<p>I am troubleshooting an issue with IIS6 where all sites bound to ip addresses other than the default give an error message "network location cannot be reached" when trying to start any of these sites.</p>
<p>The nic has all the ip addresses configured.
When I do a httpcfg query iplisten, I see only the default ip address.
When I added them with httpcfg, then all the web sites stopped working so I figured I didn something wrong so I removed them.</p>
<p>Two questions:
1- Why are those websites refusing to start?
2- What should be in the result of httpcfg query iplisten? All ip addresses or just one?</p>
<p>The websites used to work fine and something has changed. I applied a few Windows updates but I am not sure if they broke anything (I doubt it.. otherwise hundreds of web hosting companies would be screaming)</p>
|
<p>The solution was to use httpcfg without specifying the port number. </p>
|
<p>Sometimes there are bugs wehn applying windows updates. One thing you might try is running aspnet_regiis /i or /c. I'm not sure if that's your problem but it's certainly worth a shot.</p>
| 18,766
|
<p>When an iPhone application manages its own preferences, rather than using a bundle, it seems to be common practice to style that view to mimic the System Preferences app: fields are grouped by light rectangles with rounded edges; titles and explanatory text are added to the space between. </p>
<p>What is best used to achieve this styling? My initial thoughts are a background image to the view, but is there a better way?</p>
|
<p>You need to use a UITableView with the "group" style. I've seen some applications that "fake" it with graphics, but doing it with the correct components isn't terribly tricky. The main downside being you can't do it all in Interface Builder.</p>
|
<p>The WordPress app does this. Look at the BlogDetail controller and nib. You'll see many UITableViewCells that are returned when the table asks for the row/section data from the controller.</p>
<p>You can find the code at the <a href="http://iphone.wordpress.org/contribute/" rel="nofollow noreferrer">Wordpress iPhone site</a>.</p>
| 41,460
|
<p>A programmer I know has a website that is fully Standards Compliant. It uses Unicode-encoded fully-validated XHTML 1.1 with CSS. The pages are frames-free, table-free and JavaScript-free.</p>
<p>He would like to be directed to a blogging tool that does not demand any particular database system or web server, but does create static pages that comply with the above standards and best practices and is itself a professionally finished native Windows application.</p>
<p>...and it should be able to produce an RSS feed as well.</p>
<p>Is there anything out there that comes close to this?</p>
|
<p>I can't see this being a problem - allowable comments are not specified in a DTD (as they're effectively for humans, not computers). Also, the DOM API (<a href="http://www.w3.org/TR/REC-DOM-Level-1/level-one-core.html" rel="noreferrer">http://www.w3.org/TR/REC-DOM-Level-1/level-one-core.html</a>) explicitly allows many comments directly under the document node (i.e. not the root HTML element, the logical document root), so any conforming browser should allow it.</p>
<p>This is not to say you won't find browsers or tools, especially older ones, that choke. But I'd be surprised if there were many.</p>
|
<p>Yes by all means. Any rendering engine (IE, Firefix, Opera, Safari, etc) will ignore any HTML comment tag completely regardless which position.</p>
| 47,756
|
<p>How would you write a regular expression to convert mark down into HTML? For example, you would type in the following:</p>
<pre><code>This would be *italicized* text and this would be **bold** text
</code></pre>
<p>This would then need to be converted to:</p>
<pre><code>This would be <em>italicized</em> text and this would be <strong>bold</strong> text
</code></pre>
<p>Very similar to the mark down edit control used by stackoverflow.</p>
<p><strong>Clarification</strong></p>
<p>For what it is worth, I am using C#. Also, these are the <strong>only</strong> real tags/markdown that I want to allow. The amount of text being converted would be less than 300 characters or so.</p>
|
<p>The best way is to find a version of the Markdown library ported to whatever language you are using (you did not specify in your question). </p>
<hr>
<p>Now that you have clarified that you only want STRONG and EM to be processed, and that you are using C#, I recommend you take a look at <a href="http://www.aspnetresources.com/blog/markdown_announced.aspx" rel="noreferrer">Markdown.NET</a> to see how those tags are implemented. As you can see, it is in fact two expressions. Here is the code:</p>
<pre><code>private string DoItalicsAndBold (string text)
{
// <strong> must go first:
text = Regex.Replace (text, @"(\*\*|__) (?=\S) (.+?[*_]*) (?<=\S) \1",
new MatchEvaluator (BoldEvaluator),
RegexOptions.IgnorePatternWhitespace | RegexOptions.Singleline);
// Then <em>:
text = Regex.Replace (text, @"(\*|_) (?=\S) (.+?) (?<=\S) \1",
new MatchEvaluator (ItalicsEvaluator),
RegexOptions.IgnorePatternWhitespace | RegexOptions.Singleline);
return text;
}
private string ItalicsEvaluator (Match match)
{
return string.Format ("<em>{0}</em>", match.Groups[2].Value);
}
private string BoldEvaluator (Match match)
{
return string.Format ("<strong>{0}</strong>", match.Groups[2].Value);
}
</code></pre>
|
<p>I came across the following <a href="http://kore-nordmann.de/blog/do_NOT_parse_using_regexp.html" rel="nofollow noreferrer">post</a> that recommends to not do this. In my case though I am looking to keep it simple, but thought I would post this per <a href="https://stackoverflow.com/users/11830/jop">jop's</a> recommendation in case someone else wanted to do this.</p>
| 13,592
|
<p>So I just interviewed two people today, and gave them "tests" to see what their skills were like. Both are entry level applicants, one of which is actually still in college. Neither applicant saw anything wrong with the following code.</p>
<p>I do, obviously or I wouldn't have picked those examples. <strong>Do you think these questions are too harsh for newbie programmers?</strong></p>
<p>I guess I should also note neither of them had much experience with C#... but I don't think the issues with these are language dependent. </p>
<pre><code>//For the following functions, evaluate the code for quality and discuss. E.g.
//E.g. could it be done more efficiently? could it cause bugs?
public void Question1()
{
int active = 0;
CheckBox chkactive = (CheckBox)item.FindControl("chkactive");
if (chkactive.Checked == true)
{
active = 1;
}
dmxdevice.Active = Convert.ToBoolean(active);
}
public void Question2(bool IsPostBack)
{
if (!IsPostBack)
{
BindlistviewNotification();
}
if (lsvnotificationList.Items.Count == 0)
{
BindlistviewNotification();
}
}
//Question 3
protected void lsvnotificationList_ItemUpdating(object sender, ListViewUpdateEventArgs e)
{
ListViewDataItem item = lsvnotificationList.Items[e.ItemIndex];
string Email = ((TextBox)item.FindControl("txtEmailAddress")).Text;
int id = Convert.ToInt32(((HiddenField)item.FindControl("hfID")).Value);
ESLinq.ESLinqDataContext db = new ESLinq.ESLinqDataContext();
var compare = from N in db.NotificationLists
where N.ID == id
select N;
if (compare.Count() > 0)
{
lblmessage.Text = "Record Already Exists";
}
else
{
ESLinq.NotificationList Notice = db.NotificationLists.Where(N => N.ID == id).Single();
Notice.EmailAddress = Email;
db.SubmitChanges();
}
lsvnotificationList.EditIndex = -1;
BindlistviewNotification();
}
</code></pre>
|
<p>I don't typically throw code at someone interviewing for a position and say "what's wrong?", mainly because I'm not convinced it really finds me the best candidate. Interviews are sometimes stressful and a bit overwhelming and coders aren't always on their A-game.</p>
<p>Regarding the questions, honestly I think that if I didn't know C#, I'd have a hard time with question 3. Question #2 is a bit funky too. Yes, I get what you're going for there but what if the idea was that BindlistviewNotification() was supposed to be called twice? It isn't clear and one could argue there isn't enough info. Question 1 is easy enough to clean up, but I'm not convinced even it proves anything for an entry-level developer without a background in C#.</p>
<p>I think I'd rather have something talk me through how they'd attack a problem (in pseudo-code or whatever language they are comfortable with) and assess them from that. Just a personal opinion, though.</p>
|
<p>Q1 also has a potential InvalidCastException on the <code>item.FindControl()</code> line.</p>
<p>I don't think Q1 or Q2 are outside the realms of being too hard, even for non C# users. Any level code should be able to see that you should be using a boolean for active, and only using one if statement.</p>
<p>Q3 though atleast needs comments as someone else noted. That's not basic code, especially if you're targeting non-C# users with it too.</p>
| 18,227
|
<p>This came up in <a href="https://stackoverflow.com/questions/101268/hidden-features-of-python">Hidden features of Python</a>, but I can't see good documentation or examples that explain how the feature works.</p>
|
<p><code>Ellipsis</code>, or <code>...</code> is not a hidden feature, it's just a constant. It's quite different to, say, javascript ES6 where it's a part of the language syntax. No builtin class or Python language constuct makes use of it. </p>
<p>So the syntax for it depends entirely on you, or someone else, having written code to understand it.</p>
<p>Numpy uses it, as stated in the <a href="http://wiki.scipy.org/Numpy_Example_List_With_Doc#head-490d781b49b68b300eedaef32369fae7d58627fb" rel="noreferrer">documentation</a>. Some examples <a href="http://wiki.scipy.org/Tentative_NumPy_Tutorial#head-864862d3f2bb4c32f04260fac61eb4ef34788c4c" rel="noreferrer">here</a>.</p>
<p>In your own class, you'd use it like this:</p>
<pre><code>>>> class TestEllipsis(object):
... def __getitem__(self, item):
... if item is Ellipsis:
... return "Returning all items"
... else:
... return "return %r items" % item
...
>>> x = TestEllipsis()
>>> print x[2]
return 2 items
>>> print x[...]
Returning all items
</code></pre>
<p>Of course, there is the <a href="https://docs.python.org/library/constants.html#Ellipsis" rel="noreferrer" title="Ellipsis">python documentation</a>, and <a href="https://docs.python.org/reference/expressions.html#grammar-token-slicing" rel="noreferrer">language reference</a>. But those aren't very helpful. </p>
|
<p>As stated in other answers, it can be used for creating slices.
Useful when you do not want to write many full slices notations (<code>:</code>), or when you are just not sure on what is dimensionality of the array being manipulated.</p>
<p>What I thought important to highlight, and that was missing on the other answers, is that it can be used even when there is no more dimensions to be filled.</p>
<p>Example:</p>
<pre><code>>>> from numpy import arange
>>> a = arange(4).reshape(2,2)
</code></pre>
<p>This will result in error:</p>
<pre><code>>>> a[:,0,:]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: too many indices for array
</code></pre>
<p>This will work:</p>
<pre><code>a[...,0,:]
array([0, 1])
</code></pre>
| 14,409
|
<p>Can I somehow disable spell-checking on HTML textfields (as seen in e.g. Safari)?</p>
|
<p><strong>Update</strong>: As suggested by a commenter (additional credit to <a href="https://stackoverflow.com/questions/3416867/how-can-i-disable-the-spell-checker-on-text-inputs-on-the-iphone">How can I disable the spell checker on text inputs on the iPhone</a>), use this to handle all desktop and mobile browsers.</p>
<pre><code><tag autocomplete="off" autocorrect="off" autocapitalize="off" spellcheck="false"/>
</code></pre>
<p>Original answer: Javascript cannot override user settings, so unless you use another mechanism other than textfields, this is not (or shouldn't be) possible.</p>
|
<p>If you have created your HTML element dynamically, you'll want to disable the attribute via JS. There is a little trap however:</p>
<p>When setting <code>elem.contentEditable</code> you can use either the boolean <code>false</code> or the string <code>"false"</code>. But when you set <code>elem.spellcheck</code>, you can only use the boolean - for some reason. Your options are thus:</p>
<pre><code>elem.spellcheck = false;
</code></pre>
<p>Or the option <a href="https://stackoverflow.com/a/64810105/6151750">Mac</a> provided in his answer:</p>
<pre><code>elem.setAttribute("spellcheck", "false"); // Both string and boolean work here.
</code></pre>
| 31,774
|
<p>I am experiencing a minor layer separation when printing a body for a tipping-bucket rain gauge, which is basically a hollow tube with thin walls (3 mm). I am using <strong>Prusa I3 MK2</strong> and a <strong>Fillamentum ABS</strong> white plastic. The model has been sliced in <strong>Siplify 3D</strong> with the following settings:</p>
<ul>
<li>layer height: 0.2 mm</li>
<li>perimeter shells: 3 layers (almost entirely
fills up the wall)</li>
<li>extruder temperature: 230 °C</li>
<li>printing speed: default - 50 mm/s, outline - 35 mm/s, infill - 35 mm/s</li>
</ul>
<p>Is it possible to prevent the irregular and layer separation by adjusting some of the settings, and not significantly increasing the printing time, which is already 13 hours?</p>
<p>PICTURES:</p>
<p><a href="https://i.stack.imgur.com/vNvWx.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/vNvWx.jpg" alt="enter image description here"></a></p>
<p><a href="https://i.stack.imgur.com/93hzZ.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/93hzZ.jpg" alt="enter image description here"></a></p>
|
<p>The best thing you can do for a large ABS print is to have an enclosure heated to 50C or better. For example, see <a href="https://www.3dhubs.com/talk/thread/enclosed-vs-open-printers" rel="nofollow noreferrer">this</a>, <a href="https://www.reddit.com/r/3Dprinting/comments/2ynb78/heated_build_enclosure_temperatures/?st=j6dk32oh&sh=2a550305" rel="nofollow noreferrer">this</a>, <a href="http://www.shapingbits.com/3d-printing-guide/abs-3d-printing/" rel="nofollow noreferrer">this</a>, and other search results.</p>
|
<p>increasing the temperature by 5 to 10° as well as, increasing the layer thickness to "0.3" or "0.35" may assist ,additionally increasing the flow rate of the filament, by a small margin at most 10%. These options should improve the quality of the print as they improve the layer adhesion, however none of these options will completely solve the problem.</p>
<p>alternatively you can repair the current print. In order to do this you will need to use something cot such as a soldering iron with a variable temperature, to melt and rejoined the layers. similarly you can use a 3d pen to apply additional plastic across the sections of separation in order to repair it.</p>
| 668
|
<p>How do you install Boost on MacOS?
Right now I can't find bjam for the Mac.</p>
|
<p>Download <a href="https://www.macports.org/" rel="noreferrer">MacPorts</a>, and run the following command:</p>
<pre><code>sudo port install boost
</code></pre>
|
<p>you can download bjam for OSX (or any other OS) <a href="http://sourceforge.net/project/showfiles.php?group_id=7586&package_id=72941" rel="nofollow noreferrer">here</a></p>
| 12,989
|
<p>I have a Visual Studio 2005 solution (.sln) with a mix of .NET and C++ projects. What is the best way to generate the .build file I will need to run my build process with NAnt. I'm new to using NAnt, and I'm not sure how to set it up. Will I have to update the .build file manually every time there is a new source file in any of the projects? Is there a tool that will generate the files for NAnt from the .sln and studio project files?</p>
|
<p>There is no way that I know of to generate a .build file from an sln. There should be decent examples of .build files at <a href="http://nant.sourceforge.net" rel="nofollow noreferrer">http://nant.sourceforge.net</a>.</p>
<p>That being said there are two ways to build a .sln file from NAnt.</p>
<ul>
<li>checkout nant.sourceforge.net or
nant-contrib for built in or
extended tasks to do this </li>
<li>use an "exec" task to shell out
msbuild.exe
to build the sln.</li>
</ul>
<p>msbuild.exe has native support for sln files. You can build an sln file from the command line as follows:</p>
<pre><code>msbuild.exe /p:Configuration=Debug /t:rebuild MySolution.sln
</code></pre>
<p>msbuild.exe can be found in your .NET Framework directory (e.g. C:\WINDOWS\Microsoft.NET\Framework\vX.XX.XXXX)</p>
|
<p>With nant you will have to use the EXEC command to shell out to msbuild for the solution files. </p>
<p>Others have been experiencing the same issues.</p>
| 43,951
|
<p>Is there any website/service which will enable me to add RSS subscription to any website?</p>
<p>This is for my company I work. We have a website which displays company related news. These news are supplied by an external agency and they gets updated to our database automatically. Our website picks up random/new news and displays them. We are looking at adding a "Subscribe via RSS" button to our website.</p>
|
<p>If you have the data in your database, creating one yourself is fairly straight forward - there's a simple tutorial <a href="http://www.downes.ca/cgi-bin/page.cgi?post=56" rel="nofollow noreferrer">here</a>.</p>
<p>Once you've set up a feed, in the <head> of your page, you put text like:</p>
<pre><code><link rel="alternate" title="RSS Feed"
href="http://www.example.com/rss-feed/latest/" type="application/rss+xml" />
</code></pre>
<p>This allows the feed to be "auto-discovered" by your user's browser (e.g. the RSS icon appears in the address bar in FF).</p>
|
<p>Write a webhandler that exposes the content of the database as an RSS feed.</p>
| 11,894
|
<p>How can one programmatically sort a union query when pulling data from two tables? For example,</p>
<pre><code>SELECT table1.field1 FROM table1 ORDER BY table1.field1
UNION
SELECT table2.field1 FROM table2 ORDER BY table2.field1
</code></pre>
<p>Throws an exception</p>
<p>Note: this is being attempted on MS Access Jet database engine</p>
|
<p>Sometimes you need to have the <code>ORDER BY</code> in each of the sections that need to be combined with <code>UNION</code>.</p>
<p>In this case</p>
<pre><code>SELECT * FROM
(
SELECT table1.field1 FROM table1 ORDER BY table1.field1
) DUMMY_ALIAS1
UNION ALL
SELECT * FROM
(
SELECT table2.field1 FROM table2 ORDER BY table2.field1
) DUMMY_ALIAS2
</code></pre>
|
<p>The second table cannot include the table name in the <code>ORDER BY</code> clause.</p>
<p>So...</p>
<pre><code>SELECT table1.field1 FROM table1 ORDER BY table1.field1
UNION
SELECT table2.field1 FROM table2 ORDER BY field1
</code></pre>
<p>Does not throw an exception</p>
| 26,288
|
<p>I create a GUID (as a string) and get the hash of it. Can I consider this hash to be unique?</p>
|
<p>Not as reliably unique as the GUID itself, no.</p>
<p>Just to expand, you are reducing your uniqueness by a factor of 4, going from 16 bytes to 4 bytes of possible combinations.</p>
<p>As pointed out in the comments the hash size will make a difference. The 4 byte thing was an assumption, horrible at best I know, that it may be used in .NET, where the default hash size is 4 bytes (int). So you can replace what I said above with whatever byte size your hash may be.</p>
|
<p>If you use cryptographic hash (MD5, SHA1, RIPEMD160), the hash will be unique (modulo collisions which are very improbable -- SHA1 is used e.g. for digital signatures, and MD5 is also collision-resistant on <em>random inputs</em>). Though, why do you want to hash a GUID?</p>
| 16,735
|
<p>I remember back when MS released a forum sample application, the design of the application was like this:</p>
<p>/Classes/User.cs
/Classes/Post.cs
...
/Users.cs
/Posts.cs</p>
<p>So the classes folder had just the class i.e. properties and getters/setters.
The Users.cs, Post.cs, etc. have the actual methods that access the Data Access Layer, so Posts.cs might look like:</p>
<pre><code>public class Posts
{
public static Post GetPostByID(int postID)
{
SqlDataProvider dp = new SqlDataProvider();
return dp.GetPostByID(postID);
}
}
</code></pre>
<p>Another more traditional route would be to put all of the methods in Posts.cs into the class definition also (Post.cs).</p>
<p>Splitting things into 2 files makes it much more procedural doesn't it?
Isn't this breaking OOP rules since it is taking the behavior out of the class and putting it into another class definition?</p>
|
<p>If every method is just a static call straight to the data source, then the "Posts" class is really a Factory. You could certainly put the static methods in "Posts" into the "Post" class (this is how CSLA works), but they are still factory methods.</p>
<p>I would say that a more modern and accurate name for the "Posts" class would be "PostFactory" (assuming that all it has is static methods).</p>
<p>I guess I wouldn't say this is a "procedural" approach necessarily -- it's just a misleading name, you would assume in the modern OO world that a "Posts" object would be stateful and provide methods to manipulate and manage a set of "Post" objects.</p>
|
<p>Are you sure the classes aren't partial classes. In which case they really aren't two classes, just a single class spread across multiple files for better readability.</p>
| 8,252
|
<p>I have an array I've created in JavaScript. The end result comes out to element1,element2,,,element5,element6,,,element9.... etc</p>
<p>Once passed to ColdFusion, it removes the null elements, I end up with element1,element2,element5,element6,element9</p>
<p>I need to maintain these spaces, any ideas? My problem may begin before this, to explain in more detail...</p>
<p>I have a form with 13 elements that are acting as a search/filter type function. I want to "post" with AJAX, in essence, i'm using a button to call a jQuery function and want to pass the fields to a ColdFusion page, then have the results passed back. The JavaScript array may not even be my best option.</p>
<p>Any ideas?</p>
|
<p>Are you deserializing the jS array into a list? CF ignores empty list fields using its built-in functions. This can be worked around by processing the text directly. Someone has already done this for you, fortunately. There are several functions at cflib.org, like:</p>
<ul>
<li><a href="http://cflib.org/udf/ListFix" rel="nofollow noreferrer">ListFix</a></li>
<li><a href="http://cflib.org/udf/ListLenIncNulls" rel="nofollow noreferrer">ListLenIncNulls</a></li>
</ul>
<p>etc, etc, etc.</p>
|
<p>In exchanging data between javascript and coldfusion have a look at using JSON. </p>
<p><a href="http://www.json.org" rel="nofollow noreferrer">http://www.json.org</a></p>
<p><a href="http://www.epiphantastic.com/cfjson/" rel="nofollow noreferrer">http://www.epiphantastic.com/cfjson/</a></p>
| 28,966
|
<p>I don't see a Visual Studio plugin for it (although I didn't look that hard, so I might have missed it), and searches turn up random third-party solutions, but is there something that comes with PowerShell or something that plugs into Visual Studio?</p>
|
<p>Visual Studio templates are available <a href="http://channel9.msdn.com/playground/Sandbox/249904-Windows-PowerShell-Visual-Studio-2005-Templates-C-and-VBNET/" rel="nofollow noreferrer">here</a>. And there are samples in the Server 2008 SDK for developing providers and hosts.</p>
<p>If you are talking about an IDE for scripting, see <a href="https://stackoverflow.com/questions/33559/how-to-get-started-with-powershell">this question (How to Get Started with PowerShell)</a></p>
|
<p>Sapiens Powershell Studio 2012 - hands down the best Powershell specific IDE.</p>
<p><a href="http://www.sapien.com/software/powershell_studio" rel="nofollow">http://www.sapien.com/software/powershell_studio</a></p>
| 30,398
|
<p>Like the title says, If I place an <code>app_offline.htm</code> in the application root, will it cut off currently running requests, or just new ones?</p>
|
<p>Here is my lame experiment; I created an ASPX page with the following code:
</p>
<pre class="lang-cs prettyprint-override"><code>protected void Page_Load(object sender, EventArgs e)
{
Response.BufferOutput = false;
Response.Write("Step 1<br />");
System.Threading.Thread.Sleep(10000);
Response.Write("Step 2<br />");
System.Threading.Thread.Sleep(10000);
Response.Write("Step 3<br />");
}
</code></pre>
<p>This code simply introduces some loooong page loads. I accessed the page and while it was loading, I created an "app_offline.htm" file. I then loaded another web browser and confirmed the application was offline. I then re-visited my "loading" request...it completed all the way to step 3.</p>
<p>This confirms that current requests finish loading and new requests are turned away.</p>
|
<p>From ScottGu's blog:</p>
<blockquote>
<p>Basically, if you place a file with
this name in the root of a web
application directory, <strong>ASP.NET 2.0
will shut-down the application, unload
the application domain from the
server, and stop processing any new
incoming requests for that
application</strong>. ASP.NET will also then
respond to all requests for dynamic
pages in the application by sending
back the content of the
app_offline.htm file (for example: you
might want to have a “site under
construction” or “down for
maintenance” message).</p>
</blockquote>
<p><a href="http://weblogs.asp.net/scottgu/archive/2005/10/06/426755.aspx" rel="nofollow noreferrer">App_Offline.htm - ScottGu's Blog</a></p>
<p>So, it seems like it will continue processing current request, but stop new incoming requests.</p>
| 21,656
|
<p>I have a script that did double inserts into the database with the same data. Is there a good way to do this (without scanning through, inserting every record into an array, and then deleting duplicate array entries)?</p>
|
<pre><code>DELETE
FROM t
WHERE ID IN (
SELECT MAX(ID)
FROM t
GROUP BY {Your Group Criteria Here}
HAVING COUNT(*) > 1
)
</code></pre>
|
<p>If you don't have anything referencing into the table by key right now, I'd mysqldump --complete-insert it, strip the primary keys, change the table definition to enforce some unique key or another that would catch your duplications, change the INSERTs to REPLACEs, and load the data back in. Gets you a nice clean table without holes in the PK sequence or deleted rows.</p>
| 49,770
|
<p>What techniques and/or modules are available to implement robust rate limiting (requests|bytes/ip/unit time) in apache?</p>
|
<p>The best</p>
<ul>
<li><a href="https://github.com/jzdziarski/mod_evasive" rel="noreferrer">mod_evasive</a> (Focused more on reducing DoS exposure)</li>
<li><a href="http://dembol.org/blog/mod_cband/" rel="noreferrer">mod_cband</a> (Best featured for 'normal' bandwidth control)</li>
</ul>
<p>and the rest</p>
<ul>
<li><a href="http://dominia.org/djao/limitipconn.html" rel="noreferrer">mod_limitipconn</a></li>
<li><a href="http://bwmod.sourceforge.net/" rel="noreferrer">mod_bw</a></li>
<li><a href="http://www.topology.org/src/bwshare/README.html" rel="noreferrer">mod_bwshare</a></li>
</ul>
|
<p>One more option - mod_qos</p>
<p>Not simple to configure - but powerful.</p>
<p><a href="http://opensource.adnovum.ch/mod_qos/" rel="nofollow">http://opensource.adnovum.ch/mod_qos/</a></p>
| 15,976
|
<p>I want to build an ASP.NET MVC application with Boo instead of C#. If you know the steps to configure this type of project setup, I'd be interested to know what I need to do. </p>
<p>The MVC project setup is no problem. What I'm trying to figure out how to configure the pages and project to switch to use the Boo language and compiler.</p>
|
<p>So there are two levels of "work with Boo". One would be all the code (namely, the Controllers), and the other would be the views.</p>
<p>For the code, I assume Boo compiles to standard .NET assemblies, so simply properly following the naming conventions using by ASP.NET MVC should allow you to write Controllers. You will probably need to start with a C# or VB version of the MVC web application project template and port some of the boilerplate code over into Boo to get the solution entirely in Boo (I presume Boo supports Web Application projects?).</p>
<p>The other half is views. Someone will need to port the Brail view engine over to the ASP.NET MVC view engine system. This may already be done, but I don't know for sure. If it's not, then this is probably a significant amount of work to be done.</p>
<p>Probably the best place to get answers to these kinds of questions is the <a href="http://www.codeplex.com/MVCContrib" rel="nofollow noreferrer">MvcContrib community on CodePlex</a>.</p>
|
<p>The Brail view engine has been implemented to be used in ASP.NET MVC. The <a href="http://www.mvccontrib.org" rel="nofollow noreferrer">MvcContrib</a> project implemented the code. The <a href="http://code.google.com/p/mvccontrib/" rel="nofollow noreferrer">source code</a> is located on Google Code.</p>
<p>As far as the controllers, I really am not sure. I am not that familiar with Boo. I know a lot of developers use it for configuration instead of using xml for instance. My tips would be, if Boo can inherit off the Controller base class and you stick to the naming conventions, you should be alright. If you vary off the naming conventions, well you would need to implement your own IControllerFactory to instantiate the boo controllers as the requests come in.</p>
<p>I have been following the ASP.NET MVC bits since the first CTP and through that whole time, I have not seen somebody use Boo to code with. I think you will be the first to try to accomplish this.</p>
| 5,060
|
<p>First, yes I know about <a href="https://stackoverflow.com/questions/50182/linuxx11-input-library-without-creating-a-window">this question</a>, but I'm looking for a bit more information that that. I have actually, a fairly similar problem, in that I need to be able to capture input for mouse/keyboard/joystick, and I'd also like to avoid SDL if at all possible. I was more or less wondering if anyone knows where I can get some decent primers on handling input from devices in Linux, perhaps even some tutorials. SDL works great for cross-platform input handling, but I'm not going to be using anything else at all from SDL, so I'd like to cut it out altogether. Suggestion, comments, and help are all appreciated. Thanks!</p>
<p>Edit for clarity:</p>
<p>The point is to capture mouse motion, keyboard press/release, mouse clicks, and potentially joystick handling for a game.</p>
|
<p>Using the link below look at the function void kGUISystemX::Loop(void)</p>
<p>This is my main loop for getting input via keyboard and mouse using X Windows on Linux.</p>
<p><a href="http://code.google.com/p/kgui/source/browse/trunk/kguilinux.cpp" rel="noreferrer">http://code.google.com/p/kgui/source/browse/trunk/kguilinux.cpp</a></p>
<p>Here is a snippet:</p>
<pre><code> if(XPending(m_display))
{
XNextEvent(m_display, &m_e);
switch(m_e.type)
{
case MotionNotify:
m_mousex=m_e.xmotion.x;
m_mousey=m_e.xmotion.y;
break;
case ButtonPress:
switch(m_e.xbutton.button)
{
case Button1:
m_mouseleft=true;
break;
case Button3:
m_mouseright=true;
break;
case Button4:/* middle mouse wheel moved */
m_mousewheel=1;
break;
case Button5:/* middle mouse wheel moved */
m_mousewheel=-1;
break;
}
break;
case ButtonRelease:
switch(m_e.xbutton.button)
{
case Button1:
m_mouseleft=false;
break;
case Button3:
m_mouseright=false;
break;
}
break;
case KeyPress:
{
XKeyEvent *ke;
int ks;
int key;
ke=&m_e.xkey;
kGUI::SetKeyShift((ke->state&ShiftMask)!=0);
kGUI::SetKeyControl((ke->state&ControlMask)!=0);
ks=XLookupKeysym(ke,(ke->state&ShiftMask)?1:0);
......
</code></pre>
|
<p>You can get direct input from the files in /dev/input. This is simplest way to do it, and you don't need any extra software. </p>
| 15,296
|
<p>Assuming I have only the class name of a generic as a string in the form of "MyCustomGenericCollection(of MyCustomObjectClass)" and don't know the assembly it comes from, what is the easiest way to create an instance of that object? </p>
<p>If it helps, I know that the class implements IMyCustomInterface and is from an assembly loaded into the current AppDomain.</p>
<p>Markus Olsson gave an excellent example <a href="https://stackoverflow.com/questions/31238/c-instantiating-classes-from-xml">here</a>, but I don't see how to apply it to generics.</p>
|
<p>Once you parse it up, use <a href="http://msdn.microsoft.com/en-us/library/w3f99sx1.aspx" rel="noreferrer">Type.GetType(string)</a> to get a reference to the types involved, then use <a href="http://msdn.microsoft.com/en-us/library/system.type.makegenerictype.aspx" rel="noreferrer">Type.MakeGenericType(Type[])</a> to construct the specific generic type you need. Then, use <a href="http://msdn.microsoft.com/en-us/library/system.type.getconstructor.aspx" rel="noreferrer">Type.GetConstructor(Type[])</a> to get a reference to a constructor for the specific generic type, and finally call <a href="http://msdn.microsoft.com/en-us/library/6ycw1y17.aspx" rel="noreferrer">ConstructorInfo.Invoke</a> to get an instance of the object.</p>
<pre><code>Type t1 = Type.GetType("MyCustomGenericCollection");
Type t2 = Type.GetType("MyCustomObjectClass");
Type t3 = t1.MakeGenericType(new Type[] { t2 });
ConstructorInfo ci = t3.GetConstructor(Type.EmptyTypes);
object obj = ci.Invoke(null);
</code></pre>
|
<p>If you don't mind translating to VB.NET, something like this should work</p>
<pre><code>foreach (Assembly assembly in AppDomain.CurrentDomain.GetAssemblies())
{
// find the type of the item
Type itemType = assembly.GetType("MyCustomObjectClass", false);
// if we didnt find it, go to the next assembly
if (itemType == null)
{
continue;
}
// Now create a generic type for the collection
Type colType = assembly.GetType("MyCusomgGenericCollection").MakeGenericType(itemType);;
IMyCustomInterface result = (IMyCustomInterface)Activator.CreateInstance(colType);
break;
}
</code></pre>
| 15,812
|
<p>When a PHP application makes a database connection it of course generally needs to pass a login and password. If I'm using a single, minimum-permission login for my application, then the PHP needs to know that login and password somewhere. What is the best way to secure that password? It seems like just writing it in the PHP code isn't a good idea.</p>
|
<p>Several people misread this as a question about how to <strong>store</strong> passwords in a database. That is wrong. It is about how to store the password that lets you get <strong>to</strong> the database.</p>
<p>The usual solution is to move the password out of source-code into a configuration file. Then leave administration and securing that configuration file up to your system administrators. That way developers do not need to know anything about the production passwords, and there is no record of the password in your source-control.</p>
|
<p>Actually, the best practice is to store your database crendentials in environment variables because :</p>
<ul>
<li>These credentials are dependant to environment, it means that you won't have the same credentials in dev/prod. Storing them in the same file for all environment is a mistake.</li>
<li>Credentials are <strong>not related to business logic</strong> which means login and password have nothing to do in your code.</li>
<li>You can set environment variables without creating any business code class file, which means you will never make the mistake of adding the credential files to a commit in Git.</li>
<li>Environments variables are superglobales : you can use them everywhere in your code without including any file.</li>
</ul>
<p><strong>How to use them ?</strong></p>
<ul>
<li>Using the $_ENV array :
<ul>
<li>Setting : <code>$_ENV['MYVAR'] = $myvar</code></li>
<li><a href="https://www.php.net/manual/en/reserved.variables.environment.php" rel="nofollow noreferrer">Getting</a> : <code>echo $_ENV["MYVAR"]</code></li>
</ul>
</li>
<li>Using the php functions :
<ul>
<li>Setting with the <a href="https://www.php.net/manual/en/function.putenv.php" rel="nofollow noreferrer">putenv function</a> - <code>putenv("MYVAR=$myvar");</code></li>
<li>Getting with the <a href="https://www.php.net/manual/en/function.getenv.php" rel="nofollow noreferrer">getenv function</a> - <code>getenv('MYVAR');</code></li>
</ul>
</li>
<li><a href="https://stackoverflow.com/questions/17550223/set-an-environment-variable-in-htaccess-and-retrieve-it-in-php">In vhosts files and .htaccess</a> but it's not recommended since its in another file and its not resolving the problem by doing it this way.</li>
</ul>
<p>You can easily drop a file such as envvars.php with all environment variables inside and execute it (<code>php envvars.php</code>) and delete it. It's a bit old school, but it still work and you don't have any file with your credentials in the server, and no credentials in your code. Since it's a bit laborious, frameworks do it better.</p>
<p><strong>Example with Symfony (ok its not only PHP)</strong>
The modern frameworks such as Symfony recommends using environment variables, and store them in a .env not commited file or directly in command lines which means you wether can do :</p>
<ul>
<li><a href="https://symfony.com/doc/current/cloud/cookbooks/env.html" rel="nofollow noreferrer">With CLI</a> : <code>symfony var:set FOO=bar --env-level</code></li>
<li><a href="https://symfony.com/doc/current/configuration/env_var_processors.html" rel="nofollow noreferrer">With .env or .env.local</a> : FOO="bar"</li>
</ul>
<p>Documentation :</p>
| 12,348
|
<p>During the installation of Apache2 I got the following message into cmd window:</p>
<blockquote>
<p>Installing the Apache2.2 service The
Apache2.2 service is successfully
installed. Testing httpd.conf....</p>
<p>Errors reported here must be corrected
before the service can be started.
httpd.exe: Could not reliably
determine the server's fully qualified
domain name , using 192.168.1.3 for
ServerName (OS 10048)Only one usage of
each socket address (protocol/network
address/port) is normally permitted.
: make_sock: could not bind to address
0.0.0.0:80 no listening sockets available, shutting down Unable to
open logs Note the errors or messages
above, and press the key to
exit. 24...</p>
</blockquote>
<p>and after installing everything look fine, but it isn't. If I try to start service I got the following message:</p>
<blockquote>
<p>Windows could not start the Apache2 on
Local Computer. For more information,
review the System Event Log. If this
is a non-Micorsoft service, contact
the service vendor, and refer to
service-specific error code 1.</p>
</blockquote>
<p>Apach2 version is 2.2.9</p>
<p>Does anyone have the same problem, or could help me.</p>
|
<p>There is some other program listening on port 80, usual suspects are</p>
<ol>
<li>Skype (Listens on port 80)</li>
<li>NOD32 (Add Apache to the IMON exceptions' list for it to allow apache to bind)</li>
<li>Some other antivirus (Same as above)</li>
</ol>
<p>Way to correct it is either shutting down the program that's using the port 80 or configure it to use a different port or configure Apache to listen on a different port with the Listen directive in httpd.conf. In the case of antivirus configure the antivirus to allow Apache to bind on the port you have chosen.</p>
<p>Way to diagnose which app, if any, has bound to port 80 is run the netstat with those options, look for :80 next to the local IP address (second column) and find the PID (last column). Then, on the task manager you can find which process has the PID you got in the previous step. (You might need to add the PID column on the task manager)</p>
<p>C:\Users\vinko>netstat -ao -p tcp</p>
<pre><code>Conexiones activas
Proto Dirección local Dirección remota Estado PID
TCP 127.0.0.1:1110 127.0.0.1:51373 TIME_WAIT 0
TCP 127.0.0.1:1110 127.0.0.1:51379 TIME_WAIT 0
TCP 127.0.0.1:1110 127.0.0.1:51381 ESTABLISHED 388
TCP 127.0.0.1:1110 127.0.0.1:51382 TIME_WAIT 0
TCP 127.0.0.1:1110 127.0.0.1:51479 TIME_WAIT 0
TCP 127.0.0.1:1110 127.0.0.1:51481 TIME_WAIT 0
TCP 127.0.0.1:1110 127.0.0.1:51483 TIME_WAIT 0
TCP 127.0.0.1:1110 127.0.0.1:51485 ESTABLISHED 388
TCP 127.0.0.1:1110 127.0.0.1:51487 TIME_WAIT 0
TCP 127.0.0.1:1110 127.0.0.1:51489 ESTABLISHED 388
TCP 127.0.0.1:51381 127.0.0.1:1110 ESTABLISHED 5168
TCP 127.0.0.1:51485 127.0.0.1:1110 ESTABLISHED 5168
TCP 127.0.0.1:51489 127.0.0.1:1110 ESTABLISHED 5168
TCP 127.0.0.1:59264 127.0.0.1:59265 ESTABLISHED 5168
TCP 127.0.0.1:59265 127.0.0.1:59264 ESTABLISHED 5168
TCP 127.0.0.1:59268 127.0.0.1:59269 ESTABLISHED 5168
TCP 127.0.0.1:59269 127.0.0.1:59268 ESTABLISHED 5168
TCP 192.168.1.34:51278 192.168.1.33:445 ESTABLISHED 4
TCP 192.168.1.34:51383 67.199.15.132:80 ESTABLISHED 388
TCP 192.168.1.34:51486 66.102.9.18:80 ESTABLISHED 388
TCP 192.168.1.34:51490 74.125.4.20:80 ESTABLISHED 388
</code></pre>
<p>If you want to Disable Skype from listening on port 80 and 443, you can follow the link <a href="http://www.mydigitallife.info/disable-skype-from-using-opening-and-listening-on-port-80-and-443-on-local-computer/" rel="noreferrer">http://www.mydigitallife.info/disable-skype-from-using-opening-and-listening-on-port-80-and-443-on-local-computer/</a></p>
|
<p>Thanks for the help guys. I found another culprit. Recently SimplifyMedia added a photo sharing option. Apparently it too uses port 80 and prevented Apache from starting up. I hope this helps someone out.</p>
| 23,771
|
<p>I'm working on a form that will display links to open different types of reports. This system has different types of users, so the users should only be able to see the links to the types of reports they can access.</p>
<p>Currently, the way I have this set up is that I have an ArrayList of LinkLabels, but the problem I'm having is how to have a LinkClicked event for each LinkLabel in the ArrayList so that it will bring up a form specific to each report.</p>
|
<p>You can apply the same event handler to every LinkLabel in your list and get the specific LinkLabel from the sender argument.</p>
|
<p>Definitely recommend a single event handler for all of the dynamic LinkLabel instances. </p>
<p>I usually use a Hashtable where the key is the LinkLabel instance and the value is something that will be used within the click event (such as the report instance, if appropriate). </p>
<p>Then in the click event you use (for example)</p>
<pre><code>Report r = m_TheTable[sender] as Report;
if( r != null ) r.DoSomething();
</code></pre>
| 17,056
|
<p>I need the "Select Data Source" dialog added to my application so that the user can manually select a range (or ranges) in Excel and the range is pasted in my text box. This functionality is everywhere in Excel (most notably when selecting a range for a chart). How can I easily do this?</p>
|
<p>have you tried using the refedit control?</p>
<p><a href="http://support.microsoft.com/kb/213776" rel="nofollow noreferrer">How to Use the RefEdit Control with a UserForm</a></p>
|
<pre><code>Dim myRange As Range
On Error Resume Next
Set myRange = Application.InputBox(prompt:="Select the cells you want", Type:=8)
On Error GoTo 0
If myRange Is Nothing Then
MsgBox "User cancelled"
Else
MsgBox "User selected " & myRange.Address
End If
</code></pre>
<p>This will show an input dialog. Don't type anything into it, but instead, select cells with the mouse, and their address will appear in the dialog textbox. When you press OK,they should be assigned to the variable myRange.</p>
<p>Notes:
The "Type:=8" at the end of the InputBox line tells VBA this must be a range of cells
The On Error bit prevents an error if the user cancels</p>
| 29,460
|
<p>On input validation, I'm using balloon tips instead of message boxes.
My problem is that on Vista, they have the old XP style with the rounded corners, not the newer more rectangle like appearance.</p>
<p>I've tried creating them using CreateWindowEx and <code>tooltips_class32</code> or showing the Edit's associated balloontip using SendMessageW and <code>EM_SHOWBALLOONTIP</code>, the result is the same.
Doing the same thing in Visual Studio and C# results in a Vista style balloon tip.</p>
<p>You can see an example of the balloon hint I need, when you toggle Caps Lock while in a password edit, like the one on the Windows Logon.</p>
|
<p>If you're using Delphi 2009, then adding balloon hints is reasonably straightforward, although the documentation is poor. (surprise, surprise)</p>
<ul>
<li>Drop a TBalloonHint on your form</li>
<li>Drop a TImageList to contain icons if needed.</li>
<li>Link the TIMageList to the TBalloonHint</li>
<li>Set the form's CustomHint property to the TBalloonHint</li>
<li>Make sure ShowHint and ParentCustomHint are set true for your controls.</li>
</ul>
<p>This next bit is <a href="http://qc.codegear.com/wc/qcmain.aspx?d=67445" rel="nofollow noreferrer">very non-obvious</a>:</p>
<ul>
<li>Format the "Hint" property of your control as "Title|Hint|ImageIndex"</li>
</ul>
<p>You're done. This doesn't look 100% vista-like, maybe due to font choice. But it's pretty close.</p>
<p><a href="https://i.stack.imgur.com/rvyYs.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/rvyYs.png" alt="Delphi 2009"></a><br>
<sub>(source: <a href="http://dn.codegear.com/article/images/38757/0300000D.png" rel="nofollow noreferrer">codegear.com</a>)</sub> ,</p>
|
<p>As can be read in <a href="http://dn.codegear.com/article/38757" rel="nofollow noreferrer">Delphi 2009 reviewers guide</a> each VCL component now has a CustomHint property. It can be set to any descendant of TCustomHint.</p>
<p>Be sure to enable baloon hints in Vista else they won't show.</p>
| 38,162
|
<p>After hitting a few StackOverflowExceptions in .NET I noticed they completely bypass the unhandled exception handlers that .NET offers (Application.ThreadException / AppDomain.UnhandledException).
This is very disturbing since we have critical cleanup code in those exception handlers.</p>
<p>Is there any way to overcome this?</p>
|
<p>There are three kind of so-called "asynchronous exceptions". That are the ThreadAbortException, the OutOfMemoryException and the mentioned StackOverflowException. Those excepions are allowed to occur at any instruction in your code.</p>
<p>And, there's also a way to overcome them:</p>
<p>The easiest is the ThreadAbortException. When the current code executes in a finally-block. ThreadAbortExceptions are kind of "moved" to the end of the finally-block. So everything in a finally-block can't be aborted by a ThreadAbortException.</p>
<p>To avoid an OutOfMemoryException, you have only one possibility: Do not allocate anything on the Heap. This means that you're not allowed to create any new reference-types.</p>
<p>To overcome the StackOverflowException, you need some help from the Framework. This help manifests in Constrained Execution Regions. The required stack is allocated <strong>before</strong> the actual code is executed and additionally also ensures that the code is already JIT-Compiled and therefor is available for execution.</p>
<p>There are three forms to execute code in Constrained Execution Regions (copied from the <a href="http://blogs.msdn.com/bclteam/archive/2005/06/14/429181.aspx" rel="noreferrer">BCL Team Blog</a>):</p>
<ul>
<li>ExecuteCodeWithGuaranteedCleanup, a stack-overflow safe form of a try/finally.</li>
<li>A try/finally block preceded immediately by a call to RuntimeHelpers.PrepareConstrainedRegions. The try block is not constrained, but all catch, finally, and fault blocks for that try are.</li>
<li>As a critical finalizer - any subclass of CriticalFinalizerObject has a finalizer that is eagerly prepared before an instance of the object is allocated.
<ul>
<li>A special case is SafeHandle's ReleaseHandle method, a virtual method that is eagerly prepared before the subclass is allocated, and called from SafeHandle's critical finalizer.</li>
</ul></li>
</ul>
<p>You can find more at these blog posts:</p>
<p><a href="http://blogs.msdn.com/bclteam/archive/2005/06/14/429181.aspx" rel="noreferrer">Constrained Execution Regions and other errata [Brian Grunkemeyer]</a> at the BCL Team Blog.</p>
<p>Joe Duffy's Weblog about <a href="http://www.bluebytesoftware.com/blog/PermaLink.aspx?guid=c1898a31-a0aa-40af-871c-7847d98f1641" rel="noreferrer">Atomicity and asynchronous exception failures</a> where he gives a very good overview over asynchronous exceptions and robustness in the .net Framework.</p>
|
<p><a href="https://stackoverflow.com/a/107742/4076315">blowdart nailed it</a>. Really just a problem with typing code too quickly.</p>
<pre><code>private Thing _myThing = null;
Public Thing MyThing
{
get{
return this.MyThing;}
set{
this.MyThing = value;}
}
</code></pre>
| 13,315
|
<p>I'm making an automated script to read a list from a site posting the latest compiled code. That's the part I've already figured out. The next part of the script is to grab that compiled code from a server with an Untrusted Cert.</p>
<p>This is how I'm going about grabbing the file:</p>
<pre><code>$web = new-object System.Net.WebClient
$web.DownloadFile("https://uri/file.msi", "installer.msi")
</code></pre>
<p>Then I get the following error:</p>
<blockquote>
<p>Exception calling "DownloadFile" with "2" argument(s): "The underlying
connection was closed: Could not establish trust relationship for the
SSL/TLS secure channel."</p>
</blockquote>
<p>I know I'm missing something, but I can't get the correct way to search for it.</p>
|
<p>You need to write a callback handler for <a href="http://msdn.microsoft.com/en-us/library/system.net.servicepointmanager.servercertificatevalidationcallback.aspx" rel="nofollow noreferrer">ServicePointManager.ServerCertificateValidationCallback</a>.</p>
|
<p>The simplest PowerShell implementation of ServerCertificateValidationCallback is a script block that always returns true. This works for me in PowerShell version 5.1; haven't tested it on other versions.</p>
<pre><code>[System.Net.ServicePointManager]::ServerCertificateValidationCallback = {$true}
</code></pre>
<p>See Bhargav Shukla's <a href="https://bhargavs.com/index.php/2014/03/17/ignoring-ssl-trust-in-powershell-using-system-net-webclient/" rel="nofollow noreferrer">blog</a></p>
| 17,695
|
<p>I am using log.properties to configure logging for a Java app. Each class gets its own logger named after itself (e.g. com.company.program.ClassX).</p>
<p>I want to set a custom formatter for just one log, and leave the handler with the SimpleFormatter. Is this possible?</p>
<p>I am not interested in using log4j or another of the other logging suites. I am well aware of them. Nor am I interested in configuring a customer formatter for the logger through code, although if that is the only way to do it, it would be nice to know. Google isn't helping, and I am having problems testing this myself.</p>
|
<p>The <a href="http://java.sun.com/javase/6/docs/api/java/util/logging/Handler.html" rel="nofollow noreferrer">Handler</a> owns the Formatter, not the Logger. You would need a second Handler to perform special formatting. I'm assuming that you want both to show up in the console, so the answer would appear to be "no".</p>
<p>Something to try:
Create a subclass of java.util.logging.ConsoleHandler and use it as a second console handler. (I'm assuming here that you're using the <a href="http://edocs.bea.com/kodo/docs303/ref_guide_logging_jdk14.html" rel="nofollow noreferrer">system property</a>, otherwise it won't help you.)</p>
|
<p>I believe this is a limitation of Java logging. </p>
<p>You should decide to become interested in log4j. java.util.logging is only marginally better than <code>System.out.println</code></p>
| 25,870
|
<p>Say I have a Rails Model called Thing. Thing has a url attribute that can <strong>optionally</strong> be set to a URL somewhere on the Internet. In view code, I need logic that does the following:</p>
<pre><code><% if thing.url.blank? %>
<%= link_to('Text', thing_path(thing)) %>
<% else %>
<%= link_to('Text', thing.url) %>
<% end %>
</code></pre>
<p>This conditional logic in the view is ugly. Of course, I could build a helper function, which would change the view to this:</p>
<pre><code><%= thing_link('Text', thing) %>
</code></pre>
<p>That solves the verbosity problem, but I would really prefer having the functionality in the model itself. In which case, the view code would be:</p>
<pre><code><%= link_to('Text', thing.link) %>
</code></pre>
<p>This, obviously, would require a link method on the model. Here's what it would need to contain:</p>
<pre><code>def link
(self.url.blank?) ? thing_path(self) : self.url
end
</code></pre>
<p>To the point of the question, thing_path() is an undefined method inside Model code. I'm assuming it's possible to "pull in" some helper methods into the model, but how? And is there a real reason that routing only operates at the controller and view layers of the app? I can think of lots of cases where model code may need to deal with URLs (integrating with external systems, etc).</p>
|
<p>In Rails 3 and higher:</p>
<pre><code>Rails.application.routes.url_helpers
</code></pre>
<p>e.g.</p>
<pre><code>Rails.application.routes.url_helpers.posts_path
Rails.application.routes.url_helpers.posts_url(:host => "example.com")
</code></pre>
|
<p><em>(Edit: Forget my previous babble...)</em></p>
<p>Ok, there might be situations where you would go either to the model or to some other url... But I don't really think this belongs in the model, the view (or maybe the model) sounds more apropriate.</p>
<p>About the routes, as far as I know the routes is for the actions in controllers (wich usually "magically" uses a view), not directly to views. The controller should handle all requests, the view should present the results and the model should handle the data and serve it to the view or controller. I've heard a lot of people here talking about routes to models (to the point I'm allmost starting to beleave it), but as I understand it: routes goes to controllers. Of course a lot of controllers are controllers for one model and is often called <code><modelname>sController</code> (e.g. "UsersController" is the controller of the model "User"). </p>
<p>If you find yourself writing nasty amounts of logic in a view, try to move the logic somewhere more appropriate; request and internal communication logic probably belongs in the controller, data related logic may be placed in the model (but not display logic, which includes link tags etc.) and logic that is purely display related would be placed in a helper.</p>
| 44,327
|
<p><a href="http://www.nevrona.com/" rel="nofollow noreferrer">Nevrona Designs'</a> <a href="http://www.nevrona.com/Products/RaveReports/StandardEdition/tabid/66/Default.aspx" rel="nofollow noreferrer">Rave Reports</a> is a Report Engine for use by <a href="http://www.embarcadero.com/" rel="nofollow noreferrer">Embarcadero's</a> <a href="http://www.codegear.com/products/delphi/win32" rel="nofollow noreferrer">Delphi</a> IDE.</p>
<p>This is what I call the Rave Endless Loop bug. In Rave Reports
version 6.5.0 (VCL10) that comes bundled with Delphi 2006, there is a
nortorious bug that plagues many Rave report developers. If you have a
non-empty dataset, and the data rows for this dataset fit exactly into a
page (that is to say there are zero widow rows), then upon PrintPreview,
Rave will get stuck in an infinite loop generating pages.</p>
<p>This problem has been previously reported in this newsgroup under the
following headings:</p>
<ol>
<li>"error: generating infinite pages"; Hugo Hiram 20/9/2006 8:44PM</li>
<li>"Rave loop bug. Please help"; Tomas Lazar 11/07/2006 7:35PM</li>
<li>"Loop on full page of data?"; Tony Chistiansen 23/12/2004 3:41PM</li>
<li>reply to (3) by another complainant; Oliver Piche</li>
<li>"Endless lopp print bug"; Richso 9/11/2004 4:44PM</li>
</ol>
<p>In each of these postings, there was no response from Nevrona, and no
solution was reported.</p>
<p>Possibly, the problem has also been reported on an allied newsgroup
(nevrona.public.rave.reports.general), to wit:
6. "Continuously generating report"; Jobard 20/11/2005
Although it is not clear to me if (6) is the Rave Endless loop bug or
another problem. This posting did get a reply from Nevrona, but it was
more in relation to multiple regions ("There is a problem when using
multiple regions that go over a page-break.") than the problem of zero
widows.</p>
|
<p>This is more of a work-around than a true solution. I first posted this work-around on the Nevrona newsgroup (Group=nevrona.public.rave.developer.delphi.rave; Subject="Are you suffering from the Rave Endless Loop bug?: Work-around announced."; Date=13/11/2006 7:06 PM)</p>
<p>So here is my solution. It is more of a work-around than a good
long-term solution, and I hope that Nevrona will give this issue some
serious attention in the near future.</p>
<ol>
<li>Given your particular report layout, count the maximum number of rows
per page. Let us say that this is 40.</li>
<li>Set up a counter to count the rows within the page (as opposed to rows within the whole report). You could do this either by event script or by a CalcTotal component.</li>
<li>Define an OnBeforePrint scripted event handler for the main data band.</li>
<li>In this event handler set the FinishNewPage property of the main data band to be True when the row-per-page count is one or two below the max (in our example, this would be 38). And set it to False in all other cases. The effect of this is to give every page a non-zero number of widows (in this case 1..38), thus avoiding the condition that gives rise to the Rave Endless loop problem.</li>
</ol>
|
<p>thank's a lot, this thread helps me out from my problem with endless printing loop in Nevrona Rave...., I set MinHeightLeft to 0,500, this setting is work but i'm not sure that it will work for anothers result set of my query report.</p>
| 9,439
|
<p>What issues / pitfalls must be considered when overriding <code>equals</code> and <code>hashCode</code>?</p>
|
<h3>The theory (for the language lawyers and the mathematically inclined):</h3>
<p><code>equals()</code> (<a href="http://docs.oracle.com/javase/7/docs/api/java/lang/Object.html#equals(java.lang.Object)" rel="noreferrer">javadoc</a>) must define an equivalence relation (it must be <em>reflexive</em>, <em>symmetric</em>, and <em>transitive</em>). In addition, it must be <em>consistent</em> (if the objects are not modified, then it must keep returning the same value). Furthermore, <code>o.equals(null)</code> must always return false.</p>
<p><code>hashCode()</code> (<a href="http://docs.oracle.com/javase/7/docs/api/java/lang/Object.html#hashCode()" rel="noreferrer">javadoc</a>) must also be <em>consistent</em> (if the object is not modified in terms of <code>equals()</code>, it must keep returning the same value).</p>
<p>The <strong>relation</strong> between the two methods is:</p>
<blockquote>
<p><em>Whenever <code>a.equals(b)</code>, then <code>a.hashCode()</code> must be same as <code>b.hashCode()</code>.</em></p>
</blockquote>
<h3>In practice:</h3>
<p>If you override one, then you should override the other.</p>
<p>Use the same set of fields that you use to compute <code>equals()</code> to compute <code>hashCode()</code>.</p>
<p>Use the excellent helper classes <a href="http://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/builder/EqualsBuilder.html" rel="noreferrer">EqualsBuilder</a> and <a href="http://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/builder/HashCodeBuilder.html" rel="noreferrer">HashCodeBuilder</a> from the <a href="http://commons.apache.org/lang/" rel="noreferrer">Apache Commons Lang</a> library. An example:</p>
<pre><code>public class Person {
private String name;
private int age;
// ...
@Override
public int hashCode() {
return new HashCodeBuilder(17, 31). // two randomly chosen prime numbers
// if deriving: appendSuper(super.hashCode()).
append(name).
append(age).
toHashCode();
}
@Override
public boolean equals(Object obj) {
if (!(obj instanceof Person))
return false;
if (obj == this)
return true;
Person rhs = (Person) obj;
return new EqualsBuilder().
// if deriving: appendSuper(super.equals(obj)).
append(name, rhs.name).
append(age, rhs.age).
isEquals();
}
}
</code></pre>
<h3>Also remember:</h3>
<p>When using a hash-based <a href="http://download.oracle.com/javase/1.4.2/docs/api/java/util/Collection.html" rel="noreferrer">Collection</a> or <a href="http://download.oracle.com/javase/1.4.2/docs/api/java/util/Map.html" rel="noreferrer">Map</a> such as <a href="http://download.oracle.com/javase/1.4.2/docs/api/java/util/HashSet.html" rel="noreferrer">HashSet</a>, <a href="http://download.oracle.com/javase/1.4.2/docs/api/java/util/LinkedHashSet.html" rel="noreferrer">LinkedHashSet</a>, <a href="http://download.oracle.com/javase/1.4.2/docs/api/java/util/HashMap.html" rel="noreferrer">HashMap</a>, <a href="http://download.oracle.com/javase/1.4.2/docs/api/java/util/Hashtable.html" rel="noreferrer">Hashtable</a>, or <a href="http://download.oracle.com/javase/1.4.2/docs/api/java/util/WeakHashMap.html" rel="noreferrer">WeakHashMap</a>, make sure that the hashCode() of the key objects that you put into the collection never changes while the object is in the collection. The bulletproof way to ensure this is to make your keys immutable, <a href="http://www.javapractices.com/topic/TopicAction.do?Id=29" rel="noreferrer">which has also other benefits</a>.</p>
|
<p>One gotcha I have found is where two objects contain references to each other (one example being a parent/child relationship with a convenience method on the parent to get all children).<br>
These sorts of things are fairly common when doing Hibernate mappings for example.</p>
<p>If you include both ends of the relationship in your hashCode or equals tests it's possible to get into a recursive loop which ends in a StackOverflowException.<br>
The simplest solution is to not include the getChildren collection in the methods.</p>
| 4,721
|
<p>The program that I am currently assigned to has a requirement that I copy the contents of a table to a backup table, prior to the real processing.</p>
<p>During code review, a coworker pointed out that</p>
<pre><code>INSERT INTO BACKUP_TABLE
SELECT *
FROM PRIMARY_TABLE
</code></pre>
<p>is unduly risky, as it is possible for the tables to have different columns, and different column orders.</p>
<p>I am also under the constraint to not create/delete/rename tables. ~Sigh~</p>
<p>The columns in the table are expected to change, so simply hard-coding the column names is not really the solution I am looking for.</p>
<p>I am looking for ideas on a reasonable non-risky way to get this job done.</p>
|
<p>Does the backup table stay around? Does it keep the data permanently, or is it just a copy of the current values?</p>
<p>Too bad about not being able to create/delete/rename/copy. Otherwise, if it's short term, just used in case something goes wrong, then you could drop it at the start of processing and do something like</p>
<pre><code>create table backup_table as select * from primary_table;
</code></pre>
<p>Your best option may be to make the select explicit, as</p>
<pre><code>insert into backup_table (<list of columns>) select <list of columns> from primary_table;
</code></pre>
<p>You could generate that by building a SQL string from the data dictionary, then doing execute immediate. But you'll still be at risk if the backup_table doesn't contain all the important columns from the primary_table. </p>
<p>Might just want to make it explicit, and raise a major error if backup_table doesn't exist, or any of the columns in primary_table aren't in backup_table. </p>
|
<p>You could try something like:</p>
<pre><code>CREATE TABLE secondary_table AS SELECT * FROM primary_table;
</code></pre>
<p>Not sure if that automatically copies data. If not:</p>
<pre><code>CREATE TABLE secondary_table AS SELECT * FROM primary_table LIMIT 1;
INSERT INTO secondary_table SELECT * FROM primary_table;
</code></pre>
<p>Edit:</p>
<p>Sorry, didn't read your post completely: especially the constraints part. I'm afraid I don't know how. My guess would be using a procedure that first describes both tables and compares them, before creating a lengthy insert / select query.</p>
<p>Still, if you're using a backup-table, I think it's pretty important it matches the original one exactly.</p>
| 39,340
|
<p>Here's a question to expose my lack of experience: I have a method <strong>DoSomething()</strong> which throws an exception if it doesn't manage to do it cleanly. If it fails, I try the less accurate method <strong>DoSomethingApproximately()</strong> several times in the hope that it will find a sufficiently good solution; if this also fails I finally call <strong>DoSomethingInaccurateButGuaranteedToWork()</strong>. All three are methods belonging to this object.</p>
<p>Two questions: first, is this (admittedly ugly) pattern acceptable, or is there a more elegant way?</p>
<p>Second, what is the best way to keep track of how many times I have called <strong>DoSomethingApproximately()</strong>, given that it is likely to throw an exception? I am currently keeping a variable iNoOfAttempts in the object, and nesting try blocks... this is horrible and I am ashamed. </p>
|
<p>You should never use exceptions for control flow of your application.</p>
<p>In your case I'd bunch the three methods together into a single method and have it return which particular approach succeeded, maybe with an enum or something like that.</p>
|
<p>Return an error code instead of throwing an exception. </p>
<p>If the ways those methods fail do throw exceptions, catch them all in the same method and take appropriate action, like increasing a counter and returning an error code.</p>
<pre><code> bool result = DoSomething();
while (!result && tries < MAX_TRIES) {
result = DoSomethingApproximately(); //This will increment tries
if (tries > THRESHOLD) {
result = DoSomethingThatAlwaysWorks();
}
}
</code></pre>
| 15,430
|
<p>I have a custom class loader so that a desktop application can dynamically start loading classes from an AppServer I need to talk to. We did this since the amount of jars that are required to do this are ridiculous (if we wanted to ship them). We also have version problems if we don't load the classes dynamically at run time from the AppServer library.</p>
<p>Now, I just hit a problem where I need to talk to two different AppServers and found that depending on whose classes I load first I might break badly... Is there any way to force the unloading of the class without actually killing the JVM?</p>
<p>Hope this makes sense</p>
|
<p>The only way that a Class can be unloaded is if the Classloader used is garbage collected. This means, references to every single class and to the classloader itself need to go the way of the dodo.</p>
<p>One possible solution to your problem is to have a Classloader for every jar file, and a Classloader for each of the AppServers that delegates the actual loading of classes to specific Jar classloaders. That way, you can point to different versions of the jar file for every App server.</p>
<p>This is not trivial, though. The OSGi platform strives to do just this, as each bundle has a different classloader and dependencies are resolved by the platform. Maybe a good solution would be to take a look at it.</p>
<p>If you don't want to use OSGI, one possible implementation could be to use one instance of <a href="https://docs.oracle.com/javase/tutorial/deployment/jar/jarclassloader.html" rel="noreferrer">JarClassloader</a> class for every JAR file.</p>
<p>And create a new, MultiClassloader class that extends Classloader. This class internally would have an array (or List) of JarClassloaders, and in the defineClass() method would iterate through all the internal classloaders until a definition can be found, or a NoClassDefFoundException is thrown. A couple of accessor methods can be provided to add new JarClassloaders to the class. There is several possible implementations on the net for a MultiClassLoader, so you might not even need to write your own.</p>
<p>If you instanciate a MultiClassloader for every connection to the server, in principle it is possible that every server uses a different version of the same class.</p>
<p>I've used the MultiClassloader idea in a project, where classes that contained user-defined scripts had to be loaded and unloaded from memory and it worked quite well.</p>
|
<p>If you're live watching if unloading class worked in <a href="http://docs.oracle.com/javase/7/docs/technotes/guides/management/jconsole.html" rel="nofollow noreferrer">JConsole</a> or something, try also adding <code>java.lang.System.gc()</code> at the end of your class unloading logic. It explicitly triggers Garbage Collector.</p>
| 17,912
|
<p>I had someting like this in my code (.Net 2.0, MS SQL)</p>
<pre><code>SqlConnection connection = new SqlConnection(@"Data Source=localhost;Initial
Catalog=DataBase;Integrated Security=True");
connection.Open();
SqlCommand cmdInsert = connection.CreateCommand();
SqlTransaction sqlTran = connection.BeginTransaction();
cmdInsert.Transaction = sqlTran;
cmdInsert.CommandText =
@"INSERT INTO MyDestinationTable" +
"(Year, Month, Day, Hour, ...) " +
"VALUES " +
"(@Year, @Month, @Day, @Hour, ...) ";
cmdInsert.Parameters.Add("@Year", SqlDbType.SmallInt);
cmdInsert.Parameters.Add("@Month", SqlDbType.TinyInt);
cmdInsert.Parameters.Add("@Day", SqlDbType.TinyInt);
// more fields here
cmdInsert.Prepare();
Stream stream = new FileStream(fileName, FileMode.Open, FileAccess.Read);
StreamReader reader = new StreamReader(stream);
char[] delimeter = new char[] {' '};
String[] records;
while (!reader.EndOfStream)
{
records = reader.ReadLine().Split(delimeter, StringSplitOptions.None);
cmdInsert.Parameters["@Year"].Value = Int32.Parse(records[0].Substring(0, 4));
cmdInsert.Parameters["@Month"].Value = Int32.Parse(records[0].Substring(5, 2));
cmdInsert.Parameters["@Day"].Value = Int32.Parse(records[0].Substring(8, 2));
// more here complicated stuff here
cmdInsert.ExecuteNonQuery()
}
sqlTran.Commit();
connection.Close();
</code></pre>
<p>With <em>cmdInsert.ExecuteNonQuery()</em> commented out this code executes in less than 2 sec. With SQL execution it takes 1m 20 sec. There are around 0.5 milion records. Table is emptied before. SSIS data flow task of similar functionality takes around 20 sec.</p>
<ul>
<li>Bulk Insert <strong>was</strong> not an option (see below). I did some fancy stuff during this import.</li>
<li>My test machine is Core 2 Duo with 2 GB RAM. </li>
<li>When looking in Task Manager CPU was not fully untilized. IO seemed also not to be fully utilized.</li>
<li>Schema is simple like hell: one table with AutoInt as primary index and less than 10 ints, tiny ints and chars(10).</li>
</ul>
<p>After some answers here I found that it is possible to execute <strong>bulk copy from memory</strong>! I was refusing to use bulk copy beacuse I thought it has to be done from file...</p>
<p>Now I use this and it takes aroud 20 sec (like SSIS task)</p>
<pre><code> DataTable dataTable = new DataTable();
dataTable.Columns.Add(new DataColumn("ixMyIndex", System.Type.GetType("System.Int32")));
dataTable.Columns.Add(new DataColumn("Year", System.Type.GetType("System.Int32")));
dataTable.Columns.Add(new DataColumn("Month", System.Type.GetType("System.Int32")));
dataTable.Columns.Add(new DataColumn("Day", System.Type.GetType("System.Int32")));
// ... and more to go
DataRow dataRow;
object[] objectRow = new object[dataTable.Columns.Count];
Stream stream = new FileStream(fileName, FileMode.Open, FileAccess.Read);
StreamReader reader = new StreamReader(stream);
char[] delimeter = new char[] { ' ' };
String[] records;
int recordCount = 0;
while (!reader.EndOfStream)
{
records = reader.ReadLine().Split(delimeter, StringSplitOptions.None);
dataRow = dataTable.NewRow();
objectRow[0] = null;
objectRow[1] = Int32.Parse(records[0].Substring(0, 4));
objectRow[2] = Int32.Parse(records[0].Substring(5, 2));
objectRow[3] = Int32.Parse(records[0].Substring(8, 2));
// my fancy stuf goes here
dataRow.ItemArray = objectRow;
dataTable.Rows.Add(dataRow);
recordCount++;
}
SqlBulkCopy bulkTask = new SqlBulkCopy(connection, SqlBulkCopyOptions.TableLock, null);
bulkTask.DestinationTableName = "MyDestinationTable";
bulkTask.BatchSize = dataTable.Rows.Count;
bulkTask.WriteToServer(dataTable);
bulkTask.Close();
</code></pre>
|
<p>Instead of inserting each record individually, Try using the <a href="http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlbulkcopy.aspx" rel="noreferrer">SqlBulkCopy</a> class to bulk insert all the records at once.</p>
<p>Create a DataTable and add all your records to the DataTable, and then use <a href="http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlbulkcopy.aspx" rel="noreferrer">SqlBulkCopy</a>.<a href="http://msdn.microsoft.com/en-us/library/ex21zs8x.aspx" rel="noreferrer">WriteToServer</a> to bulk insert all the data at once.</p>
|
<p>I assume that what is taking the approximately 58 seconds is the physical inserting of 500,000 records - so you are getting around 10,000 inserts a second. Without knowing the specs of your database server machine (I see you are using localhost, so network delays shouldn't be an issue), it is hard to say if this is good, bad, or abysmal.</p>
<p>I would look at your database schema - are there a bunch of indices on the table that have to be updated after each insert? This could be from other tables with foreign keys referencing the table you are working on. There are SQL profiling tools and performance monitoring facilities built into SQL Server, but I've never used them. But they may show up problems like locks, and things like that.</p>
| 15,475
|
<p>When working on a project, after the interesting parts are coded, my motivation is severely diminished. What do you do to get over this problem? </p>
|
<p>Don't leave all the "boring" bits to the end - make sure that each component works, with regression tests and documentation, as early as possible in the project.</p>
<p>That said, the last few weeks are still going to involve chasing down the really elusive bugs, dealing with last-second requirements changes, finalising the documentation, and generally getting the damn thing out of the door. My approach is just to suck it up: put your head down and know that the sooner it's done, the sooner you can start on all the lower-priority, more interesting things that have been queued behind the current release.</p>
<p>You can't completely avoid last-minute requirements/docs changes other than by arranging for your customers to all be on holiday just before release. Or get yourself in a dominating position like Apple and Google, so that customers have no prior knowledge of releases. </p>
<p>You "should" chase elusive bugs (by which I mean the ones so hard to reproduce that you don't have a consistent test case) early, because you cannot estimate how long they will take to fix. But in practice some proportion of them will become less elusive as the project goes on, or turn out to be side-effects of another known issue, so you save time on average by giving them a limited chance to do so. The downside of this is that towards the end there will be a few left. If there are more than about two, though, you've done it wrong.</p>
<p>Taking a short "break" after a major deadline to do whatever you find most fun is a good way to avoid burn-out in the long run. Even if you end up throwing most of it away because you skipped some difficult planning, you'll have made yourself more productive.</p>
|
<p>I agree it is tough. The only thing that keeps me going is to keep in mind the feeling I would have after seeing it complete / shipped / in the hands of customers.</p>
| 11,765
|
<p>Given the hash of a blob, is there a way to get a list of commits that have this blob in their tree?</p>
|
<p>Both of the following scripts take the blob’s SHA1 as the first argument, and after it, optionally, any arguments that <a href="http://git-scm.com/docs/git-log" rel="noreferrer"><code>git log</code></a> will understand. E.g. <code>--all</code> to search in all branches instead of just the current one, or <code>-g</code> to search in the reflog, or whatever else you fancy.</p>
<p>Here it is as a shell script – short and sweet, but slow:</p>
<pre class="lang-bash prettyprint-override"><code>#!/bin/sh
obj_name="$1"
shift
git log "$@" --pretty=tformat:'%T %h %s' \
| while read tree commit subject ; do
if git ls-tree -r $tree | grep -q "$obj_name" ; then
echo $commit "$subject"
fi
done
</code></pre>
<p>And an optimised version in Perl, still quite short but much faster:</p>
<pre class="lang-perl prettyprint-override"><code>#!/usr/bin/perl
use 5.008;
use strict;
use Memoize;
my $obj_name;
sub check_tree {
my ( $tree ) = @_;
my @subtree;
{
open my $ls_tree, '-|', git => 'ls-tree' => $tree
or die "Couldn't open pipe to git-ls-tree: $!\n";
while ( <$ls_tree> ) {
/\A[0-7]{6} (\S+) (\S+)/
or die "unexpected git-ls-tree output";
return 1 if $2 eq $obj_name;
push @subtree, $2 if $1 eq 'tree';
}
}
check_tree( $_ ) && return 1 for @subtree;
return;
}
memoize 'check_tree';
die "usage: git-find-blob <blob> [<git-log arguments ...>]\n"
if not @ARGV;
my $obj_short = shift @ARGV;
$obj_name = do {
local $ENV{'OBJ_NAME'} = $obj_short;
`git rev-parse --verify \$OBJ_NAME`;
} or die "Couldn't parse $obj_short: $!\n";
chomp $obj_name;
open my $log, '-|', git => log => @ARGV, '--pretty=format:%T %h %s'
or die "Couldn't open pipe to git-log: $!\n";
while ( <$log> ) {
chomp;
my ( $tree, $commit, $subject ) = split " ", $_, 3;
print "$commit $subject\n" if check_tree( $tree );
}
</code></pre>
|
<p>So... I needed to find all files over a given limit in a repo over 8GB in size, with over 108,000 revisions. I adapted Aristotle's perl script along with a ruby script I wrote to reach this complete solution.</p>
<p>First, <code>git gc</code> - do this to ensure all objects are in packfiles - we don't scan objects not in pack files.</p>
<p>Next Run this script to locate all blobs over CUTOFF_SIZE bytes. Capture output to a file like "large-blobs.log"</p>
<pre class="lang-ruby prettyprint-override"><code>#!/usr/bin/env ruby
require 'log4r'
# The output of git verify-pack -v is:
# SHA1 type size size-in-packfile offset-in-packfile depth base-SHA1
#
#
GIT_PACKS_RELATIVE_PATH=File.join('.git', 'objects', 'pack', '*.pack')
# 10MB cutoff
CUTOFF_SIZE=1024*1024*10
#CUTOFF_SIZE=1024
begin
include Log4r
log = Logger.new 'git-find-large-objects'
log.level = INFO
log.outputters = Outputter.stdout
git_dir = %x[ git rev-parse --show-toplevel ].chomp
if git_dir.empty?
log.fatal "ERROR: must be run in a git repository"
exit 1
end
log.debug "Git Dir: '#{git_dir}'"
pack_files = Dir[File.join(git_dir, GIT_PACKS_RELATIVE_PATH)]
log.debug "Git Packs: #{pack_files.to_s}"
# For details on this IO, see http://stackoverflow.com/questions/1154846/continuously-read-from-stdout-of-external-process-in-ruby
#
# Short version is, git verify-pack flushes buffers only on line endings, so
# this works, if it didn't, then we could get partial lines and be sad.
types = {
:blob => 1,
:tree => 1,
:commit => 1,
}
total_count = 0
counted_objects = 0
large_objects = []
IO.popen("git verify-pack -v -- #{pack_files.join(" ")}") do |pipe|
pipe.each do |line|
# The output of git verify-pack -v is:
# SHA1 type size size-in-packfile offset-in-packfile depth base-SHA1
data = line.chomp.split(' ')
# types are blob, tree, or commit
# we ignore other lines by looking for that
next unless types[data[1].to_sym] == 1
log.info "INPUT_THREAD: Processing object #{data[0]} type #{data[1]} size #{data[2]}"
hash = {
:sha1 => data[0],
:type => data[1],
:size => data[2].to_i,
}
total_count += hash[:size]
counted_objects += 1
if hash[:size] > CUTOFF_SIZE
large_objects.push hash
end
end
end
log.info "Input complete"
log.info "Counted #{counted_objects} totalling #{total_count} bytes."
log.info "Sorting"
large_objects.sort! { |a,b| b[:size] <=> a[:size] }
log.info "Sorting complete"
large_objects.each do |obj|
log.info "#{obj[:sha1]} #{obj[:type]} #{obj[:size]}"
end
exit 0
end
</code></pre>
<p>Next, edit the file to remove any blobs you don't wait and the INPUT_THREAD bits at the top. once you have only lines for the sha1s you want to find, run the following script like this:</p>
<pre><code>cat edited-large-files.log | cut -d' ' -f4 | xargs git-find-blob | tee large-file-paths.log
</code></pre>
<p>Where the <code>git-find-blob</code> script is below.</p>
<pre class="lang-perl prettyprint-override"><code>#!/usr/bin/perl
# taken from: http://stackoverflow.com/questions/223678/which-commit-has-this-blob
# and modified by Carl Myers <cmyers@cmyers.org> to scan multiple blobs at once
# Also, modified to keep the discovered filenames
# vi: ft=perl
use 5.008;
use strict;
use Memoize;
use Data::Dumper;
my $BLOBS = {};
MAIN: {
memoize 'check_tree';
die "usage: git-find-blob <blob1> <blob2> ... -- [<git-log arguments ...>]\n"
if not @ARGV;
while ( @ARGV && $ARGV[0] ne '--' ) {
my $arg = $ARGV[0];
#print "Processing argument $arg\n";
open my $rev_parse, '-|', git => 'rev-parse' => '--verify', $arg or die "Couldn't open pipe to git-rev-parse: $!\n";
my $obj_name = <$rev_parse>;
close $rev_parse or die "Couldn't expand passed blob.\n";
chomp $obj_name;
#$obj_name eq $ARGV[0] or print "($ARGV[0] expands to $obj_name)\n";
print "($arg expands to $obj_name)\n";
$BLOBS->{$obj_name} = $arg;
shift @ARGV;
}
shift @ARGV; # drop the -- if present
#print "BLOBS: " . Dumper($BLOBS) . "\n";
foreach my $blob ( keys %{$BLOBS} ) {
#print "Printing results for blob $blob:\n";
open my $log, '-|', git => log => @ARGV, '--pretty=format:%T %h %s'
or die "Couldn't open pipe to git-log: $!\n";
while ( <$log> ) {
chomp;
my ( $tree, $commit, $subject ) = split " ", $_, 3;
#print "Checking tree $tree\n";
my $results = check_tree( $tree );
#print "RESULTS: " . Dumper($results);
if (%{$results}) {
print "$commit $subject\n";
foreach my $blob ( keys %{$results} ) {
print "\t" . (join ", ", @{$results->{$blob}}) . "\n";
}
}
}
}
}
sub check_tree {
my ( $tree ) = @_;
#print "Calculating hits for tree $tree\n";
my @subtree;
# results = { BLOB => [ FILENAME1 ] }
my $results = {};
{
open my $ls_tree, '-|', git => 'ls-tree' => $tree
or die "Couldn't open pipe to git-ls-tree: $!\n";
# example git ls-tree output:
# 100644 blob 15d408e386400ee58e8695417fbe0f858f3ed424 filaname.txt
while ( <$ls_tree> ) {
/\A[0-7]{6} (\S+) (\S+)\s+(.*)/
or die "unexpected git-ls-tree output";
#print "Scanning line '$_' tree $2 file $3\n";
foreach my $blob ( keys %{$BLOBS} ) {
if ( $2 eq $blob ) {
print "Found $blob in $tree:$3\n";
push @{$results->{$blob}}, $3;
}
}
push @subtree, [$2, $3] if $1 eq 'tree';
}
}
foreach my $st ( @subtree ) {
# $st->[0] is tree, $st->[1] is dirname
my $st_result = check_tree( $st->[0] );
foreach my $blob ( keys %{$st_result} ) {
foreach my $filename ( @{$st_result->{$blob}} ) {
my $path = $st->[1] . '/' . $filename;
#print "Generating subdir path $path\n";
push @{$results->{$blob}}, $path;
}
}
}
#print "Returning results for tree $tree: " . Dumper($results) . "\n\n";
return $results;
}
</code></pre>
<p>The output will look like this:</p>
<pre><code><hash prefix> <oneline log message>
path/to/file.txt
path/to/file2.txt
...
<hash prefix2> <oneline log msg...>
</code></pre>
<p>And so on. Every commit which contains a large file in its tree will be listed. if you <code>grep</code> out the lines that start with a tab, and <code>uniq</code> that, you will have a list of all paths you can filter-branch to remove, or you can do something more complicated.</p>
<p>Let me reiterate: this process ran successfully, on a 10GB repo with 108,000 commits. It took much longer than I predicted when running on a large number of blobs though, over 10 hours, I will have to see if the memorize bit is working...</p>
| 27,626
|
<p>I would like to create a copy of a database with approximately 40 InnoDB tables and around 1.5GB of data with mysqldump and MySQL 5.1.</p>
<p>What are the best parameters (ie: --single-transaction) that will result in the quickest dump and load of the data?</p>
<p>As well, when loading the data into the second DB, is it quicker to:</p>
<p>1) pipe the results directly to the second MySQL server instance and use the --compress option</p>
<p>or</p>
<p>2) load it from a text file (ie: mysql < my_sql_dump.sql)</p>
|
<h2>QUICKLY dumping a quiesced database:</h2>
<p>Using the "-T " option with mysqldump results in lots of .sql and .txt files in the specified directory. This is ~50% faster for dumping large tables than a single .sql file with INSERT statements (takes 1/3 less wall-clock time).</p>
<p>Additionally, there is a huge benefit when restoring if you can load multiple tables in parallel, and saturate multiple cores. On an 8-core box, this could be as much as an 8X difference in wall-clock time to restore the dump, on top of the efficiency improvements provided by "-T". Because "-T" causes each table to be stored in a separate file, loading them in parallel is easier than splitting apart a massive .sql file.</p>
<p>Taking the strategies above to their logical extreme, one could create a script to dump a database widely in parallel. Well, that's exactly what the Maakit mk-parallel-dump (see <a href="http://www.maatkit.org/doc/mk-parallel-dump.html" rel="noreferrer">http://www.maatkit.org/doc/mk-parallel-dump.html</a>) and mk-parallel-restore tools are; perl scripts that make multiple calls to the underlying mysqldump program. However, when I tried to use these, I had trouble getting the restore to complete without duplicate key errors that didn't occur with vanilla dumps, so keep in mind that your milage may vary.</p>
<h2>Dumping data from a LIVE database (w/o service interruption):</h2>
<p>The --single-transaction switch is very useful for taking a dump of a live database without having to quiesce it or taking a dump of a slave database without having to stop slaving.</p>
<p>Sadly, -T is not compatible with --single-transaction, so you only get one.</p>
<p>Usually, taking the dump is much faster than restoring it. There is still room for a tool that take the incoming monolithic dump file and breaks it into multiple pieces to be loaded in parallel. To my knowledge, such a tool does not yet exist.</p>
<hr>
<h2>Transferring the dump over the Network is usually a win</h2>
<p>To listen for an incoming dump on one host run:</p>
<pre><code>nc -l 7878 > mysql-dump.sql
</code></pre>
<p>Then on your DB host, run</p>
<pre><code>mysqldump $OPTS | nc myhost.mydomain.com 7878
</code></pre>
<p>This reduces contention for the disk spindles on the master from writing the dump to disk slightly speeding up your dump (assuming the network is fast enough to keep up, a fairly safe assumption for two hosts in the same datacenter). Plus, if you are building out a new slave, this saves the step of having to transfer the dump file after it is finished. </p>
<p>Caveats - obviously, you need to have enough network bandwidth not to slow things down unbearably, and if the TCP session breaks, you have to start all over, but for most dumps this is not a major concern.</p>
<hr>
<p>Lastly, I want to clear up one point of common confusion. </p>
<p>Despite how often you see these flags in mysqldump examples and tutorials, they are superfluous because they are turned ON by default:</p>
<ul>
<li><code>--opt</code></li>
<li><code>--add-drop-table</code></li>
<li><code>--add-locks</code></li>
<li><code>--create-options</code></li>
<li><code>--disable-keys</code></li>
<li><code>--extended-insert</code></li>
<li><code>--lock-tables</code></li>
<li><code>--quick</code></li>
<li><code>--set-charset</code>. </li>
</ul>
<p>From <a href="http://dev.mysql.com/doc/refman/5.1/en/mysqldump.html" rel="noreferrer">http://dev.mysql.com/doc/refman/5.1/en/mysqldump.html</a>:</p>
<blockquote>
<p>Use of --opt is the same as specifying --add-drop-table, --add-locks, --create-options, --disable-keys, --extended-insert, --lock-tables, --quick, and --set-charset. All of the options that --opt stands for also are on by default because --opt is on by default.</p>
</blockquote>
<p>Of those behaviors, "--quick" is one of the most important (skips caching the entire result set in mysqld before transmitting the first row), and can be with "mysql" (which does NOT turn --quick on by default) to dramatically speed up queries that return a large result set (eg dumping all the rows of a big table).</p>
|
<p>Use mk-parallel-dump tool from Maatkit.</p>
<p>At least that would probably be faster. I'd trust mysqldump more.</p>
<p>How often are you doing this? Is it really an application performance problem? Perhaps you should design a way of doing this which doesn't need to dump the whole data (replication?)</p>
<p>On the other hand, 1.5G is quite a small database so it probably won't be much of a problem.</p>
| 15,921
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.