Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
I am writing an Image Manager WPF application. I have a ListBox with the following ItemsTemplate: ``` <Grid x:Name="grid" Width="150" Height="150" Background="{x:Null}"> <Grid.RowDefinitions> <RowDefinition Height="*"/> <RowDefinition Height="27.45"/> </Grid.RowDefinitions> <Grid.ColumnDefinitions> <ColumnDefinition Width="150"/> </Grid.ColumnDefinitions> <Border Margin="5,5,5,5.745" Grid.RowSpan="2" Background="#FF828282" BorderBrush="{DynamicResource ListBorder}" CornerRadius="5,5,5,5" BorderThickness="1,1,2,2" x:Name="border"> <Grid> <Viewbox Margin="0,0,0,21.705"> <Image Width="Auto" Height="Auto" x:Name="picture" Source="{Binding Path=FullName}" /> </Viewbox> <TextBlock Height="Auto" Text="{Binding Path=Name}" TextWrapping="Wrap" x:Name="PictureText" HorizontalAlignment="Left" Margin="70,0,0,0" VerticalAlignment="Bottom" /> </Grid> </Border> </Grid> ``` Note that the "Image" control is bound to the "FullName" property, which is a string representing the absolute path to a JPG. Several application features require that I alter the JPG file (move, rename, or delete). When I try to do so (currently trying to Move the file) I receive an IOException: "The process cannot access the file because it is being used by another process." The process locking the file is my WPF application. I did some searching online and found several postings indicating that Images in particular have trouble letting go of their resources. I have tried the following: 1. Setting the ListBox.Source to null 2. Adding a 10 second wait time before attempting the move. 3. Issuing GC.Collect(). 4. Moving the operation to a different thread. What else can I try? I thought about finding a reference to the Image object in the ItemsTemplate and trying to dispose of the Image, but I can't figure out how to get the reference. One possible solution I read about was to create copies of the Images rather than the actual images, but since the Binding is to the filename and not the actual Image I don't know if I could make this work. Any help or suggestions would be most appreciated.
My [Intuipic](http://intuipic.codeplex.com) application allows users to delete images, too. I had to write [this converter](http://intuipic.codeplex.com/SourceControl/changeset/view/7348#114513) to achieve it. Relevant code: ``` //create new stream and create bitmap frame BitmapImage bitmapImage = new BitmapImage(); bitmapImage.BeginInit(); bitmapImage.StreamSource = new FileStream(path, FileMode.Open, FileAccess.Read); bitmapImage.DecodePixelWidth = (int) _decodePixelWidth; bitmapImage.DecodePixelHeight = (int) _decodePixelHeight; //load the image now so we can immediately dispose of the stream bitmapImage.CacheOption = BitmapCacheOption.OnLoad; bitmapImage.EndInit(); //clean up the stream to avoid file access exceptions when attempting to delete images bitmapImage.StreamSource.Dispose(); ```
I marked Kent's response as an answer, and I would have marked bendewey's as well, because I used both of them in the final solution. The file was definitely locked because the file name was all that was being bound, so the Image control opened the actual file to produce the image. To Solve this, I created a Value Converter like bendewey suggested, and then I used (most of) the code form Kent's suggestion to return a new BitmapImage: ``` [ValueConversion(typeof(string), typeof(BitmapImage))] public class PathToBitmapImage : IValueConverter { public static BitmapImage ConvertToImage(string path) { if (!File.Exists(path)) return null; BitmapImage bitmapImage = null; try { bitmapImage = new BitmapImage(); bitmapImage.BeginInit(); bitmapImage.StreamSource = new FileStream(path, FileMode.Open, FileAccess.Read); bitmapImage.CacheOption = BitmapCacheOption.OnLoad; bitmapImage.EndInit(); bitmapImage.StreamSource.Dispose(); } catch (IOException ioex) { } return bitmapImage; } #region IValueConverter Members public virtual object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { if (value == null || !(value is string)) return null; var path = value as string; return ConvertToImage(path); } public virtual object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { throw new NotImplementedException(); } #endregion } ``` As the comments suggest above, however, this did not solve the problem. I have been away on other projects and recently returned to this one reinvigorated to find the solution. I created another project that only tested this code, and of course it worked. This told me that there was more amiss in the original program. Long story short, the Image was being generated in three places, which I thought had been addressed: 1) The ImageList, now bound using the Converter. 2) The main Image which was bound to the ImageList SelectedItem property. 3) The DeleteImage popup, which was bound using the Converter. It turns out the problem was in #2. By binding to the SelectedItem, I mistakenly assumed I was binding to the newly rendered Image (based on the Converter). In reality, the SelectedItem object was in fact the file name. This meant that the main Image was again being built by directly accessing the file. So the solution was to bind the main Image control to the SelectedItem property AND employ the Converter.
Delete an image bound to a control
[ "", "c#", "wpf", "file-io", "" ]
I have a string that looks something like the following 'test:1;hello:five;just:23'. With this string I need to be able to do the following. ``` .... var test = MergeTokens('test:1;hello:five;just:23', 'yes:23;test:567'); ... ``` The end result should be 'test:567;hello:five;just:23;yes:23' (note the exact order of the tokens is not that important). Just wondering if anyone has any smart ideas of how to go about this. I was thinking a regex replace on each of the tokens on right and if a replace didn't occur because there was not match just append it. But maybe there is better way. Cheers Anthony Edit: The right side should override the left. The left being what was originally there and the right side being the new content. Another way of looking at it, is that you only keep the tokens on the left if they don't exist on the right and you keep all the tokens on the right. **@Ferdinand** Thanks for the reply. The problem is the efficiency with which the solution you proposed. I was initially thinking down similar lines but discounted it due to the O(n\*z) complexity of the merge (where n and z is the number tokens on the left and right respectively) let alone the splitting and joining. Hence why I was trying to look down the path of a regex. Maybe behind the scenes, regex is just as bad or worse, but having a regex which removes any token from the left string that exists on the right (O(n) for the total amount of token on the right) and then just add the 2 string together (i.e. vat test = test1 + test2) seems more efficient. thanks
The following is what I ended thiking about. What do you guys recon? Thanks Anthony ``` function Tokenizer(input, tokenSpacer, tokenValueSpacer) { this.Tokenizer = {}; this.TokenSpacer = tokenSpacer; this.TokenValueSpacer = tokenValueSpacer; if (input) { var TokenizerParts = input.split(this.TokenSpacer); var i, nv; for (i = 0; i < TokenizerParts.length; i++) { nv = TokenizerParts[i].split(this.TokenValueSpacer); this.Tokenizer[nv[0]] = nv[1]; } } } Tokenizer.prototype.add = function(name, value) { if (arguments.length == 1 && arguments[0].constructor == Object) { this.addMany(arguments[0]); return; } this.Tokenizer[name] = value; } Tokenizer.prototype.addMany = function(newValues) { for (nv in newValues) { this.Tokenizer[nv] = newValues[nv]; } } Tokenizer.prototype.remove = function(name) { if (arguments.length == 1 && arguments[0].constructor == Array) { this.removeMany(arguments[0]); return; } delete this.Tokenizer[name]; } Tokenizer.prototype.removeMany = function(deleteNames) { var i; for (i = 0; i < deleteNames.length; i++) { delete this.Tokenizer[deleteNames[i]]; } } Tokenizer.prototype.MergeTokenizers = function(newTokenizer) { this.addMany(newTokenizer.Tokenizer); } Tokenizer.prototype.getTokenString = function() { var nv, q = []; for (nv in this.Tokenizer) { q[q.length] = nv + this.TokenValueSpacer + this.Tokenizer[nv]; } return q.join(this.TokenSpacer); } Tokenizer.prototype.toString = Tokenizer.prototype.getTokenString; ```
I would use `join()` and `split()` to create some utility functions to pack and unpack your token data to an object: ``` // Unpacks a token string into an object. function splitTokens(str) { var data = {}, pairs = str.split(';'); for (var i = 0; i < pairs.length; ++i) { var pair = pairs[i].split(':'); data[pair[0]] = pair[1]; } return data; } // Packs an object into a token string. function joinTokens(data) { var pairs = []; for (var key in data) { pairs.push(key + ":" + data[key]); } return pairs.join(';'); } ``` Using these, merging is easy: ``` // Merges all token strings (supports a variable number of arguments). function mergeTokens() { var data = {}; for (var i = 0; i < arguments.length; ++i) { var d = splitTokens(arguments[i]); for (var key in d) { data[key] = d[key]; } } return joinTokens(data); } ``` The utility functions are also useful if you want to extract some keys (say,"test") and/or check for existence: ``` var data = splitTokens(str); if (data["test"] === undefined) { // Does not exist } else { alert("Value of 'test': " + data["test"]); } ```
Javascript token replace/append
[ "", "javascript", "regex", "merge", "replace", "token", "" ]
How can we check which database locks are applied on which rows against a query batch? Any tool that highlights table row level locking in real time? DB: SQL Server 2005
To add to the other responses, `sp_lock` can also be used to dump full lock information on all running processes. The output can be overwhelming, but if you want to know exactly what is locked, it's a valuable one to run. I usually use it along with `sp_who2` to quickly zero in on locking problems. There are multiple different versions of "friendlier" `sp_lock` procedures available online, depending on the version of SQL Server in question. In your case, for SQL Server 2005, `sp_lock` is still available, but deprecated, so it's now recommended to use the [`sys.dm_tran_locks`](http://msdn.microsoft.com/en-us/library/ms190345.aspx) view for this kind of thing. You can find an example of how to "roll your own" sp\_lock function [here](http://www.techrepublic.com/blog/the-enterprise-cloud/write-your-own-sp-lock-system-stored-procedure-in-sql-server-2005/).
This is not exactly showing you which rows are locked, but this may helpful to you. You can check which statements are blocked by running this: ``` select cmd,* from sys.sysprocesses where blocked > 0 ``` It will also tell you what each block is waiting on. So you can trace that all the way up to see which statement caused the first block that caused the other blocks. **Edit** to add comment from [@MikeBlandford](https://stackoverflow.com/users/28643/mike-blandford): > The blocked column indicates the spid of the blocking process. You can run kill {spid} to fix it.
How to check which locks are held on a table
[ "", "sql", "sql-server", "database", "performance", "sql-server-2005", "" ]
The list of jars just takes up too much space. Can I collapse it or hide it?
In the Project Explorer : * Customize View * Check `Libraries from external` [![enter image description here](https://i.stack.imgur.com/8PYAM.png)](https://i.stack.imgur.com/8PYAM.png) [![enter image description here](https://i.stack.imgur.com/l4B1i.png)](https://i.stack.imgur.com/l4B1i.png) Or in the Package Explorer : * Uncheck the 'Show Referenced Libraries Node' * Add a filter to hide "\*.jar" files
Another solution would be using the Package Explorer view.
Remove project .jars from project explorer view in Eclipse
[ "", "java", "eclipse", "ide", "jar", "classpath", "" ]
I'm having a problem implementing custom 404 error pages on my Windows/IIS/PHP webhost. Whenever I try to send the 404 status message in the header, no content is sent to the client and a blank page is displayed instead. Here is a very simple script I'm using: ``` <?php header('HTTP/1.1 404 Not Found'); header('Status: 404 Not Found'); var_dump(headers_list()); ?> ``` On my dev machine the output (displayed in a browser) is ``` array(2) { [0]=> string(23) "X-Powered-By: PHP/5.2.6" [1]=> string(21) "Status: 404 Not Found" } ``` On my host there is no output. I can't seem to generate anything but a blank page regardless of what content is echoed by PHP, or included below as normal HTML, though PHP processing e.g. logging, database writes etc continue as normal. Can anyone suggest what the problem might be or how to resolve it?
If PHP is configured at your host to run through CGI, it may be impossible to generate 404 error pages in IIS (except by lying and returning 200 OK, which is a Bad Thing). Certainly I've been unable to persuade IIS 4-6.0 to allow my CGI 404 errors through to browsers. You generally don't want PHP to run CGI anyway, there are other related problems as well as it being slow. On IIS, the PHP ISAPI extension should be preferred (though as I've not tried it I can't confirm it solves this specific problem).
'blank page' smells like error\_reporting(0) hiding the error messages you would get. Maybe there is some output before your headers and that raises an error. Check that.
PHP 404 error page won't display content
[ "", "php", "header", "http-status-code-404", "" ]
When processing XML by means of standard DOM, attribute order is not guaranteed after you serialize back. At last that is what I just realized when using standard java XML Transform API to serialize the output. However I do need to keep an order. I would like to know if there is any posibility on Java to keep the original order of attributes of an XML file processed by means of DOM API, or any way to force the order (maybe by using an alternative serialization API that lets you set this kind of property). In my case processing reduces to alter the value of some attributes (not all) of a sequence of the same elements with a bunch of attributes, and maybe insert a few more elements. Is there any "easy" way or do I have to define my own XSLT transformation stylesheet to specify the output and altering the whole input XML file? **Update** I must thank all your answers. The answer seems now more obvious than I expected. I never paid any attention to attribute order, since I had never needed it before. The main reason to require an attribute order is that the resulting XML file just *looks* different. The target is a configuration file that holds hundreds of alarms (every alarm is defined by a set of attributes). This file usually has little modifications over time, but it is convenient to keep it ordered, since when we need to modify something it is edited by hand. Now and then some projects need light modifications of this file, such as setting one of the attributes to a customer specific code. I just developed a little application to merge original file (common to all projects) with specific parts of each project (modify the value of some attributes), so project-specific file gets the updates of the base one (new alarm definitions or some attribute values bugfixes). My main motivation to require ordered attributes is to be able to check the output of the application againts the original file by means of a text comparation tool (such as Winmerge). If the format (mainly attribute order) remains the same, the differences can be easily spotted. I really thought this was possible, since XML handling programs, such as XML Spy, lets you edit XML files and apply some ordering (grid mode). Maybe my only choice is to use one of these programs to *manually* modify the output file.
Sorry to say, but the answer is more subtle than "No you can't" or "Why do you need to do this in the first place ?". The short answer is "DOM will not allow you to do that, but SAX will". This is because DOM does not care about the attribute order, since it's meaningless as far as the standard is concerned, and by the time the XSL gets hold of the input stream, the info is already lost. Most XSL engine will actually gracefully preserve the input stream attribute order (e.g. Xalan-C (except in one case) or Xalan-J (always)). Especially if you use `<xsl:copy*>`. Cases where the attribute order is not kept, best of my knowledge, are. - If the input stream is a DOM - Xalan-C: if you insert your result-tree tags literally (e.g. `<elem att1={@att1} .../>` Here is one example with SAX, for the record (inhibiting DTD nagging as well). ``` SAXParserFactory spf = SAXParserFactoryImpl.newInstance(); spf.setNamespaceAware(true); spf.setValidating(false); spf.setFeature("http://xml.org/sax/features/validation", false); spf.setFeature("http://apache.org/xml/features/nonvalidating/load-dtd-grammar", false); spf.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false); SAXParser sp = spf.newSAXParser() ; Source src = new SAXSource ( sp.getXMLReader(), new InputSource( input.getAbsolutePath() ) ) ; String resultFileName = input.getAbsolutePath().replaceAll(".xml$", ".cooked.xml" ) ; Result result = new StreamResult( new File (resultFileName) ) ; TransformerFactory tf = TransformerFactory.newInstance(); Source xsltSource = new StreamSource( new File ( COOKER_XSL ) ); xsl = tf.newTransformer( xsltSource ) ; xsl.setParameter( "srcDocumentName", input.getName() ) ; xsl.setParameter( "srcDocumentPath", input.getAbsolutePath() ) ; xsl.transform(src, result ); ``` I'd also like to point out, at the intention of many naysayers that there *are* cases where attribute order *does* matter. Regression testing is an obvious case. Whoever has been called to optimise not-so-well written XSL knows that you usually want to make sure that "new" result trees are similar or identical to the "old" ones. And when the result tree are around one million lines, XML diff tools prove too unwieldy... In these cases, preserving attribute order is of great help. Hope this helps ;-)
Look at section 3.1 of the XML recommendation. It says, "Note that the order of attribute specifications in a start-tag or empty-element tag is not significant." If a piece of software requires attributes on an XML element to appear in a specific order, that software is not processing XML, it's processing text that looks superficially like XML. It needs to be fixed. If it can't be fixed, and you have to produce files that conform to its requirements, you can't reliably use standard XML tools to produce those files. For instance, you might try (as you suggest) to use XSLT to produce attributes in a defined order, e.g.: ``` <test> <xsl:attribute name="foo"/> <xsl:attribute name="bar"/> <xsl:attribute name="baz"/> </test> ``` only to find that the XSLT processor emits this: ``` <test bar="" baz="" foo=""/> ``` because the DOM that the processor is using orders attributes alphabetically by tag name. (That's common but not universal behavior among XML DOMs.) But I want to emphasize something. If a piece of software violates the XML recommendation in one respect, it probably violates it in other respects. If it breaks when you feed it attributes in the wrong order, it probably also breaks if you delimit attributes with single quotes, or if the attribute values contain character entities, or any of a dozen other things that the XML recommendation says that an XML document can do that the author of this software probably didn't think about.
Order of XML attributes after DOM processing
[ "", "java", "xml", "dom", "" ]
### Duplicate of > [Any value in double script tags?](https://stackoverflow.com/questions/691449/any-value-in-double-script-tags) Here's a code snipped from UserVoice in order to stick their tab on my site (this isn't specific to UserVoice however, I see this kind of thing all the time): ``` <script type="text/javascript"> var uservoiceJsHost = ("https:" == document.location.protocol) ? "https://uservoice.com" : "http://cdn.uservoice.com"; document.write(unescape("%3Cscript src='" + uservoiceJsHost + "/javascripts/widgets/tab.js' type='text/javascript'%3E%3C/script%3E")) </script> <script type="text/javascript"> UserVoice.Tab.show({ key: 'wikipediamaze', host: 'wikipediamaze.uservoice.com', forum: 'general', alignment: 'right', /* 'left', 'right' */ background_color: '#94C97B', text_color: 'white', /* 'white', 'black' */ hover_color: '#7AA1C5', lang: 'en' /* 'en', 'de', 'nl', 'es', 'fr' */ }) </script> ``` How this can't all be jammed into one script tag and put into a separate file? Any time I try do it, it doesn't work. Google ads does the same kind of thing. Why are there 2 separate script declarations?
Look at the code in the first script tag, it's writing another script tag to the page. The code in the second script tag is using a function that is in the file that is loaded by the written script tag, so it has to be in a separate tag as the file is not loaded until the first code has been executed. You could put the scripts in separate files, but you still need to load them using two separate script tags as the first one has to be executed before the second one loads.
JavaScript gets executed as it is loaded so the position of the script on the page may have some importance. It really depends on the page and the script. Also, it is very common for web components and libraries to have their own scripts, so if you have many components on a page they could all have separate scripts tags for their individual scripts.
Why is JavaScript always broken up into separate <script> sections?
[ "", "javascript", "html", "" ]
Why are most priority/heap queues implemented as 0 being the highest priority? I'm assuming I'm missing out some key mathematical principle. As I was implementing my own priority queue recently it seemed easier to write the insert function if priority went up with the integer value, but apparently people smarter than me think it should go the other way. Any ideas?
Most priority queues are implemented as a [fibonacci heap](http://en.wikipedia.org/wiki/Fibonacci_heap) or something similar. That data structure supports extracting the minimum in constant time, which makes it natural to make 0 the highest priority, and take elements out of the queue by extracting the minimum.
If it's ever increasing, how could you ever set anything to the highest priority? (+1 for rossfab's answer :)
Why do priority queues mostly use 0 as the most important priority?
[ "", "c++", "algorithm", "data-structures", "queue", "" ]
It seems everyone is doing this (in code posts etc.)...but I don't know how. :( Whenever I try to manipulate an asp element using JavaScript I get an `"element is null"` or `"document is undefined"` etc. error..... JavaScript works fine usually,...but only when I add the `runat="server"` attribute does the element seem invisible to my JavaScript. Any suggestions would be appreciated. Thanks, Andrew
What's probably happening is that your element/control is within one or more ASP.NET controls which act as naming containers (Master page, ITemplate, Wizard, etc), and that's causing its ID to change. You can use "view source" in your browser to confirm that's what's happening in the rendered HTML. If your JavaScript is in the ASPX page, the easiest way to temporarily work around that is to [use the element's ClientID property](http://encosia.com/2007/08/08/robust-aspnet-control-referencing-in-javascript/). For example, if you had a control named TextBox1 that you wanted to reference via JS: ``` var textbox = document.getElementById('<%= TextBox1.ClientID %>'); ```
Making an element `runat="server"` changes the client-side ID of that element based on what ASP.NET naming containers it's inside of. So if you're using `document.getElementById` to manipulate the element, you'll need to pass it the new ID generated by .NET. Look into the [ClientId](http://msdn.microsoft.com/en-us/library/system.web.ui.control.clientid.aspx "Control.ClientId") property to get that generated ID...you can use it inline in your Javascript like so: ``` var element = document.getElementById('<%=myControl.ClientID%>'); ```
How can I access runat="server" ASP element using javascript?
[ "", "asp.net", "javascript", "runatserver", "" ]
I am attempting to implement global error handling in my MVC application. I have some logic inside my `Application_Error` that redirects to an `ErrorController` but it's not working. I have a break point inside my `Application_Error` method in the the `Global.aspx`. When I force an exception the break point is not being hit. Any ideas why?
You can try this approach for testing: ``` protected void Application_Error(object sender, EventArgs e) { var error = Server.GetLastError(); Server.ClearError(); Response.ContentType = "text/plain"; Response.Write(error ?? (object) "unknown"); Response.End(); } ``` Web.config ``` <customErrors mode="Off" /> ``` * [Rich Custom Error Handling with ASP.NET](http://msdn.microsoft.com/en-us/library/aa479319.aspx) * [How to: Handle Application-Level Errors](http://msdn.microsoft.com/en-us/library/24395wz3.aspx)
I think a better way to handle this would be using the [HandleErrorAttribute](http://msdn.microsoft.com/en-us/library/system.web.mvc.handleerrorattribute.aspx) to decorate your controller (perhaps a base controller). This would give you the option to do logging or handle errors in different controllers with different errors by extending this attribute and modifying it to fit your needs, say by changing the view that gets rendered. Using this attribute uses the standard filter processing in MVC and builds the page using views rather than writing directly to the response as you might do using Application\_Error.
MVC Global error handling: Application_Error not firing
[ "", "c#", "asp.net-mvc", "error-handling", "" ]
I have the following UPDATE scenario: ``` UPDATE destTable d SET d.test_count = ( SELECT COUNT( employee_id ) FROM sourceTable s WHERE d.matchCode1 = s.matchCode1 AND d.matchCode2 = s.matchCode2 AND d.matchCode3 = s.matchCode3 GROUP BY matchCode1, matchCode2, matchCode3, employee_id ) ``` I have to execute this in a loop changing out the match codes for each iteration. Between two large tables (~500k records each), this query takes an unacceptably long time to execute. If I just had to execute it once, I wouldn't care too much. Given it is being executed about 20 times, it takes way too long for my needs. It requires two full table scans (one for the destTable and another for the subquery). Questions: 1. What techniques do you recommend to speed this up? 2. Does the SQL-optimizer run the subquery for each row I'm updating in the destTable to satisfy the where-clause of the subquery or does it have some super intelligence to do this all at once?
In `Oracle 9i` and higher: ``` MERGE INTO destTable d USING ( SELECT matchCode1, matchCode2, matchCode3, COUNT(employee_id) AS cnt FROM sourceTable s GROUP BY matchCode1, matchCode2, matchCode3, employee_id ) so ON d.matchCode1 = s.matchCode1 AND d.matchCode2 = s.matchCode2 AND d.matchCode3 = s.matchCode3 WHEN MATCHED THEN UPDATE SET d.test_count = cnt ``` To speed up your query, make sure you have a composite index on `(matchCode1, matchCode2, matchCode3)` in `destTable`, and a composite index on `(matchCode1, matchCode2, matchCode3, employee_id)` in `sourceTable`
> I have to execute this in a loop The first thing you do is build the loop into your sub query or where clause. You're updating data, and then immediately replacing some of the data you just updated. You should be able to either filter your update to only change records appropriate to the current iteration or make your query complex enough to update everything in one statement- probably both.
How do I improve performance of a SQL UPDATE statement whose SET involves an expensive aggregate subquery?
[ "", "sql", "oracle", "performance", "" ]
**Question** I program in C (ANSI C89/ISO C90) in a \*n\*x environment on a regular basis. I am now in a position where it would be beneficial for me to learn a web-development language. In particular, I'm looking to learn a language which: 1. ...exploits my background as a C programmer. 2. ...can produce the level of interactiveness of a web-site like stackoverflow.com. I hear many good things about PHP. Do any of you have other suggestions? **Notes** 1. Other languages I am familiar with: Java, Perl, Tcsh, and Scheme. 2. I forgot to mention that I'm interested in learning a web-development language which is capable of doing things on the client-side. I'm sorry if this was unclear. 3. I plan to use my knowledge of the language to develop a web-site which is stylistically similar to stackoverflow.com (with a very different concept, of course).
If you already know C, Perl and Java then in all honesty you already know PHP, you just don't know it yet. Make sense? Perhaps not. But it will once you start playing with it. You don't say why you're learning a Web development language or what it's for. That's key information in providing any sort of recommendation like this. In the absence of such information I would suggest PHP for several reasons: * It's Web-centric; * It's extremely popular. Finding answers to problems is very easy; * It's very easy to learn (you already know C, Perl, and Java, but its easy even if you didn't) * As [Cal Henderson](http://en.wikipedia.org/wiki/Cal_Henderson) put it in his keynote ["Why I Hate Django"](http://www.youtube.com/watch?v=i6Fr65PFqfk) (at DjangoCon 2008 no less) "PHP is a serious language". It powers 4 of the top 20 sites on the internet (Wikipedia, Flickr, Facebook and one other I forget; * It's not too dissimilar to Perl although Perl does have a somewhat differen typing system and regular expressions are more first-class in Perl. Plus PHP doesn't have the $\_ operator but in spite of all that there are many similarities; * As a dynamic scripted language, it'll help you get out of the strongly-typed mould, which should make for a bit of a change and useful experience; * In spite of PHP supporting objects (I subscribe to the view that [PHP is not object-oriented](http://michaelkimsal.com/blog/php-is-not-object-oriented/)), most PHP is written in a procedural fashion, making it more familiar to the C programmer; * It has an incredibly rich set of libraries; * Requiring only Apache, it's extremely lightweight and, as a result, hosting is extraordinarily cheap compared to Java or ASP.NET hosting; and * There is something satisfying about just saving your text file and clicking reload on your browser to see what happens rather than having separate compile, build and deployment steps.
PHP's syntax is quite similar to C. However, it has its differences, you can't manage pointers and memory (at least, not that I know). It is also very easy. PHP is a server side language, so browsers do not have anything to do with it. They'll all get the same HTML/CSS information and there is where they differ. If you want to have a level of interactiveness like this website, you should take a look at Javascript (and it's frameworks (i.e.: jQuery). This language is responsible for the client side in web-development.
Which web-development language is best for a C programmer?
[ "", "php", "c", "" ]
I have the following code that tries to enumerate strings. ``` #include <string> #include <iostream> using namespace std; string base = "000"; char values[] = {'0', '1', '2', '3' }; // Error Here for (int i = 0; i < base.length(); ++i) { for (int j = 0; j < countof(values); ++j) { if (base[i] != values[j]) { string copy = base; copy[i] = values[j]; cout << copy << endl; for (int k = i+1; k < base.length(); ++k) { for (int l = 0; l < countof(values); ++l) { if (copy[k] != values[l]) { string copy2 = copy; copy[k] = values[l]; cout << copy2 << endl; } } } } } } ``` But how come upon compilation it gave error: ``` test.cc:9: error: expected unqualified-id before 'for' test.cc:9: error: expected constructor, destructor, or type conversion before '<' token test.cc:9: error: expected unqualified-id before '++' token ```
The error is actually in the following line, at the `for` loop: your code needs to be contained in a function of some sort, most likely `int main(void)`
You are missing a main. Try: ``` #include <string> #include <iostream> using namespace std; string base = "000"; char values[] = {'0', '1', '2', '3' }; // Error Here int main() // Added { // Added for (int i = 0; i < base.length(); ++i) { for (int j = 0; j < countof(values); ++j) { if (base[i] != values[j]) { string copy = base; copy[i] = values[j]; cout << copy << endl; for (int k = i+1; k < base.length(); ++k) { for (int l = 0; l < countof(values); ++l) { if (copy[k] != values[l]) { string copy2 = copy; copy[k] = values[l]; cout << copy2 << endl; } } } } } } return 0; // Added } // Added ```
Howto Construct Char Arrays
[ "", "c++", "arrays", "" ]
**Scenario:** There is a complex piece of software that is annoying to launch by hand. What I've done is to create a python script to launch the executable and attach *gdb* for debugging. The process launching script: * ensures an environment variable is set. * ensures a local build directory gets added to the environment's `LD_LIBRARY_PATH` variable. * changes the current working directory to where the executable expects to be (not my design) * launches the executable with a config file the only command line option * pipes the output from the executable to a second logging process * remembers PID of executable, then launches & attaches gdb to running executable. The script works, with one caveat. **ctrl-c doesn't interrupt the debugee and return control to gdb.** So if I "continue" with no active breakpoints I can never stop the process again, it has to be killed/interrupted from another shell. BTW, running "kill -s SIGINT <pid>" where <pid> is the debuggee's pid does get me back to gdb's prompt... but it is really annoying to have to do things this way At first I thought Python was grabbing the SIGINT signal, but this doesn't seem to be the case as I set up signal handlers forward the signal to the debugee and that doesn't fix the problem. I've tried various configurations to the python script (calling os.spawn\* instead of subprocess, etc.) It seems that any way I go about it, if python launched the child process, SIGINT (ctrl-c) signals DO NOT to get routed to gdb or the child process. **Current line of thinking** * This might be related to needing a separate process group id for the debugee & gdb...any credence to this? * Possible bug with SELinux? **Info:** * gdb 6.8 * Python 2.5.2 (problem present with Python 2.6.1 as well) * SELinux Environment (bug delivering signals to processes?) **Alternatives I've considered:** * Setting up a .gdbinit file to do as much of what the script does, environment variables and current working directory are a problem with this approach. * Launching executable and attaching gdb manually (yuck) **Question:** How do you automate the launching/debugging of large scale projects? **Update:** I've tried Nicholas Riley's examples below, on my Macintosh at home they all allow cntl-c to work to varrying degrees, on the production boxen (which I now to believe may be running SELinux) they don't...
Instead of forwarding the signal to the debuggee from Python, you could try just ignoring it. The following worked for me: ``` import signal signal.signal(signal.SIGINT, signal.SIG_IGN) import subprocess cat = subprocess.Popen(['cat']) subprocess.call(['gdb', '--pid=%d' % cat.pid]) ``` With this I was able to ^C repeatedly inside GDB and interrupt the debuggee without a problem, however I did see some weird behavior. Incidentally, I also had no problem when forwarding the signal to the target process. ``` import subprocess cat = subprocess.Popen(['cat']) import signal, os signal.signal(signal.SIGINT, lambda signum, frame: os.kill(cat.pid, signum)) subprocess.call(['gdb', '--pid=%d' % cat.pid]) ``` So, maybe something else is going on in your case? It might help if you posted some code that breaks.
if you already have a current script set up to do this, but are having problems automating part of it, maybe you can just grab expect and use it to provide the setup, then drop back into interactive mode in expect to launch the process. Then you can still have your ctrl-c available to interrupt.
How do you automate the launching/debugging of large scale projects?
[ "", "python", "debugging", "gdb", "subprocess", "selinux", "" ]
Is there an easy way to get DataContractSerializer to spit out formatted XML rather then one long string? I don't want to change the tags or content in any way, just have it add line breaks and indentation to make the XML more readable? ``` <tagA> <tagB>This is</tagB> <tagC>Much</tagC> <tagD> <tagE>easier to read</tagE> </tagD> </tagA> <tagA><tagB>This is</tagB><tagC>Much</tagC><tagD><tagE>harder to read</tagE></tagD></tagA> ```
As bendewey says, XmlWriterSettings is what you need - e.g. something like ``` var ds = new DataContractSerializer(typeof(Foo)); var settings = new XmlWriterSettings { Indent = true }; using (var w = XmlWriter.Create("fooOutput.xml", settings)) ds.WriteObject(w, someFoos); ```
Take a look at the `Indent` property of the [`XmlWriterSettings`](http://msdn.microsoft.com/en-us/library/system.xml.xmlwritersettings_properties.aspx) **Update:** Here is a good link from MSDN on [How to: Specify the Output format on the XmlWriter](http://msdn.microsoft.com/en-us/library/kbef2xz3(VS.80).aspx) Additionally, here is a sample: ``` class Program { static void Main(string[] args) { var Mark = new Person() { Name = "Mark", Email = "mark@example.com" }; var serializer = new DataContractSerializer(typeof(Person)); var settings = new XmlWriterSettings() { Indent = true, IndentChars = "\t" }; using (var writer = XmlWriter.Create(Console.Out, settings)) { serializer.WriteObject(writer, Mark); } Console.ReadLine(); } } public class Person { public string Name { get; set; } public string Email { get; set; } } ```
Formatting of XML created by DataContractSerializer
[ "", "c#", "xml", "formatting", "datacontractserializer", "" ]
I'm writing a Windows service that runs a variable length activity at intervals (a database scan and update). I need this task to run frequently, but the code to handle isn't safe to run multiple times concurrently. How can I most simply set up a timer to run the task every 30 seconds while never overlapping executions? (I'm assuming `System.Threading.Timer` is the correct timer for this job, but could be mistaken).
You could do it with a Timer, but you would need to have some form of locking on your database scan and update. A simple `lock` to synchronize may be enough to prevent multiple runs from occurring. That being said, it might be better to start a timer AFTER your operation is complete, and just use it one time, then stop it. Restart it after your next operation. This would give you 30 seconds (or N seconds) between events, with no chance of overlaps, and no locking. Example : ``` System.Threading.Timer timer = null; timer = new System.Threading.Timer((g) => { Console.WriteLine(1); //do whatever timer.Change(5000, Timeout.Infinite); }, null, 0, Timeout.Infinite); ``` *Work immediately .....Finish...wait 5 sec....Work immediately .....Finish...wait 5 sec....*
I'd use Monitor.TryEnter in your elapsed code: ``` if (Monitor.TryEnter(lockobj)) { try { // we got the lock, do your work } finally { Monitor.Exit(lockobj); } } else { // another elapsed has the lock } ```
Synchronizing a timer to prevent overlap
[ "", "c#", "multithreading", "timer", "overlap", "" ]
I had been using [Ternary Search Tree](http://en.wikipedia.org/wiki/Ternary_search_tree) for a while, as the data structure to implement a auto complete drop down combo box. Which means, when user type "fo", the drop down combo box will display foo food football The problem is, my current used of Ternary Search Tree is case sensitive. My implementation is as follow. It had been used by real world for around 1++ yeas. Hence, I consider it as quite reliable. [My Ternary Search Tree code](http://jstock.cvs.sourceforge.net/viewvc/jstock/jstock/src/org/yccheok/jstock/engine/TernarySearchTree.java?view=markup) However, I am looking for a case insensitive Ternary Search Tree, which means, when I type "fo", the drop down combo box will show me foO Food fooTBall Here are some key interface for TST, where I hope the new case insentive TST may have similar interface too. ``` /** * Stores value in the TernarySearchTree. The value may be retrieved using key. * @param key A string that indexes the object to be stored. * @param value The object to be stored in the tree. */ public void put(String key, E value) { getOrCreateNode(key).data = value; } /** * Retrieve the object indexed by key. * @param key A String index. * @return Object The object retrieved from the TernarySearchTree. */ public E get(String key) { TSTNode<E> node = getNode(key); if(node==null) return null; return node.data; } ``` An example of usage is as follow. TSTSearchEngine is using TernarySearchTree as the core backbone. [Example usage of Ternary Search Tree](http://jstock.cvs.sourceforge.net/viewvc/jstock/jstock/src/org/yccheok/jstock/engine/TSTSearchEngine.java?revision=1.2&view=markup) ``` // There is stock named microsoft and MICROChip inside stocks ArrayList. TSTSearchEngine<Stock> engine = TSTSearchEngine<Stock>(stocks); // I wish it would return microsoft and MICROCHIP. Currently, it just return microsoft. List<Stock> results = engine.searchAll("micro"); ```
One of the key factor which make my current Ternary Search Tree difficult to support case insensitive search is that, my underlying data structure is one-to-one mapping. Please look at the following test code : ``` public void testPut() { System.out.println("put"); Name name0 = new Name("abc"); Name name1 = new Name("abc"); TernarySearchTree<Name> instance = new TernarySearchTree<Name>(); instance.put(name0.toString(), name0); instance.put(name1.toString(), name1); assertEquals(2, instance.matchPrefix("a").size()); // fail here. Result is 1 } ``` What my current short-term solution is that, I am using TSTSearchEngine to wrap up the whole TernarySearchTree. TSTSearchEngine is comprised of (1) A TernarySearchTree, providing UPPER-CASE key to map. (2) A String-To-ArrayList map. Here is what happen when I perform : ``` TSTSearchEngine<Name> engine = TSTSearchEngine<Name>(); engine.put(name0); // name0 is new Name("Abc"); engine.put(name1); // name0 is new Name("aBc"); ``` (1) name0.toString() will be converted to UPPER-CASE ("ABC"). It will be inserted to TernarySearchTree. "ABC" will be both key and value for TernarySearchTree. (2) "ABC" will use as the key for map, to insert name0 into an array list. (3) name1.toString() will be converted to UPPER-CASE ("ABC"). It will be inserted to TernarySearchTree. S1 will be both key and value for TernarySearchTree. (4) "ABC" will use as the key for map, to insert name1 into an array list. When I try to ``` engine.searchAll("a"); ``` (1) TernarySearchTree will return "ABC". (2) "ABC" will be used as the key to access map. Map will return an array list, which is containing name0 and name1. This solution works. The sample code can be referred to [Sample Code for New TSTSearchEngine](http://jstock.cvs.sourceforge.net/viewvc/jstock/jstock/src/org/yccheok/jstock/engine/TSTSearchEngine.java?view=markup) However, this may not be an effective solution, as it requires two pass of search. I find out there is an implementation in C++ [C++ Implementation of Case Insensitive Ternary Search Tree](http://www.abc.se/~re/code/tst/tst_docs/tst_usage.html#usage_custom_comp). Hence, there is an opportunity that C++ code can be ported over to Java.
I haven't used a TST before, but isn't this as simple as lower or uppercasing your keys, both during storage and during lookup? From your code snippet it looks like that should work.
Case Insensitive Ternary Search Tree
[ "", "java", "data-structures", "ternary-tree", "ternary-search-tree", "" ]
I need to create a simple hashing method for passing some data in a URL. It doesn't need to be very secure, it just shouldn't be obvious to most people. The hash needs to contains the numerical id of the sender and the id of the recipient and I should be able to decode the data after reading the appended hash. Any ideas? I'd like the hash to be a short as possible, simply because this url is meant to be shared via IM, email, etc..
Hash is one way only. If you want to decrypt it, you have to encrypt it. Try [mcrypt](http://php.net/manual/en/function.mcrypt-encrypt.php) with [one of these](http://php.net/manual/en/mcrypt.ciphers.php). For non secure stuff you can try [base64\_encode](http://php.net/manual/en/function.base64-encode.php), You can also [base\_convert](http://php.net/manual/en/function.base-convert.php) each numeric id from 10 to 36 digits or so. Multiplying the numbers with a secret constant could also help. ``` $obscurity = base_convert($recipientId * 42, 10, 36) . ':' . base_convert($senderId * 42, 10, 36) ```
Try base64 encoding/decoding. put together with the apache option "Multiviews" or apache mod\_rewrite, would make your urls look like: ``` http://mysite.com/messages/[encoded string here] ```
Need a simple hash in PHP
[ "", "php", "encryption", "" ]
Using PHP and MySQL, I want to query a table of postings my users have made to find the person who has posted the most entries. What would be the correct query for this? Sample table structure: ``` [id] [UserID] 1 johnnietheblack 2 johnnietheblack 3 dannyrottenegg 4 marywhite 5 marywhite 6 johnnietheblack ``` I would like to see that "johnnietheblack" is the top poster, "marywhite" is second to best, and "dannyrottenegg" has the least
Something like: ``` SELECT COUNT(*) AS `Rows`, UserID FROM `postings` GROUP BY UserID ORDER BY `Rows` DESC LIMIT 1 ``` This gets the number of rows posted by a particular ID, then sorts though the count to find the highest value, outputting it, and the ID of the person. You'll need to replace the 'UserID' and 'postings' with the appropriate column and field though.
I believe this should work... ``` SELECT user_id, COUNT(*) FROM postings ORDER BY COUNT(*) GROUP BY user_id LIMIT 1 ```
How do I find the most common result in a column in my MySQL table
[ "", "php", "mysql", "" ]
In continuation of: [Storing DataRelation in xml?](https://stackoverflow.com/questions/729634/storing-datarelation-in-xml) Thanks to everybody for answers to my earlier thread. However, could I ask the reason why everybody is not supporting this XML based approach? What exactly will be the problems? I can apply connstraints to dataset, and I can, I guess, also use transactions. I am new to this. So if you could point me to some link, where I can find some sort of comparisons, that would be really helpful. According to FAQ, discussions are not very encouraged, but I guess this is quite specific. I hope, not to be fired for this... :) Thanks for reading, Saurabh.
Database management systems are specifically designed to store data and retrieve it quickly, to preserve the integrity of the data and to leverage concurrent access to the data. XML, on the other hand, was originally designed for documents, separating the content from the presentation. It became a handy way to store simple data because the file structure is so well defined, and then it went out of hand with people trying to store entire databases in an unsuited structure. XML doesn't guarantee atomicity, concurrency, integrity, fast access or anything like that. Not inherently, anyway. .NET's DataSet libraries do help in that regard, but just because you can serialize DataSet objects to XML doesn't make it a good place to store data for multiple users. When you're faced with two tools, one which was designed to do exactly what you need to do (in this case a DBMS) and one that was designed to do something else but has been kludged to do what you want, sorta (in this case XML), you should probably go with the first option.
Concurrency will be the main issue, where multiple users want to access the same "database" file. Performance is the other, because the whole file has to be loaded into memory. If the filesize grows it'll get unmanageable. Also, performance on queries is hit, because it won't be as efficient as getting something as tuned and honed as an RDBMS to do it for you.
Datasets and XML in place of proper db: Not a good idea?
[ "", "c#", ".net-3.5", "ado.net", "dataset", "" ]
The following code sample prints: ``` T T[] T[] ``` While first two lines are as expected, why compiler selected param array for a regular array? ``` public class A { public void Print<T>(T t) { Console.WriteLine("T"); } public void Print<T>(params T[] t) { Console.WriteLine("T[]"); } } class Program { static void Main(string[] args) { A a = new A(); a.Print("string"); a.Print("string","string"); a.Print(new string[] {"a","b"}); } } ```
Under the hood ``` a.Print("string","string"); ``` is just syntactic sugar for ``` a.Print(new string[]{"string","string"}); ``` EDIT: Like I said, the `params` keyword only automagically creates the array for you, you tell the compiler: either accept an array of `T` directly or use the X input params to construct that array.
It addition to what others have said, the *params* keyword also causes a ParamArrayAttribute to the generated for array parameter. So, this... ``` public void Print<T>(params T[] t) { } ``` Is generated by the compiler as... ``` public void Print<T>([ParamArray] T[] t); { } ``` It is that attribute which indicates to the compiler and the IDE that the method can be called using simpler syntax... ``` a.Print("string", "string"); ``` rather than... ``` a.Print(new string[] { "string", "string" }); ```
How exactly keyword 'params' work?
[ "", "c#", "generics", "compiler-construction", "parameters", "" ]
Basically I want to create a user control in code behind, DataBind() it and then insert the control into current page I'm currently trying this: ``` var comment = new IncidentHistoryGroupComment(); comment.LoadControl("~/Controls/IncidentHistoryGroupComment.ascx"); comment.LoadTemplate("~/Controls/IncidentHistoryGroupComment.ascx"); comment.InitializeAsUserControl(this); comment.AttachmentActions = group.HastAttachmentActions ? group.AttachmentActions : null; comment.Comment = group.Comment; comment.NextStep = group.NextStep; comment.IsInitiationStep = group.InitializationEntry != null; comment.DataBind(); ``` But still all controls inside it are null. For example i have a pane with id pnlComments and when I try to access it in IncidentHistoryGroupComment.DataBind() method I get null. I also checked Controls property to see if there is something there but Controls.Count == 0 So the question is how to correctly initialize a user control from code behind so that all controls would be assigned to their instances in IncidentHistoryGroupComment.designer.cs so I could access them easily.
Should be something like this: ``` var comment = (IncidentHistoryGroupComment)Page.LoadControl("~/Controls/IncidentHistoryGroupComment.ascx"); ``` Then you just insert into the control tree
``` MyControl myControl = (MyControl)LoadControL("~/MyControl.ascx"); ``` I changed the name of your control for readability.
What is a correct way to initiate user control from code behind
[ "", "c#", "asp.net", "" ]
If the user selects an option in a dropdown box, there must be added a label and a textbox. Using `appendChild`, these elements get added to the end of the `container`. ``` var newFreeformLabel = document.createElement('label'); newFreeformLabel.innerHTML = 'Omschrijving:'; var newFreeformField = document.createElement('input'); newFreeformField.className = 'textfield'; newFreeformField.name = 'factuur_orderregel[]'; var newFreeformSpacer = document.createElement('div'); newFreeformSpacer.className = 'spacer'; container.appendChild(newFreeformLabel); container.appendChild(newFreeformField); container.appendChild(newFreeformSpacer); ``` The issue is that these elements should be inserted at the beginning of `container`, not at the end. Is there a solution to this in PrototypeJS?
As well as `appendChild`, DOM nodes have an [insertBefore](https://developer.mozilla.org/en/DOM/element.insertBefore) method ``` container.insertBefore(newFreeformLabel, container.firstChild); ```
## Modern Solution To add a child to the *beginning* of a parent, use `prepend` ``` parent.prepend(newChild) ``` To add at the *end* of a parent, use `append` ``` parent.append(newChild) ``` In addition, if you want to add relative to another child, use one of these: ``` child1.after(newChild) // [child1, newChild, child2] child1.before(newChild) // [newChild, child1, child2] ``` ## Advanced usage 1. You can pass multiple values (or use spread operator `...`). 2. Any string value will be added as a text element. **Examples:** ``` parent.prepend(newChild, "foo") // [newChild, "foo", child1, child2] const list = ["bar", newChild] parent.append(...list, "fizz") // [child1, child2, "bar", newChild, "fizz"] ``` [Related DOM method](https://stackoverflow.com/a/40444300/974045) - `child.replaceWith` [Documentation](https://developer.mozilla.org/en-US/docs/Web/API/ParentNode/prepend) [Can I Use](https://caniuse.com/#feat=dom-manip-convenience)
Can I insert elements to the beginning of an element using .appendChild()?
[ "", "javascript", "html", "prototypejs", "" ]
I have the code in my urls.py for my generic views; ``` infodict = { 'queryset': Post.objects.all(), 'date_field': 'date', 'template_name': 'index.html', 'template_object_name': 'latest_post_list', } urlpatterns += patterns('django.views.generic.date_based', (r'^gindex/$', 'archive_index', infodict), ) ``` So going to the address /gindex/ will use a generic view with the template of 'index.html'. But since I will have more generic views in this urlpattern, how am I supposed to provide a different template name using the same infodict? I don't want to have to use lots of infodicts, and I can't use the default template name. Please note this also applies to template object name within infodict. Thanks for your help! **Edit**: This is one of my first questions on stackoverflow and I am amazed with the thorough answers! I prefer using the dict constructor which I didn't know about. I find using the python documentation a bit harder as I can't find what i'm looking for usually! Thanks again for all the answers and different approaches.
Use the dict() constructor: ``` infodict = { 'queryset': Post.objects.all(), 'date_field': 'date', 'template_name': 'index.html', 'template_object_name': 'latest_post_list', } urlpatterns = patterns('django.views.generic.date_based', url(r'^gindex/$', 'archive_index', dict(infodict, template_name='gindex.html')), url(r'^hindex/$', 'archive_index', dict(infodict, template_name='hindex.html')), ) ```
If you want to supply different template names to different views, the common practice is indeed to pass in a unique dictionary to each URL pattern. For example: ``` urlpatterns = patterns('', url(r'^home/$', 'my.views.home', {'template_name': 'home.html'}, name='home'), url(r'^about/$', 'my.views.about', {'template_name': 'about.html'}, name='about'), ) ``` This kind of pattern is common and acceptable.
Specifying different template names in Django generic views
[ "", "python", "django", "django-urls", "" ]
this is my code to turn a byte[] array into an image ``` unsafe { //convert the UInt32[] into byte array and then assign the pointer to it fixed (byte* ptr = Misc.ConvertFromUInt32Array(image)) { Bitmap bmp = new Bitmap(200,64,800, PixelFormat.Format32bppRgb, new IntPtr(ptr)); bmp.Save("test.bmp"); } } ``` And I get this: [alt text http:////img11.imageshack.us/img11/4853/testacr.png](http:////img11.imageshack.us/img11/4853/testacr.png) Where's the problem in the code,why that happens? How to flip it back to normal?
``` bmp.RotateFlip(RotateFlipType.Rotate180FlipX); ``` Fixed the problem :)
Hey it looks like the two images you posted are not related in any way (besides have a similar pattern of obfuscation). Did you post the wrong files? With regard to the issue you are seeing, I would guess you are seeing a problem with the origin of the x-y axis. Normal images and graphics APIs use a slightly weird axis where you count "down" the y axis, that is to say, the point(0, 0) is at the top left of the screen and as you increment y, you go down the screen. Therefore it seems reasonable to assume that you have made a mistake in the conversion or that the two images are using a different y axis scheme.
I get the image reversed in C#
[ "", "c#", "bitmap", "flip", "" ]
I'm running into an issue where I'm processing unicode strings and I want to do some error reporting with standard exceptions. The error messages contained in standard exceptions are not unicode. Usually that hasn't been a problem for me because I can define the error message in non-unicode and have enough information, but in this case I want to include data from the original strings, and these *can* be unicode. How do you handle unicode messages in your exceptions? Do you create your own custom exception class, do you derive from the standard exceptions extending them to unicode, or do you have even other solutions to this problem (such as a rule "don't use unicode in exceptions")?
I think Peter Dimov's rationale as pointed out in the [Boost error handling guidelines](http://www.boost.org/community/error_handling.html) covers this well: > Don't worry too much about the what() > message. It's nice to have a message > that a programmer stands a chance of > figuring out, but you're very unlikely > to be able to compose a relevant and > user-comprehensible error message at > the point an exception is thrown. > Certainly, internationalization is > beyond the scope of the exception > class author. Peter Dimov makes an > excellent argument that the proper use > of a what() string is to serve as a > key into a table of error message > formatters. Now if only we could get > standardized what() strings for > exceptions thrown by the standard > library...
(I'm adding an answer to my own question after an insight because of Flodin's answer) In my particular case I have a string which may contain unicode characters, which I am parsing and thus expecting to be in a certain format. The parsing may fail and throw an exception to indicate that a problem occurred. Originally I intended to create a programmer-readable message inside the exception that details the contents of the string where parsing failed, and that's where I ran into trouble because the exception message of a standard exception cannot contain unicode characters. However, the new design I am considering is to return the location of the parsing error in the string through the exception mechanism within a std::exception-derived class. The process of creating a programmer-readable message that contains the parts of the string causing the error can be delegated to a handler outside the class. This feels like a much cleaner design to me. Thank you for the input, everyone!
C++ (Standard) Exceptions and Unicode
[ "", "c++", "exception", "unicode", "" ]
I want to mock the User property of an HttpContext. I'm using Scott Hanselmans MVCHelper class and RhinoMocks. I have a unit test that contains code, like this: ... ``` MockIdentity fakeId = new MockIdentity("TEST_USER", "Windows", true); MockPrincipal fakeUser = new MockPrincipal(null, fakeId); using (mocks.Record()) { Expect.Call(fakeHttpContext.User).Return(fakeUser); } ``` ... My MockIdentity and MockPrincipal classes are mocks conforming to IIdentity and IPrincipal, respectively. I get an error when running the unit test that reports: > System.NotImplementedException : The > method or operation is not > implemented. at System.Web.HttpContextBase.get\_User() This is happening when I'm trying to set the expectation for the User property. I understand that the httpContextBase has a getter and setter that aren't implemented but I thought that Rhino would handle this when mocking. Does this mean that I have to derive from the HttpContextbase and override the property for my mock object. It seems odd. Other users have had this issue and it's reported here: <http://www.mail-archive.com/rhinomocks@googlegroups.com/msg00546.html>
To mock the user property, you can do this: ``` var httpContext = MockRepository.GenerateStub<HttpContextBase>(); httpContext.Stub(x=>x.User).Return(yourFakePrincipalHere); var controllerContext = new ControllerContext(httpContext, ....); var controller = new HomeController(); controller.ControllerContext = controllerContext; ``` (this uses the new RM 3.5 api, if you're doing it w/ record/replay then: ``` using(mocks.Record) { _httpContext = _mocks.DynamicMock<HttpContextBase>(); SetupResult.For(_httpContext.User).Return(...); } using(mocks.PlayBack()) { .... } ```
I had nearly the same problem and moved to Moq. This is the custom helper I uses in my apps: ``` public static class MvcMockHelpers { public static HttpContextBase FakeHttpContext() { var context = new Mock<HttpContextBase>(); var request = new Mock<HttpRequestBase>(); var response = new Mock<HttpResponseBase>(); var session = new Mock<HttpSessionStateBase>(); var server = new Mock<HttpServerUtilityBase>(); context.Expect(ctx => ctx.Request).Returns(request.Object); context.Expect(ctx => ctx.Response).Returns(response.Object); context.Expect(ctx => ctx.Session).Returns(session.Object); context.Expect(ctx => ctx.Server).Returns(server.Object); var form = new NameValueCollection(); var querystring = new NameValueCollection(); var cookies = new HttpCookieCollection(); var user = new GenericPrincipal(new GenericIdentity("testuser"), new string[] { "Administrator" }); request.Expect(r => r.Cookies).Returns(cookies); request.Expect(r => r.Form).Returns(form); request.Expect(q => q.QueryString).Returns(querystring); response.Expect(r => r.Cookies).Returns(cookies); context.Expect(u => u.User).Returns(user); return context.Object; } public static HttpContextBase FakeHttpContext(string url) { HttpContextBase context = FakeHttpContext(); context.Request.SetupRequestUrl(url); return context; } public static void SetFakeControllerContext(this Controller controller) { var httpContext = FakeHttpContext(); ControllerContext context = new ControllerContext(new RequestContext(httpContext, new RouteData()), controller); controller.ControllerContext = context; } public static void SetFakeControllerContext(this Controller controller, RouteData routeData) { SetFakeControllerContext(controller, new Dictionary<string, string>(), new HttpCookieCollection(), routeData); } public static void SetFakeControllerContext(this Controller controller, HttpCookieCollection requestCookies) { SetFakeControllerContext(controller,new Dictionary<string,string>(),requestCookies, new RouteData()); } public static void SetFakeControllerContext(this Controller controller, Dictionary<string, string> formValues) { SetFakeControllerContext(controller, formValues, new HttpCookieCollection(), new RouteData()); } public static void SetFakeControllerContext(this Controller controller, Dictionary<string, string> formValues, HttpCookieCollection requestCookies, RouteData routeData) { var httpContext = FakeHttpContext(); foreach (string key in formValues.Keys) { httpContext.Request.Form.Add(key, formValues[key]); } foreach (string key in requestCookies.Keys) { httpContext.Request.Cookies.Add(requestCookies[key]); } ControllerContext context = new ControllerContext(new RequestContext(httpContext, routeData), controller); controller.ControllerContext = context; } public static void SetFakeControllerContextWithLogin(this Controller controller, string userName, string password, string returnUrl) { var httpContext = FakeHttpContext(); httpContext.Request.Form.Add("username", userName); httpContext.Request.Form.Add("password", password); httpContext.Request.QueryString.Add("ReturnUrl", returnUrl); ControllerContext context = new ControllerContext(new RequestContext(httpContext, new RouteData()), controller); controller.ControllerContext = context; } static string GetUrlFileName(string url) { if (url.Contains("?")) return url.Substring(0, url.IndexOf("?")); else return url; } static NameValueCollection GetQueryStringParameters(string url) { if (url.Contains("?")) { NameValueCollection parameters = new NameValueCollection(); string[] parts = url.Split("?".ToCharArray()); string[] keys = parts[1].Split("&".ToCharArray()); foreach (string key in keys) { string[] part = key.Split("=".ToCharArray()); parameters.Add(part[0], part[1]); } return parameters; } else { return null; } } public static void SetHttpMethodResult(this HttpRequestBase request, string httpMethod) { Mock.Get(request) .Expect(req => req.HttpMethod) .Returns(httpMethod); } public static void SetupRequestUrl(this HttpRequestBase request, string url) { if (url == null) throw new ArgumentNullException("url"); if (!url.StartsWith("~/")) throw new ArgumentException("Sorry, we expect a virtual url starting with \"~/\"."); var mock = Mock.Get(request); mock.Expect(req => req.QueryString) .Returns(GetQueryStringParameters(url)); mock.Expect(req => req.AppRelativeCurrentExecutionFilePath) .Returns(GetUrlFileName(url)); mock.Expect(req => req.PathInfo) .Returns(string.Empty); } ```
Mocking and HttpContextBase.get_User()
[ "", "c#", "asp.net-mvc", "rhino-mocks", "" ]
I have extension method: ``` public static IQueryable<TResult> WithFieldLike<TResult>( this IQueryable<TResult> query, Func<TResult, string> field, string value) { Expression<Func<TResult, bool>> expr = trans => field(trans).Contains(value); return query.Where(expr); } ``` I need change parameter field to type: Expression>. Will be something like. ``` public static IQueryable<TResult> WithFieldLike<TResult>( this IQueryable<TResult> query, Expression<Func<TResult, string>> field, string value) { Expression<Func<TResult, bool>> expr = ??? return query.Where(expr); } ``` The call of this method is: ``` var query7 = query.WithFieldLike(trans => trans.DeviceModelNumber, "ber_3"); ``` How should I build the "expr" in this case? Please help.
Deconstruct `field` and create a new expression, something like this: ``` var expr = Expression.Lambda<Func<TResult, bool>> ( Expression.Call (field.Body, typeof (string).GetMethod ("Contains"), Expression.Constant (value)), field.Parameters) ; ``` *(edited as per Maxs's refinement in comments)*
You'll need to use `Expression.Invoke`; something like (untested): ``` public static IQueryable<TResult> WithFieldLike<TResult>( this IQueryable<TResult> query, Expression<Func<TResult, string>> field, string value) { var param = Expression.Parameter(typeof(TResult), "x"); var expr = Expression.Lambda<Func<TResult, bool>>( Expression.Call(Expression.Invoke(field, param), "Contains", null, Expression.Constant(value)), param); return query.Where(expr); } ``` (edit: fixed)
Change parameter from lambda function to lambda expression
[ "", "c#", "lambda", "" ]
I'm considering using Spring to assemble the components of my application, but I've got a problem. Our application uses a configuration repository that is global to the VM, and is similar (but not precisely) to the system properties. This configuration API is accessed like so: ``` Configuration.getDb ().get ("some_property_name") ``` Is there any way to use values from this global configuration in Spring xml bean files? `getDb` may return a different value depending on the current state of the configuration library (it has context), but I'm willing to make the statement that the Spring configuration will be fully-loaded at application context initialization time. Still, something more flexible would be fantastic. Given that I'm a Spring newbie, code examples would make my life a great deal easier.
To expand on cletus' suggesrion, I'd say you want a custom subclass of PropertyPlaceholderConfigurer, and override the resolvePlaceholder() method, which would call your Configuration.getDb() code. If you can't resolve the value, then delegate back to the superclass. For example: ``` public class MyPlaceholderConfigurer extends PropertyPlaceholderConfigurer { @Override protected String resolvePlaceholder(String placeholder, Properties props) { String value = Configuration.getDb().get(placeholder) if (value == null) { value = super.resolvePlaceholder(placeholder, props); } return value; } } ``` Then just define a bean of type MyPlaceholderConfigurer in your application context, and spring will automagically consult your class to resolve the placeholder values. If your Configuration.getDb() component can't resolve the value, then delegating back to the superclass allows spring to look up the value as a system property instead. Alternatively, you can inject a properties file into the bean, and it can check that also. Read the ref docs on the basic usage of PropertyPlaceholderConfigurer, to get a feel for how it works. It's quite flexible.
You can do this, although it's not the advised method of handling configuration data. Refer to [3.7 Container extension points](http://static.springframework.org/spring/docs/2.5.x/reference/beans.html#beans-factory-extension) of the Spring reference documentation. Basically you will want to create a custom BeanFactoryPostProcessor implementation that will replace an expression like: ``` ${some_property_name} ``` with the appropriate value based on the callback. Look at the implementation of the PropertyPlaceholderConfigurer as a starting point.
Acquiring a spring configuration value from a custom class
[ "", "java", "spring", "configuration", "" ]
I have a `std::vector` with `n` elements. Now I need to pass a pointer to a vector that has the last `n-1` elements to a function. For example, my `vector<int> foo` contains `(5,2,6,87,251)`. A function takes `vector<int>*` and I want to pass it a pointer to `(2,6,87,251)`. Can I just (safely) take the iterator `++foo.begin()`, convert it to a pointer and pass that to the function? Or use `&foo[1]`? **UPDATE:** People suggest that I change my function to take an iterator rather than a pointer. That seems not possible in my situation, since the function I mentioned is the `find` function of `unordered_set<std::vector*>`. So in that case, is copying the `n-1` elements from `foo` into a new vector and calling `find` with a pointer to that the only option? Very inefficient! It's like Shlemiel the painter, especially since i have to query many subsets: the last `n-1`, then `n-2`, etc. elements and see if they are in the `unordered_set`.
> That seems not possible in my situation, since the function I mentioned is the find function of `unordered_set<std::vector*>`. Are you using custom hash/predicate function objects? If not, then you must pass `unordered_set<std::vector<int>*>::find()` the pointer to the exact vector that you want to find. A pointer to another vector with the same contents will not work. This is not very useful for lookups, to say the least. Using `unordered_set<std::vector<int> >` would be better, because then you could perform lookups by value. I think that would also require a custom hash function object because `hash` does not to my knowledge have a specialization for `vector<int>`. Either way, a pointer into the middle of a vector is not itself a vector, as others have explained. You cannot convert an iterator into a pointer to vector without copying its contents.
here it is, obtaining a reference to the coresponding pointer of an iterator use : example: ``` string my_str= "hello world"; string::iterator it(my_str.begin()); char* pointer_inside_buffer=&(*it); //<-- ``` [notice operator \* returns a **reference** so doing & on a reference will give you the address].
Convert iterator to pointer?
[ "", "c++", "stl", "pointers", "vector", "iterator", "" ]
In the form.cs file I have two buttons,a memo and a timer.My question is: How do I access the timer or the memo from another cs file? I've tried to make the objects public,but it didn't work,please give me a source or a project,so I can see where I'm mistaken. Thanks!
Select your button in designer, go to it's properties and change "Modifiers" property from Private to Public. Then you can get access to it from another class, something like this: ``` public static class Test { public static void DisalbeMyButton() { var form = Form.ActiveForm as Form1; if (form != null) { form.MyButton.Enabled = false; } } } ``` Note: it's just an example and definitely not a pattern for good design :-)
I worry whenever I hear someone talking about "another .cs file" or "another .vb file". It often (though not always) indicates a lack of understanding of programming, at least of OO programming. What's *in* the files? One class? Two? You're not trying to access these things from another *file*, you're trying to access them from a method of a class, or possibly of a module in VB. The answer to your question will depend on the nature of the class and method from which you're trying to access these things, and the reason why you want to access them. Once you edit your question to include this information, the answers you receive will probably show you that you shouldn't be accessing these private pieces of the form in classes other than the form class itself.
How to access form objects from another cs file in C#
[ "", "c#", "forms", "object", "" ]
I am trying to make a simple game that goes across a TCP network. The server does something like this to check for connections, in Server.java: ``` try { server = new ServerSocket(port); System.out.println("Server started on port " + port); while (true) { socket = server.accept(); System.out.println("A new player has joined the server."); new Server(socket).start(); } } ``` And to make a new client, in Player.java: ``` socket = new Socket(hostname, port); ``` Now, this works fine and all, but I need the server to add the instance of the Player to an array list and be able to send all of them certain data. They both have main methods, so one computer can just run the server and have 4 other computers connect to it by running Player.java. If all Player does is create a new socket, how is the Server supposed to interact with each Player?
I'm not sure I understand the question. The call to accept will produce a different return value for each connecting client (typically representing the client address and port), so you need to store each of them. You can then interact via the sockets, Sun has a [pretty good example in its tutorial](http://java.sun.com/docs/books/tutorial/networking/sockets/clientServer.html): That being said, save yourself a lot of headache and think over the performance you expect from the game. You can save yourself a lot of trouble and easily add reliability and scalability if you [use JMS and ActiveMQ](http://java.sun.com/products/jms/tutorial/) for your communications rather than mess around with sockets yourself. Spend your time writing the game, not doing low-level socket programming, unless you're trying to learn.
`server.accept()` method returns you an object of `Socket`. `Socket` class have a method `getOutputStream()`, you can use this stream to send a message.
JAVA - Difficulties with a simple server seeing the clients
[ "", "java", "networking", "sockets", "tcp", "" ]
I've got the following installed through MacPorts on MacOS X 10.5.6: ``` py25-sqlite3 @2.5.4_0 (active) python25 @2.5.4_1+darwin_9+macosx (active) sqlite3 @3.6.12_0 (active) ``` `python25` is correctly set as my system's default Python. I downloaded a fresh copy of Django 1.1 beta (I have the same problem with 1.0 and trunk, though) and installed it with "`sudo python setup.py install`". Things seem to load correctly through the interactive interpreter: ``` $ python Python 2.5.4 (r254:67916, Apr 10 2009, 16:02:52) [GCC 4.0.1 (Apple Inc. build 5490)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> import django >>> import sqlite3 >>> ^D ``` But: ``` $ django-admin.py startproject foo $ cd foo/ $ python manage.py runserver Validating models... Unhandled exception in thread started by <function inner_run at 0x6c1e70> Traceback (most recent call last): File "/opt/local/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/site-packages/django/core/management/commands/runserver.py", line 48, in inner_run self.validate(display_num_errors=True) File "/opt/local/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/site-packages/django/core/management/base.py", line 246, in validate num_errors = get_validation_errors(s, app) File "/opt/local/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/site-packages/django/core/management/validation.py", line 22, in get_validation_errors from django.db import models, connection File "/opt/local/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/site-packages/django/db/__init__.py", line 22, in <module> backend = __import__('%s.base' % settings.DATABASE_ENGINE, {}, {}, ['']) ImportError: No module named dummy.base ``` If I change `DATABASE_ENGINE` in `settings.py` to "`sqlite3`", I get the following, seemingly related problem: ``` $ python manage.py runserver Validating models... Unhandled exception in thread started by <function inner_run at 0x6c1e70> Traceback (most recent call last): File "/opt/local/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/site-packages/django/core/management/commands/runserver.py", line 48, in inner_run self.validate(display_num_errors=True) File "/opt/local/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/site-packages/django/core/management/base.py", line 246, in validate num_errors = get_validation_errors(s, app) File "/opt/local/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/site-packages/django/core/management/validation.py", line 22, in get_validation_errors from django.db import models, connection File "/opt/local/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/site-packages/django/db/__init__.py", line 22, in <module> backend = __import__('%s.base' % settings.DATABASE_ENGINE, {}, {}, ['']) ImportError: No module named base ^C$ ``` I swear this all worked a few days ago and I don't recall changing anything related to Django or Python, installation-wise. My various Google adventures have turned up nothing useful. So... Any ideas? Edit: '`syncdb`' raises the same exceptions.
I found this [thread](http://groups.google.com/group/django-users/browse_thread/thread/ea60854ad2e00b98) on the Django Users group: They suggest that it has something to do with the way MacPorts installs Python. I wish I had more details to help you with, but as a workaround, I recommend you use MacPorts to uninstall this copy of Python and try to use alternate method of install it. If you're looking for an quick and easy install, you might want to try [MacPython](http://wiki.python.org/moin/MacPython/Leopard). Hope this helps!
did you try the intro doc? [doc link](http://docs.djangoproject.com/en/dev/intro/tutorial01) If you follow this doc, you can at least say, "at step XXXX it got error YYY". Then someone with some experience (no me) should be able to find a good answer. This link is for the trunk, there's a link for 1.0 docs at the top.
"ImportError: No module named dummy" on fresh Django project
[ "", "python", "database", "django", "sqlite", "" ]
A lot of times in Perl, I'll do something like this: ``` $myhash{foo}{bar}{baz} = 1 ``` How would I translate this to Python? So far I have: ``` if not 'foo' in myhash: myhash['foo'] = {} if not 'bar' in myhash['foo']: myhash['foo']['bar'] = {} myhash['foo']['bar']['baz'] = 1 ``` Is there a better way?
``` class AutoVivification(dict): """Implementation of perl's autovivification feature.""" def __getitem__(self, item): try: return dict.__getitem__(self, item) except KeyError: value = self[item] = type(self)() return value ``` Testing: ``` a = AutoVivification() a[1][2][3] = 4 a[1][3][3] = 5 a[1][2]['test'] = 6 print a ``` Output: ``` {1: {2: {'test': 6, 3: 4}, 3: {3: 5}}} ```
If the amount of nesting you need is fixed, `collections.defaultdict` is wonderful. e.g. nesting two deep: ``` myhash = collections.defaultdict(dict) myhash[1][2] = 3 myhash[1][3] = 13 myhash[2][4] = 9 ``` If you want to go another level of nesting, you'll need to do something like: ``` myhash = collections.defaultdict(lambda : collections.defaultdict(dict)) myhash[1][2][3] = 4 myhash[1][3][3] = 5 myhash[1][2]['test'] = 6 ``` edit: MizardX points out that we can get full genericity with a simple function: ``` import collections def makehash(): return collections.defaultdict(makehash) ``` Now we can do: ``` myhash = makehash() myhash[1][2] = 4 myhash[1][3] = 8 myhash[2][5][8] = 17 # etc ```
What's the best way to initialize a dict of dicts in Python?
[ "", "python", "autovivification", "" ]
I just made a browser using c# as one of my first projects of programming and it works pretty good but its pretty generic. I tried adding different tools on it but it still ends up pretty bare and I'm better off using Firefox. Is there a way to add useful apps and color on your browser. I want to make it more personal and add things that make it unique not necessarily better than all the others. I did it more for practice than anything but I want to add a little flare to it. If I'm not doing it for a job I might as well go for style points.
Implement HTML5 and CSS3. All of it. That would be worth using. Now in the short run what I'd really like, would be a browser, that combines V8 JavaScript engine, WebKit as rendering engine with flexibility of XPCOM (but without its bloat). I mean basically cross-platform Google Chrome, accepting Firefox extensions.
I suspect you'll find most of the really useful ideas have already been implemented in the major browsers. If you think of something really neat which *hasn't* been done already, I think it would be a more useful contribution to the world if you'd implement it for/in the major browsers instead of in your own one. I'm not trying to put a damper on your aim - it's just that quite a few people have already thought about browsers long and hard. It's great to do something as a route to learning, but it would be unrealistic to think you'll come up with a world-beating new idea at the same time.
How can I make my browser unique?
[ "", "c#", "winforms", "browser", "" ]
Here is my code: ``` <?php $variable1 = 00001; $variable2 = (sprintf('%04d', $variable1 + 1)); echo $variable2; ?> ``` How come the outcome of this code is "0002" and not "00002"? in other words it is missing a 0.
The 4 in %04d sets the total width of the printed value
the number in the first parameter is the "total number of characters" not the number of zeroes to use in padding. What you are looking for is %05d instead.
sprintf outcome problem
[ "", "php", "formatting", "printf", "" ]
I've written a C# application which uses `System.Diagnostics.Process` class to create a process, using ``` Process P1 = new Process(); P1.FileName = "myexe.exe"; ``` and other proper settings. I've linked it to an exe file which runs for about 10 minutes. (I'm writing program to measure run-time of programs). Now in between I want to abort the running process. So I wrote in the cancel button's event, ``` Process.Close(); ``` But in the task manager I still see myexe.exe running, it doesn't get aborted. What to do?
[Process.Close()](http://msdn.microsoft.com/en-us/library/system.diagnostics.process.close.aspx) isn't meant to abort the process - it's just meant to release your "local" view on the process, and associated resources. I think you mean [Process.Kill()](http://msdn.microsoft.com/en-us/library/system.diagnostics.process.kill.aspx) or [Process.CloseMainWindow()](http://msdn.microsoft.com/en-us/library/system.diagnostics.process.closemainwindow.aspx). Personally I'd try to find a more graceful way of shutting it down though.
Use [Process.Kill](http://msdn.microsoft.com/en-us/library/system.diagnostics.process.kill.aspx) instead.
Process.Close() is not terminating created process,c#
[ "", "c#", "process", "" ]
When im naming a variable for a directory should i end the variable name with path, folder or directory. Im writing my code in .net..
Ok, first some definitions: * A **Path** is an address within the file system, it can point to either a file or a directory. * A **Directory** can contain multiple files and subdirectories. * A **File** can be accessed via it's full path (e.g. `C:\Temp\Foo.txt`), or a relative path (`..\Temp\Foo.txt`). (I would consider the file name (`Foo.txt`) to be a relative path as well). Therefore, if a variable is ambiguous, (i.e. could point to either a file or a directory, like when recursively walking through the directory tree,) I would call it `FooPath`. If your variable always points to one file, I would call it `FooFile` If your variable is always the name of a directory, and never of a file, I would let this reflect by calling it `FooDirectory`, or `FooDir` for short. But of course the most important rule is consistency: Choose one naming convention and stick with it. Do not call one variable `FooDirectory`, the next `BarDir` and the third `BuzzFolder`.
I use "path" to refer to the full path of a file (directory + file name). I'd recommend "folder", "directory" or even "dir".
Variable\Property naming convention
[ "", "c#", ".net", "vb.net", "naming-conventions", "" ]
Using Java, assuming v1.6. I have a collection where the unique index is a string and the non-unique value is an int. I need to perform thousands of lookups against this collection as fast as possible. I currently am using a `HashMap<String, Integer>` but I am worried that the boxing/unboxing of the Integer to int is making this slower. I had thought of using an `ArrayList<String>` coupled with an `int[]`. i.e. Instead of: ``` int value = (int) HashMap<String, Integer>.get("key"); ``` I could do ``` int value = int[ArrayList<String>.indexOf("key")]; ``` Any thoughts? Is there a faster way to do this? p.s. I will only build the collection once and maybe modify it once but each time I will know the size so I can use `String[]` instead of `ArrayList` but not sure there's a faster way to replicate indexOf...
Unboxing is fast - no allocations are required. Boxing is a potentially slower, as it needs to allocate a new object (unless it uses a pooled one). Are you sure you've really got a problem though? Don't complicate your code until you've actually proved that this is a significant hit. I very much doubt that it is. There are collection libraries available for primitive types, but I would stick to the normal HashMap from the JRE until you've profiled and checked that this is causing a problem. If it really only is *thousands* of lookups, I very much doubt it'll be a problem at all. Likewise if you're lookup-based rather than addition-based (i.e. you fetch more often than you add) then the boxing cost won't be particularly significant, just unboxing, which is cheap. I would suggest using `intValue()` rather than the cast to convert the value to an `int` though - it makes it clearer (IMO) what's going on. EDIT: To answer the question in the comment, `HashMap.get(key)` will be faster than `ArrayList.indexOf(key)` *when the collection is large enough*. If you've actually only got five items, the list may well be faster. I assume that's not really the case though. If you really, really don't want the boxing/unboxing, try [Trove](http://trove4j.sourceforge.net/) (TObjectHashMap). There's also [COLT](http://acs.lbl.gov/~hoschek/colt/) to consider, but I couldn't find the right type in there.
Any performance gain that you get from not having to box/unbox is significanlty erased by the for loop that you need to go with the indexOf method. Use the HashMap. Also you don't need the (int) cast, the compiler will take care of it for you. The array thing would be ok with a small number of items in the array, but then so is the HashMap... The only way you could make it fast to look up in an array (and this is *not* a real suggestion as it has too many issues) is if you use the hashCode of the String to work with as the index into the array - don't even think about doing that though! (I only mention it because you might find something via google that talks about it... if they don't explain why it is bad don't read any more about it!)
String indexed collection in Java
[ "", "java", "collections", "" ]
I would like to determine the IP address of a printer, using C# (.NET 2.0). I have only the printer share name as set up on the Windows OS, in the format `\\PC Name\Printer Name`. The printer is a network printer, and has a different IP address to the PC. Does anyone have any pointers? Thanks in advance for your help. Regards, Andy.
Check this question: [How to get Printer Info in C#.NET?](https://stackoverflow.com/questions/296182/how-to-get-printer-info-in-c-net/). I think that you have to get the property `PortName` from the WMI properties.
Just adding an another solution here using .Net Framework 4.0 or higher ``` Using System.Printing var server = new PrintServer(); var queues = server.GetPrintQueues(new[] { EnumeratedPrintQueueTypes.Local, EnumeratedPrintQueueTypes.Connections }); foreach (var queue in queues) { string printerName = queue.Name; string printerPort = queue.QueuePort.Name; } ```
Determine the IP Address of a Printer in C#
[ "", "c#", ".net", "network-programming", "printing", "" ]
I have a couple of questions actually. I have a class **Dog** with the following instance fields: ``` private int id; private int id_mother; private int id_father; private String name=""; private String owner=""; private String bDate=""; ``` I also have a class **Archive** which can instantiate **Dog** and put Dog objects into an ArrayList. I am trying to write a method in **Archive** which takes an integer as ID and looks through the ArrayList, and returns the object containing that ID. ``` private Dog getDog(int id){ Dog dog = new Dog(); int length=getSize(); int i=0; dog=al.get(i); i++; while(dog.getId()!=id && i<length) dog=al.get(i); i++; if(dog.getId()!=id) dog=null; return dog; }//end getDog ``` There are two problems with this method (the other methods I use work). First of all it's not working, and I can't see why. I'm while-looping through (potentially) all the objects in the arraylist, for then after the loop is finished, checking whether the loop finished because it ran out of objects to search through, or because it found an object with the given ID. Secondly, that seems like an immensely time-consuming process. Is there some way to speed this up?
A `while` applies to the expression or block after the `while`. You dont have a block, so your while ends with the expression `dog=al.get(i);` ``` while(dog.getId()!=id && i<length) dog=al.get(i); ``` Everything after that happens only once. There's no reason to new up a Dog, as you're never using the dog you new'd up; you immediately assign a Dog from the array to your dog reference. And if you need to get a value for a key, you should use a Map, not an Array. Edit: this was donwmodded why?? Comment from OP: > One further question with regards to not having to make a new instance of a Dog. If I am just taking out copies of the objects from the array list, how can I then take it out from the array list without having an object in which I put it? I just noticed as well that I didn't bracket the while-loop. A Java reference and the object it refers to are different things. They're very much like a C++ reference and object, though a Java reference can be re-pointed like a C++ pointer. The upshot is that `Dog dog;` or `Dog dog = null` gives you a reference that points to no object. `new Dog()` *creates* an object that can be pointed to. Following that with a `dog = al.get(i)` means that the reference now points to the dog reference returned by `al.get(i)`. Understand, in Java, objects are never returned, only references to objects (which are addresses of the object in memory). The pointer/reference/address of the Dog you newed up is now lost, as no code refers to it, as the referent was replaced with the referent you got from `al.get()`. Eventually the Java garbage collector will destroy that object; in C++ you'd have "leaked" the memory. The upshot is that you do need to create a variable that can refer to a Dog; you don't need to create a Dog with `new`. (In truth you don't need to create a reference, as what you really ought to be doing is returning what a Map returns from its get() function. If the Map isn't parametrized on Dog, like this: `Map<Dog>`, then you'll need to cast the return from get, but you won't need a reference: `return (Dog) map.get(id);` or if the Map is parameterized, `return map.get(id)`. And that one line is your whole function, and it'll be faster than iterating an array for most cases.)
Assuming that you've written an equals method for Dog correctly that compares based on the id of the Dog the easiest and simplest way to return an item in the list is as follows. ``` if (dogList.contains(dog)) { return dogList.get(dogList.indexOf(dog)); } ``` That's less performance intensive that other approaches here. You don't need a loop at all in this case. Hope this helps. P.S You can use Apache Commons Lang to write a simple equals method for Dog as follows: ``` @Override public boolean equals(Object obj) { EqualsBuilder builder = new EqualsBuilder().append(this.getId(), obj.getId()); return builder.isEquals(); } ```
Java method: Finding object in array list given a known attribute value
[ "", "java", "arraylist", "" ]
What is the closest Java alternative to [Twisted](http://twistedmatrix.com/trac/wiki/TwistedProject)?
Like Stephane, I would suggest you take a look at [Mina](http://mina.apache.org/). Its a framework for asynchronous network IO. It is built on top of NIO, which was mentioned earlier, and IMO hides away some of the complexity involved with Selectors,Channels,etc.. I've used Mina for a couple of projects and its pretty good, but be warned, I've found the documentation to be a little weak. And again, like Stephane mentioned, it doesn't have out of the box support for too many protocols.
Nio is really low level and supports Socket only and SSL if you dig hard enough on Google for samples. Apache Mina wraps the complexity and adds a few protocols but not as much as Twister.
Twisted in Java
[ "", "java", "network-programming", "twisted", "" ]
I have to activate android's system key lock (the one you get when you press the *power off*/*hang up* button). See here: ![img](https://farm4.static.flickr.com/3202/2849046033_fd42359cef.jpg) I already browsed the docs but everything I found was [PowerManager](http://developer.android.com/reference/android/os/PowerManager.html) and [KeyguardManager](http://developer.android.com/reference/android/app/KeyguardManager.html). Both seem not to be the solution :-(. So, does everyone know how to achieve that from a android application? (If special permissions are required, that is no problem but changing the device's settings is not a solution...) **EDIT**: Or does someone know that this is definitely not possible at all? Btw. craigs solution with sending keys does not work anymore (see comments).
I have been searching for an answer to the exact same question for a while. Apparently, after 2.0 onwards the device manager privileges for the app level were removed. But with Froyo - 2.2 the device policy manager is revealed granting us developers a multitude of administrative level controls. <http://developer.android.com/guide/topics/admin/device-admin.html>
Looks like the screen lock function is performed using the method: ``` public void goToSleep(long time) ``` method in `PowerManager.java`. It's possible to get a reference to it in this fashion: ``` PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE); ``` However this requires the permission ``` android.permission.DEVICE_POWER ``` which is a level 2 permission available to the system only. So looks like this isn't doable. This is for version 1.1 only, I don't know for 1.5.
Android - Activation of the system key lock (aka lock screen)
[ "", "java", "android", "keyboard", "locking", "device-admin", "" ]
I want to know when building a typical site on the LAMP stack how do you optimize it for the best possible load times. I am picturing a typical DB-driven site. This is a high-level look and could probably pull in question and let me break it down into each layer of the stack. L - At the system level, (setup and filesystem) can you do to improve speed? One thing I can think of is image sizes, can compression here help optimize anything? A - There have to be a ton of settings related to site speed here in the web server. Not my Forte. Probably depends a lot on how many sites are running concurrently. M - MySQL in a database driven site, DB performance is key. Is there a better normalization approach i.e, using link tables? Web developers often just make simple monolithic tables resembling 1NF and this can kill performance. P - aside from performance-boosting settings like caching, what can the programmer do to affect performance at a high level? I would really like to know if MVC design approaches hit performance more than quick-and-dirty. Other simple tips like are sessions faster than cookies would be interesting to know. Obviously you have to get down and dirty into the details and find what code is slowing you down. Also I realize that many sites have many different performance characteristics, but let's assume a typical site that has more reads then writes. I am just wondering if we can compile a bunch of best practices and fully expect people to link other questions so we can effectively workup a checklist. My goal is to see if even in addition to the usual issues in performance we can see some oddball things you might not think of crop up to go along with a best-practices summary. So my question is, if you were starting from scratch, how would you make *sure* your LAMP site was fast?
Here's a few personal must-dos that I always set up in my LAMP applications. * Install mod\_deflate for apache, and do not use PHP's gzip handlers. mod\_deflate will allow you to compress static content, like javascript/css/static html, as well as the usual dynamic PHP output, and it's one less thing you have to worry about in your code. * Be careful with .htaccess files! Enabling .htaccess files for directories in your app means that Apache has to scan the filesystem constantly, looking for .htaccess directives. It is far better to put directives inside the main configuration or a vhost configuration, where they are loaded once. Any time you can get rid of a directory-level access file by moving it into a main configuration file, you save disk access time. * Prepare your application's database layer to utilize a connection manager of some sort (I use a Singleton for most applications). It's not very hard to do, and reducing the number of database connections your application opens saves resources. * If you think your application will see significant load, memcached can perform miracles. Keep this in mind while you write your code... perhaps one day instead of creating objects on the fly, you will be getting them from memcached. A little foresight will make implementation painless. * Once your app is up and running, set MySQL's slow query time to a small number and monitor the slow query log diligently. This will show you where your problem queries are coming from, and allow you to optimize your queries and indexes before they become a problem. * For serious performance tweakers, you will want to compile PHP from source. Installing from a package installs a lot of libraries that you may never use. Since PHP environments are loaded into every instance of an Apache thread, even a 5MB memory overhead from extra libraries quickly becomes 250MB of lost memory when there's 50 Apache threads in existence. I keep a list of my standard ./configure line I use when building PHP [here](http://www.phpvs.net/articles/blakes-centos-lamp-server-guide/php/#Install-PHP), and I find it suits most of my applications. The downside is that if you end up needing a library, you have to recompile PHP to get it. Analyze your code and test it in a devel environment to make sure you have everything you need. * Minify your Javascript. * Be prepared to move static content, such as images and video, to a non-dynamic web server. Write your code so that any URLs for images and video are easily configured to point to another server in the future. A web server optimized for static content can easily serve tens or even hundreds of times faster than a dynamic content server. That's what I can think of off the top of my head. Googling around for PHP best practices will find a lot of tips on how to write faster/better code as well (Such as: `echo` is faster than `print`).
First, realize that performance is an iterative process. You don't build a web application in a single pass, launch it, and never work on it again. On the contrary, you start small, and address performance issues as your site grows. Now, onto specifics: 1. Profile. Identify your bottlenecks. This is the most important step. You need to focus your effort where you'll get the best results. You should have some sort of monitoring solution in place (like cacti or munin), giving you visibility into what's going on on your server(s) 2. Cache, cache, cache. You'll probably find that database access is your biggest bottleneck on the back end -- but you should verify this on your own. Fortunately, you'll probably find that a lot of your traffic is for a small set of resources. You can cache those resources in something like memcached, saving yourself the database hit, and resulting in better backend performance. 3. As others have mentioned above, take a look at the YDN performance rules. Consider picking up the [accompanying book](http://oreilly.com/catalog/9780596529307/). This'll help you with front end performance 4. Install [PHP APC](http://php.net/apc), and make sure it's configured with enough memory to hold all your compiled PHP bytecode. We recently discovered that our APC installation didn't have nearly enough ram; giving it enough to work in cut our CPU time in half, and disk activity by 10% 5. Make sure your database tables are properly indexed. This goes hand in hand with monitoring the slow query log. The above will get you very far. That is to say, even a fairly db-heavy site should be able to survive a frontpage digg on a single modestly-spec'd server if you've done the above. You'll eventually hit a point where the default apache config won't always be able to keep up with incoming requests. When you hit this wall, there are two things to do: 1. As above, profile. Monitor your apache activity -- you should have an idea of how many connections are active at any given time, in addition to the max number of active connections when you get sudden bursts of traffic 2. Configure apache with this in mind. This is the best guide to apache config I've seen: [Practical mod\_perl chapter 11](http://modperlbook.org/html/Chapter-11-Tuning-Performance-by-Tweaking-Apache-s-Configur.html) 3. Take as much load off of apache as you can. Apache's too heavy-duty to serve static content efficiently. You should be using a lighter-weight reverse proxy (like squid) or webserver (lighttpd or nginx) to serve static content, and to take over the job of spoon-feeding bytes to slow clients. This leaves Apache to do what it does best: execute your code. Again, the mod\_perl book does a good job of [explaining this](http://modperlbook.org/html/12-5-Adding-a-Proxy-Server-in-httpd-Accelerator-Mode.html). Once you've gotten this far, it's largely an issue of caching more, and keeping an eye on your database. Eventually, you'll outgrow a single server. First, you'll probably add more front end boxes, all backed by a single database server. Then you're going to have to start spreading your database load around, probably by sharding. For an excellent overview of this growth process, see [this livejournal presentation](http://www.slideshare.net/vishnu/livejournals-backend-a-history-of-scaling) For a more in-depth look at much of the above, check out [Building Scalable Web Sites](http://oreilly.com/catalog/9780596102357/), by Cal Henderson, of Flickr fame. Google has [portions of the book available for preview](http://books.google.com/books?id=gXmatd2suh4C&pg=PA235&dq=0596102356&ei=5xfRScSqG4fqkwTy9_ihAQ)
Best practices for optimizing LAMP sites for speed?
[ "", "php", "mysql", "optimization", "lamp", "" ]
Lets say I have the following tables: * Customers * Products * CustomerProducts Is there a way I can do a select from the Customers and Products tables, where the values are NOT in the map table? Basically I need a matched list of Customers and Products they do NOT own. Another twist: I need to pair one customer per product. So If 5 customers do not have Product A, only the first customer in the query should have Product A. So the results would look something like this: (Assume that all customers own product B, And more than one customer owns products A, C, and D) 1. Customer 1, Product A 2. Customer 2, Product C 3. Customer 3, Product D Final twist: I need to run this query as part of an UPDATE statement in SQL Sever. So I need to take the value from the first row: Customer 1, Product A and update the Customer record to something like ``` UPDATE Customers SET Customers.UnownedProduct = ProductA WHERE Customers.CustomerID = Customer1ID ``` But it would be nice if I could do this whole process, in one SQL statement. So I run the query once, and it updates 1 customer with a product they do not own. Hope that's not too confusing for you! Thanks in advance!
``` WITH q AS ( SELECT c.*, p.id AS Unowned, ROW_NUMBER() OVER (PARTITION BY p.id ORDER BY c.id) AS rn FROM Customers c CROSS JOIN Products p LEFT JOIN CustomerProducts cp ON cp.customer = c.id AND cp.product = p.id WHERE cp.customer IS NULL ) UPDATE q SET UnownedProduct = Unowned WHERE rn = 1 ``` `UPDATE` statement will update the *first* customer who doesn't own a certain product. If you want to select the list, you'll need: ``` SELECT * FROM ( SELECT c.*, p.id AS Unowned, ROW_NUMBER() OVER (PARTITION BY p.id ORDER BY c.id) AS rn FROM Customers c CROSS JOIN Products p LEFT JOIN CustomerProducts cp ON cp.customer = c.id AND cp.product = p.id WHERE cp.customer IS NULL ) cpo WHERE rn = 1 ```
I tried this in oracle (hope it works for you too) ``` UPDATE customers c SET unownedProduct = ( SELECT MIN( productid ) FROM products WHERE productid NOT IN ( SELECT unownedProduct FROM customers WHERE unownedProduct IS NOT NULL ) AND productid NOT IN ( SELECT productid FROM customerProducts cp WHERE cp.customerId = c.customerid ) ) WHERE customerId = 1 ```
How to select values from two tables that are not contained in the map table?
[ "", "sql", "sql-server", "stored-procedures", "subquery", "" ]
Consider this: Requisite: ``` //The alphabet from a-z List<char> letterRange = Enumerable.Range('a', 'z' - 'a' + 1) .Select(i => (Char)i).ToList(); //97 - 122 + 1 = 26 letters/iterations ``` Standard foreach: ``` foreach (var range in letterRange) { Console.Write(range + ","); } Console.Write("\n"); ``` Inbuilt foreach: ``` letterRange.ForEach(range => Console.Write(range + ",")); //delegate(char range) works as well Console.Write("\n"); ``` I have tried timing them against each other and the inbuilt foreach is up to 2 times faster, which seems like a lot. I have googled around, but I can not seem to find any answers. Also, regarding: [In .NET, which loop runs faster, 'for' or 'foreach'?](https://stackoverflow.com/questions/365615/in-c-net-which-loop-runs-faster-for-or-foreach) ``` for (int i = 0; i < letterRange.Count; i++) { Console.Write(letterRange[i] + ","); } Console.Write("\n"); ``` Doesn't act execute faster than standard foreach as far as I can tell.
I think your benchmark is flawed. `Console.Write` is an I/O bound task and it's the most time consuming part of your benchmark. This is a micro-benchmark and should be done very carefully for accurate results. Here is a benchmark: <http://diditwith.net/PermaLink,guid,506c0888-8c5f-40e5-9d39-a09e2ebf3a55.aspx> (It looks good but I haven't validated it myself). **The link appears to be broken as of 8/14/2015**
When you enter a foreach loop, you enumerate over each item. That enumeration causes two method calls per iteration: one to `IEnumerator<T>.MoveNext()`, and another to `IEnumerator<T>.Current`. That's two `call` IL instructions. `List<T>.ForEach` is faster because it has only one method call per iteration -- whatever your supplied `Action<T>` delegate is. **That's one `callvirt` IL instruction. This is significantly faster than two `call` instructions.** As others pointed out, IO-bound instructions like `Console.WriteLine()` will pollute your benchmark. Do something that can be confined entirely to memory, like adding elements of a sequence together.
Why is List<T>.ForEach faster than standard foreach?
[ "", "c#", ".net", "list", "foreach", "benchmarking", "" ]
I have 1 table filled with articles. For the purpose of this post, lets just say it has 4 fields. story\_id, story\_title, story\_numyes, story\_numno Each article can be voted YES or NO. I store every rating in another table, which contains 3 fields: vote\_storyid, vote\_date (as a timestamp), vote\_code (1 = yes, 0 = no). So when somebody votes yes on an article, it run an update query to story\_numyes+1 as well as an insert query to log the story id, date and vote\_code in the 2nd table. I would like to sort articles based on how many YES or NO votes it has. For "Best of all time" rating is obviously simple.... ORDER BY story\_numyes DESC. But how would I go about doing best/worst articles today, this week, this month? I get the timestamps to mark the cut-off dates for each period via the following: ``` $yesterday= strtotime("yesterday"); $last_week = strtotime("last week"); $last_month = strtotime("last month"); ``` But Im not sure how to utilize these timestamps in a mysql query to achieve the desired results.
Try something like > SELECT id, > SUM(CASE WHEN votedate >= $yesterday THEN 1 ELSE 0 END) AS daycount, > SUM(CASE WHEN votedate >= $last\_week THEN 1 ELSE 0 END) AS weekcount, > SUM(1) AS monthcount > FROM votes > WHERE yes\_no = 'YES' > AND votedate >= $last\_month > GROUP BY id Then make that a subquery and you can get the max values for the counts. (Please allowing for the usual syntax sloppiness inherent in an untested query.) --- In response to the comments: To use it as an efficient subquery (i.e. not correlated) to get the maximum values: > SELECT > MAX(daycount) AS MaxDayCount, > MAX(weekcount) AS MaxWeekCount, > MAX(monthcount) AS MaxMonthCount > FROM > ( > .... all that stuff ... > ) AS qcounts but of course you can't attribute them to ids, because they are different. If you want them one at a time with ids, you might > SELECT id, monthcount > FROM > ( > .... all that stuff ... > ) AS qcounts > ORDER BY monthcount DESC > LIMIT 1 and do it three times, once for day/week/month. Note: this is all to illustrate some things you could accomplish in a single reasonably efficient query. I wouldn't be surprised if you were to find it's simplest (and simple == good) to break it up as others suggest.
In general: ``` select story_id, sum(vote_code) from story_vote group by story_id; ``` For particular vote date ranges: ``` select story_id, sum(vote_code) from story_vote where vote_date >= 'least date, inclusive' and vote_date < 'last date, exclusive' group by story_id; ``` OP comments: > How would I use the ORDER BY clause? You'd add an `order by sum(vote_code)`. Descending if you want stories with the most votes first: ``` order by sum(vote_code) desc; ``` On edit: I notice he wants all stories, not one, so I'm removing the having clause.
Whats the best way to implement time based sorting in php/mysql?
[ "", "php", "mysql", "" ]
Imagine that users are inserting strings in several computers. On one computer, the pattern in the configuration will extract some characters of that string, lets say position 4 to 5. On another computer, the extract pattern will return other characters, for instance, last 3 positions of the string. These configurations (the Regex patterns) are different for each computer, and should be available for change by the administrator, without having to change the source code. Some examples: ``` Original_String Return_Value User1 - abcd78defg123 78 User2 - abcd78defg123 78g1 User3 - mm127788abcd 12 User4 - 123456pp12asd ppsd ``` Can it be done with Regex? Thanks.
To have a regex capture values for further use you typically use (), depending on the regex compiler it might be () or for microsoft MSVC I think it's [] Example ``` User4 - 123456pp12asd ppsd ``` is most interesting in that you have here 2 seperate capture areas. Is there some default rule on how to join them together, or would you then want to be able to specify how to make the result? Perhaps something like ``` r/......(..)...(..)/\1\2/ for ppsd r/......(..)...(..)/\2-\1/ for sd-pp ``` do you want to run a regex to get the captures and handle them yourself, or do you want to run more advanced manipulation commands?
Why do you want to use regex for this? What is wrong with: ``` string foo = s.Substring(4,2); string bar = s.Substring(s.Length-3,3); ``` (you can wrap those up to do a bit of bounds-checking on the length easily enough) If you really want, you could wrap it up in a `Func<string,string>` to put somewhere - not sure I'd bother, though: ``` Func<string, string> get4and5 = s => s.Substring(4, 2); Func<string,string> getLast3 = s => s.Substring(s.Length - 3, 3); string value = "abcd78defg123"; string foo = getLast3(value); string bar = get4and5(value); ```
Extract substring from string with Regex
[ "", "c#", "regex", "" ]
Can someone help me? I am trying to do something like the following: ``` #include <boost/iostreams/tee.hpp> #include <boost/iostreams/stream.hpp> #include <sstream> #include <cassert> namespace io = boost::iostreams; typedef io::stream<io::tee_device<std::stringstream, std::stringstream> > Tee; std::stringstream ss1, ss2; Tee my_split(ss1, ss2); // redirects to both streams my_split << "Testing"; assert(ss1.str() == "Testing" && ss1.str() == ss2.str()); ``` But it won't compile in VC9: ``` c:\lib\boost_current_version\boost\iostreams\stream.hpp(131) : error C2665: 'boost::iostreams::tee_device<Sink1,Sink2>::tee_device' : none of the 2 overloads could convert all the argument types ``` Has anyone gotten this to work? I know I could make my own class to do it, but I want to know what I am doing wrong. Thanks
You use the [constructor-forwarding version](http://www.boost.org/doc/libs/1_38_0/libs/iostreams/doc/guide/generic_streams.html#stream_forwarding_constructors) of `io::stream`, which construct a tee-stream itself and forward all arguments to that. C++03 has only limited capabilities when it comes to forwarding arguments to functions (amount of overloads needed easily grow exponentially). It (`io::stream`) makes the following restrictions: > Each of these members constructs an instance of stream and associates it with an instance of the Device T constructed from the given lists of arguments. *The T constructors involved must take all arguments by value or const reference.* Well, but the `tee_device` constructor says > Constructs an instance of tee\_device based on the given pair of Sinks. Each function parameter is a non-const reference if the corresponding template argument is a stream or stream buffer type, and a const reference otherwise. That won't work, of course. `io::stream` provides another constructor that takes a `T` as first argument. This works here (Compiles, at least. The assertion fails, though. I've not worked with `boost::iostreams` so i can't help with that) ``` namespace io = boost::iostreams; typedef io::tee_device<std::stringstream, std::stringstream> TeeDevice; typedef io::stream< TeeDevice > TeeStream; std::stringstream ss1, ss2; TeeDevice my_tee(ss1, ss2); TeeStream my_split(my_tee); my_split << "Testing"; assert(ss1.str() == "Testing" && ss1.str() == ss2.str()); ``` Edit: After calling `flush()` or streaming `<< std::flush`, the assertion passes.
Probably you need to set it up like this: ``` typedef io::tee_device<std::stringstream, std::stringstream> Tee; typedef io::stream<Tee> TeeStream; std::stringstream ss1, ss2; Tee my_tee(ss1, ss2); TeeStream my_split(my_tee); ```
Using boost::iostreams::tee_device?
[ "", "c++", "stream", "iostream", "boost-iostreams", "" ]
I have a CEdit text box which is a part of a property pane and only allows numeric values (positive integers). The box works fine when people enter non-numeric values, but when they delete the value in the box a dialog pops up saying: "Please enter a positive integer." Here is the situation: 1. I have a number (say 20) in the box. 2. I delete the number. 3. I get the error dialog. Could anybody tell me how I can intercept this event and put a default value in there? Here is what my property pane looks like: ``` const int DEFAULT_VALUE = 20; class MyPropertyPane:public CPropertyPane { //.... private: CEdit m_NumericBox; int m_value; //.... public: afx_msg void OnEnChangeNumericBox(); //.... } void MyPropertyPane::MyPropertyPane() { // Set a default value m_value = DEFAULT_VALUE; } //.... void MyPropertyPane::DoDataExchange(CDataExchange* pDX) { DDX_Control(pDX, IDC_NUMERIC_BOX, m_NumericBox); // this sets the displayed value to 20 DDX_Text(pDX, IDC_NUMERIC_BOX, m_value); } //.... void MyPropertyPane::OnEnChangeNumericBox() { // Somebody deleted the value in the box and I got an event // saying that the value is changed. // I try to get the value from the box by updating my data UpdateData(TRUE); // m_value is still 20 although the value is // deleted inside the text box. } ```
The message you are receiving is coming from the data validation routines, not the data exchange routines. There is probably a call like this in DoDataExchange(): ``` void MyPropertyPane::DoDataExchange(CDataExchange* pDX) { DDX_Control(pDX, IDC_NUMERIC_BOX, m_NumericBox); DDX_Text(pDX, IDC_NUMERIC_BOX, m_value); DDV_MinMaxInt(pDX, m_value, 1, 20); // if the value in m_value is outside the range 1-20, MFC will pop up an error dialog } ``` You can fix this problem by removing the built-in MFC data validation and adding your own: ``` void MyPropertyPane::DoDataExchange(CDataExchange* pDX) { DDX_Control(pDX, IDC_NUMERIC_BOX, m_NumericBox); DDX_Text(pDX, IDC_NUMERIC_BOX, m_value); if( m_value < 1 || m_value > 20 ) { m_value = DefaultValue; } } ```
John Dibling's hint led me to this solution: ``` void MyPropertyPane::OnEnChangeNumericBox() { UpdateData(TRUE); CString value; m_NumericBox.GetWindowText(value); if( value.IsEmpty() ) { m_value = DEFAULT_VALUE; UpdateData(FALSE); } } ``` The ONLY validation that I really had to do is to check that the box contains a value, since the actual numeric validation is already handled by the box. The user can't enter a non-numeric value, but they can delete the existing one so that was a situation which was hard to handle in the data exchange function and I had to "hack" the OnChange event.
CEdit numeric validation event C++ MFC
[ "", "c++", "events", "mfc", "numeric", "cedit", "" ]
I'm wondering if there is a quick and easy way to output ordinals given a number in python. For example, given the number `1`, I'd like to output `"1st"`, the number `2`, `"2nd"`, et cetera, et cetera. This is for working with dates in a breadcrumb trail ``` Home > Venues > Bar Academy > 2009 > April > 01 ``` is what is currently shown I'd like to have something along the lines of ``` Home > Venues > Bar Academy > 2009 > April > 1st ```
Or shorten David's answer with: ``` if 4 <= day <= 20 or 24 <= day <= 30: suffix = "th" else: suffix = ["st", "nd", "rd"][day % 10 - 1] ```
Here's a more general solution: ``` def ordinal(n): if 10 <= n % 100 < 20: return str(n) + 'th' else: return str(n) + {1 : 'st', 2 : 'nd', 3 : 'rd'}.get(n % 10, "th") ```
Date Ordinal Output?
[ "", "python", "" ]
I've got a thread dump of an applet running on JVM 1.6.0\_12 in Opera 9.64 Build 10487 - and it shows three event queues! As far as I know the Java Swing event handling is single threaded - did this change in any recent update? My problem is, that multiple event queues will tend to cause deadlocks since I've got some more locks than only the GUI TreeLock.
There can be more than one, and it depends on the browser. [EventQueue documentation](http://java.sun.com/javase/6/docs/api/java/awt/EventQueue.html) says: Some browsers partition applets in different code bases into separate contexts, and establish walls between these contexts. In such a scenario, there will be one EventQueue per context. Other browsers place all applets into the same context, implying that there will be only a single, global EventQueue for all applets. This behavior is implementation-dependent.
Yes. Typically there will be only one `Toolkit` for `Toolkit.getDefaultToolkit`, but multiple `EventQueue`s from `Toolkit.getSystemEventQueue` (which from 1.2.2 you typically get permissions to call successfully). There is magic based on `ThreadGroup` and `ClassLoader`s on the stack to determine which `EventQueue` to return. Applets are partitioned dependent upon their origin and configuration. Exactly how this is done is implementation dependent. Now, what you are probably seeing is an event queue for your applet and the secure context. The secure context handles the dialog boxes from the plugin itself. Accepting certificates and things like that. The secure context keeps these away from user code in your applet context.
Can there be more than one AWT event queue?
[ "", "java", "multithreading", "swing", "events", "queue", "" ]
I have a package with a ``` public abstract class Player { /*...*/ } ``` and these ``` public abstract class GamePlayer extends Player { /*...*/ } public abstract class TournamentPlayer extends Player { /*...*/ } public abstract class StatelessPlayer extends Player { /*...*/ } ``` Users of the package need Players but in order to use the package without breaking it I require that they never *directly* extend Player. Instead they should extend one of the subclasses provided. Question: How should I prevent users from extending Player directly? I'm looking for a way that makes it obvious that this prohibition is intended.
Make the constructors in `Player` have package access only. Then they won't be able to call the constructor or extend it themselves. If you don't already *have* an explicit constructor in `Player`, create one (as otherwise the compiler will create a default public parameterless constructor). (Note that I've only suggested doing this to the *constructor*. The class itself can be public so that clients can still use it.) This works because any constructor (other than in `java.lang.Object`) has to call a superclass constructor (either explicitly or implicitly). If there are no accessible constructors, you can't create the subclass.
Make sure the constructors of Player are not public: ``` public abstract class Player { Player() { // initialization goes here } } ``` Then classes can extend Player from within the same package, but should not be able to from outside of the package.
Prohibit direct extension of Java class outside its package
[ "", "java", "inheritance", "api-design", "" ]
Im actually new to using this function.. and was using preg\_replace and addslashes previous to finding it. I'm mostly curious, because Im about to go through, and tighten security in the posting areas in my first large app, and wanted to know the best instances where this function is effective, and highly recommended. I've seen this function applied in a few different situations, and not just before user input is posted.. but when queries are done in general, so Im really curious about its full possibilities, and how to implement it to its full effectiveness. Also, any infallible security methods, and suggestions in general will be really appreciated. Cheers all!
Ideally you should *never* be using it, because [Parameterized queries](http://en.wikipedia.org/wiki/SQL_injection#Using_Parameterized_Statements) (either through [PDO](http://php.net/manual/en/pdo.prepare.php) or [mysqli](http://php.net/manual/en/mysqli-stmt.prepare.php)) are the correct way to prevent SQL injection.
You should probably use [mysqli\_real\_escape\_string](http://ca.php.net/mysqli_real_escape_string) or [PDO](http://ca.php.net/pdo) with bound parameters instead. The main use for any of them is to escape characters like single and double quotes. This is generally to prevent [SQL injection](http://phpsec.org/projects/guide/3.html#3.2).
When are the most recommended times to use mysql_real_escape_string()
[ "", "php", "mysql", "security", "" ]
I'm using Django 1.0.2. I've written a ModelForm backed by a Model. This model has a ForeignKey where blank=False. When Django generates HTML for this form it creates a select box with one option for each row in the table referenced by the ForeignKey. It also creates an option at the top of the list that has no value and displays as a series of dashes: ``` <option value="">---------</option> ``` What I'd like to know is: 1. What is the cleanest way to remove this auto-generated option from the select box? 2. What is the cleanest way to customize it so that it shows as: ``` <option value="">Select Item</option> ``` In searching for a solution I came across [Django ticket 4653](http://code.djangoproject.com/ticket/4653) which gave me the impression that others had the same question and that the default behavior of Django may have been modified. This ticket is over a year old so I was hoping there might be a cleaner way to accomplish these things. Thanks for any help, Jeff Edit: I've configured the ForeignKey field as such: ``` verb = models.ForeignKey(Verb, blank=False, default=get_default_verb) ``` This does set the default so that it's no longer the empty/dashes option but unfortunately it doesn't seem to resolve either of my questions. That is, the empty/dashes option still appears in the list.
Haven't tested this, but based on reading Django's code [here](http://code.djangoproject.com/browser/django/trunk/django/forms/models.py#L680) and [here](http://code.djangoproject.com/browser/django/trunk/django/forms/models.py#L710) I believe it should work: ``` class ThingForm(forms.ModelForm): class Meta: model = Thing def __init__(self, *args, **kwargs): super(ThingForm, self).__init__(*args, **kwargs) self.fields['verb'].empty_label = None ``` **EDIT**: This is [documented](http://docs.djangoproject.com/en/dev/ref/forms/fields/#modelchoicefield), though you wouldn't necessarily know to look for ModelChoiceField if you're working with an auto-generated ModelForm. **EDIT**: As jlpp notes in his answer, this isn't complete - you have to re-assign the choices to the widgets after changing the empty\_label attribute. Since that's a bit hacky, the other option that might be easier to understand is just overriding the entire ModelChoiceField: ``` class ThingForm(forms.ModelForm): verb = ModelChoiceField(Verb.objects.all(), empty_label=None) class Meta: model = Thing ```
from the docs > The blank choice will not be included > if the model field has blank=False and > an explicit default value (the default > value will be initially selected > instead). so set the default and you're ok
Customize/remove Django select box blank option
[ "", "python", "django", "django-models", "django-forms", "" ]
I'm trying to delete a worksheet from a excel document from a .Net c# 3.5 application with the interop Excel class (for excel 2003). I try many things like : ``` Worksheet worksheet = (Worksheet)workbook.Worksheets[1]; worksheet.Delete(); ``` It's doesn't work and doesn't throw any error ...
After more than one hour looking I found the answer: ``` xlApp.DisplayAlerts = false; worksheet.Delete(); xlApp.DisplayAlerts = true; ```
When dealing with deleting *Excel Worksheets*, there are two important things to know: 1. Excel interop counts from 1 (and not from zero), therefore, removing the second item will cause the third item to take its place!. so, the proper way to remove worksheets is from the **last to the first**: ``` // Remove LAST worksheet MyWorkBook.Worksheets[3].Delete(); // and only then remove the second (which is the last one) MyWorkBook.Worksheets[2].Delete(); ``` alternatively, you can delete the second item ([2]) on the list **twice**, which will give you the same result. 2. The following line **will** throw exception when you only got one worksheet left: ``` MyWorkBook.Worksheets[1].Delete(); ```
.Net Excel Interop Deleting a worksheet
[ "", "c#", ".net", "excel", "interop", "" ]
**(Thanks everyone for the answers, [here is my refactored example](https://stackoverflow.com/questions/659232/it-this-an-example-of-the-single-responsibility-principle), in turn another StackOverflow question about the Single Responsibility Principle.)** Coming from PHP to C#, this syntax was intimidating: ``` container.RegisterType<Customer>("customer1"); ``` until I realized it expresses the same thing as: ``` container.RegisterType(typeof(Customer), "customer1"); ``` as I demonstrate in the code below. So **is there some reason why generics is used here** (e.g. throughout Unity and most C# IoC containers) other than it just being a cleaner syntax, i.e. you don't need the typeof() when sending the type? ``` using System; namespace TestGenericParameter { class Program { static void Main(string[] args) { Container container = new Container(); container.RegisterType<Customer>("test"); container.RegisterType(typeof(Customer), "test"); Console.ReadLine(); } } public class Container { public void RegisterType<T>(string dummy) { Console.WriteLine("Type={0}, dummy={1}, name of class={2}", typeof(T), dummy, typeof(T).Name); } public void RegisterType(Type T, string dummy) { Console.WriteLine("Type={0}, dummy={1}, name of class={2}", T, dummy, T.Name); } } public class Customer {} } //OUTPUT: //Type=TestGenericParameter.Customer, dummy=test, name of class=Customer //Type=TestGenericParameter.Customer, dummy=test, name of class=Customer ```
A primary reason is the type safety at compile time. If you are passing two `Type` objects you are placing the responsibility at the developer instead of the compiler. This is also why many IoC containers utilizes it, as your compiler will complain if an concrete type isn't inheriting the abstract type. ``` public void Register<TAbstract, TConcrete>() where TConcrete : TAbstract { } ``` This code will only work if `TConcrete` is implementing or inheriting `TAbstract`. If this method took two `Type` parameters, your method should validate this relationship.
One reason when generics are very useful is when the generic type parameter is used as the type of a parameter or as the return type of the method. That means, you can write methods like ``` public T GetAs<T>(string name) ``` where the return type can be checked by the compiler and boxing value types can sometimes be avoided. The caller would write: ``` int value = GetAs<int>("foo"); ``` Whithout generics, you would have to write ``` public object GetAs(Type t, string name) ``` and the caller has to cast the result again: ``` int value = (int)GetAs(typeof(int), "foo"); ```
What are the advantages of using generics in method signatures?
[ "", "c#", "generics", "" ]
What have you done to remove (Helpers/extension methods) string literal in code? e.g. I have nhibernate search criteria code like this all over the place. ``` Expression.Eq("Status", LoginStatus.LoggedIn), ``` *“Status”* being the property of an entity object used as a string in the case. **Update**: Primary reason in this case is to enable refactoring. If I write a helper method which reflects the object and gets the value, will make the above expression strongly typed.
Realized that I could do this the Expression trees way. Using Code as data! *Something like this* ``` protected IList<T> _FindByProperty<TResult>(Expression<Func<T, TResult>> expression, TResult value) { return _FindByProperty((expression.Body as MemberExpression).Member.Name, value); } IList<User> costCenters = _FindByProperty( user=> user.Name, "name"); ``` ***Credits***: <http://suryagaddipati.wordpress.com/2009/03/14/code-as-data-in-c-taking-advantage-of-expression-trees/> This is related to a lot questions in the [expression-trees](https://stackoverflow.com/questions/tagged/expression-trees) tag.
This is what "Resources" and "Settings" is for. You can find this by right clicking your project in Visual Studio and clicking "Properties", then going to the "Resources" or "Settings" tab. For pre-built resources that won't change often, use resources. For things you want to be configurable use Settings instead because it will auto-generate blocks of configuration for your App.config. You will still need to manually copy and paste these values if you do not want to use the defaults. The nice thing about both is that VS will build a nice static class with properties you can use throughout your code. VS will maintain the class and resources for you dynamically as long as you continue to use the wizard.
Removing literal strings in .net code
[ "", "c#", ".net", "" ]
Here's my code: ``` x = 1.0 y = 100000.0 print x/y ``` My quotient displays as `1.00000e-05`. Is there any way to suppress scientific notation and make it display as `0.00001`? I'm going to use the result as a string.
``` '%f' % (x/y) ``` but you need to manage precision yourself. e.g., ``` '%f' % (1/10**8) ``` will display zeros only. [details are in the docs](https://docs.python.org/3/library/string.html#formatstrings) Or for Python 3 [the equivalent old formatting](http://docs.python.org/py3k/library/stdtypes.html#old-string-formatting-operations) or the [newer style formatting](http://docs.python.org/py3k/library/string.html#string-formatting)
Using the newer version `''.format` (also remember to specify how many digit after the `.` you wish to display, this depends on how small is the floating number). See this example: ``` >>> a = -7.1855143557448603e-17 >>> '{:f}'.format(a) '-0.000000' ``` as shown above, default is 6 digits! This is not helpful for our case example, so instead we could use something like this: ``` >>> '{:.20f}'.format(a) '-0.00000000000000007186' ``` ## Update Starting in Python 3.6, this can be simplified with the new [formatted string literal](https://docs.python.org/3/whatsnew/3.6.html#whatsnew36-pep498), as follows: ``` >>> f'{a:.20f}' '-0.00000000000000007186' ```
How to suppress scientific notation when printing float values?
[ "", "python", "floating-point", "" ]
I have a statement ``` String pass = com.liferay.portal.util.PortalUtil.getUserPassword(renderRequest); ``` that causes the following error in eclipse IDE: > The type javax.servlet.http.HttpSession cannot be resolved. It is indirectly referenced from required .class files Why is this error occuring? I have added an import statement for the type but yet the error remains. How can I remove this error? Thanks for your help.
It sounds like you haven't referenced the right libraries. Add a reference to servlet.jar.
You need to put the definition of that class (usually contained in a servlet.jar file) into the build path of your project (right-click on the project, select "Properties" and then "Build Path").
Java type cannot be resolved
[ "", "java", "" ]
Is it possible to position an element fixed relative to the viewport in Mobile Safari? As many have noted, `position: fixed` doesn't work, but Gmail just came out with a solution that almost is what I want – see the floating menu bar on the message view. Getting real-time scroll events in JavaScript would also be a reasonable solution.
iOS 5 has [support for position:fixed](http://davidbcalhoun.com/2011/new-mobile-safari-stuff-in-ios5-position-fixed-overflow-scroll-new-input-type-support-web-workers-ecmascript-5).
This fixed position div can be achieved in just 2 lines of code which moves the div on scroll to the bottom of the page. ``` window.onscroll = function() { document.getElementById('fixedDiv').style.top = (window.pageYOffset + window.innerHeight - 25) + 'px'; }; ```
Fixed positioning in Mobile Safari
[ "", "javascript", "iphone", "css", "mobile-safari", "" ]
When creating a MailMessage object by calling the "CreateMailMessage" method on the MailDefinition class, the third parameter is an object of type System.Web.UI.Control. ``` MailDefinition mail = new MailDefinition(); ListDictionary replacements = new ListDictionary(); replacements.Add("<%myname%>", "John"); mail.BodyFileName = "~/App_Data/Emails/SomeEmail.txt"; mail.From = "me@example.com"; mail.Subject = "Hello"; MailMessage message = mail.CreateMailMessage("example@example.com,", replacements, ); ``` Why is that? And in the case that I don't have an object of that type, what should I pass instead? Just a new Control object? ``` Control control = new Control(); ``` **UPDATE** I would highly recommend using [Razor](http://razorengine.codeplex.com/) to build email templates. It has great syntax, works great, and doesn't have any weird dependencies!
Usually you just pass `this` as the control. ``` MailMessage message = mail.CreateMailMessage("example@example.com,", replacements, this); ``` As for the reason why, [here is what MSDN says:](http://msdn.microsoft.com/en-us/library/0002kwb2.aspx) > The owner parameter indicates which control is the parent of the MailDefinition control. It determines which directory to search for the text file specified in the BodyFileName property.
The **CreateMailMessage** function internally uses the specified **Control** to query its **AppRelativeTemplateSourceDirectory** property and its **OpenFile** method to read the contents of the body (specified in the **BodyFileName** property of the **MailDefinition**). Seems poor design and unnecessary tight coupling for me.
Why does the MailDefinition class require a System.Web.UI.Control?
[ "", "c#", "asp.net", "mailmessage", "" ]
What are some of the best practices in designing a JMX MBean? Any examples of ones you feel are especially useful?
Return absolute counts instead of rates. e.g. return total number of db commits, rather than deriving a rate. By doing this, your clients can monitor and derive rates themselves, over whatever time periods they require. Perhaps more importantly, this protects the clients from missing surges in rates if they only connect infrequently. If you're using JMX beans primarily via the HTML interface, then there are several practises I follow. The below often means that your JMX bean should wrap an existing bean (as opposed to just JMX-exposing existing methods): 1. output properly formatted strings representing returned objects. Getting a default `toString()` output can be next to useless 2. capture and display exceptions. Otherwise you'll likely get a blank page and have to go to the log files to determine what went wrong 3. if you're displaying different character sets, you may have to escape the output appropriately to prevent display problems (I ran into this with a JMX control displaying our Chinese data) 4. inputs to exposed methods should be sanitised properly (e.g. if you input a id as part of an operation you may wish to `trim()` it to remove whitespace etc.) The above changes the emphasis from a bean simply exposed via JMX to something approaching a useable admin console.
The first thing that got me with my first JMX bean was return types - it's a lot easier if your methods return Strings - that way your client can easily display the response (I was mainly working with JConsole) - if you don't do this, you get things like com.mycompany.Response@xxxx as a response, which doesn't mean much :)
What are the characteristics of a well-designed JMX MBean
[ "", "java", "performance", "jmx", "" ]
HI! Here is my case: I have some value type which is wrapped into another type with appropriate implicit converters. If I cast wrapped type to an object and then try to get original value I can do that in two-step cast only. If simplified my code is as follows: ``` public enum MyEnum : int { First, Second } public class Test<T> { public Test(T val) { Value = val; } private T Value { get; set; } public static implicit operator T(Test<T> m) { return m.Value; } public static implicit operator Test<T>(T m) { var res = new Test<T>(m); return res; } } static void Main() { object res = new Test<MyEnum>(MyEnum.First); Console.WriteLine((MyEnum)(Test<MyEnum>)res); Console.WriteLine((MyEnum)res); } ``` First "Console.WriteLine" works OK. Second one fails. Is there any way I can modify this behavior and get it working without double casting? **UPDATE 1** I must use object to value cast (in real application I have to cast ComboBox.SelectedItem property and I do not want to add extra property to ComboBox, because I'll have to change my UI interaction code everywhere). **UPDATE 2** Implicit conversions to and from System.Object are not allowed. **UPDATE 3** Updated my sample code to reflect the whole problem.
If you want to simplify casting and not care performance effect, then create extension method. ``` public static T To<T>(this object obj) { Type type = obj.GetType(); MethodInfo[] methods = type.GetMethods(BindingFlags.Public | BindingFlags.Static); MethodInfo method = methods.FirstOrDefault(mi => (mi.Name == "op_Implicit" || mi.Name == "op_Explicit") && mi.ReturnType == typeof(T)); if (method == null) throw new ArgumentException(); return (T)method.Invoke(null, new[] { obj }); } ``` Usage ``` Console.WriteLine(res.To<MyEnum>()); ```
Don't use `object` that way. Write your first line like this instead: ``` Test res = new Test(1); ``` If you must have it in an object first, remember that all the *compiler* knows about it at this point is that it's an object, and nothing more. You, as the programmer, have additional information about what you expect this object to be, but for the compiler to take advantage of that information you have to put it into your code somewhere. **Update:** I'm glad I was able to find this again, because this almost-very-timely article by Eric Lippert, who works on the C# language design, went up this morning and explains the problem in depth: <http://blogs.msdn.com/ericlippert/archive/2009/03/19/representation-and-identity.aspx>
C#: How can I use implicit cast operator during object to type conversion?
[ "", "c#", "enums", "casting", "" ]
I put the following in my settings.py file. The email address there is a test one. I found the email settings from [Webfaction](https://help.webfaction.com/index.php?_m=knowledgebase&_a=viewarticle&kbarticleid=128&nav=0,3)'s site: ``` EMAIL_HOST = 'smtp.webfaction.com' EMAIL_HOST_USER = 'hekevintran_test' EMAIL_HOST_PASSWORD = 'testpass' EMAIL_PORT = 465 EMAIL_USE_TLS = True ``` This is what my file looks like: ``` from django.core.mail import send_mail send_mail(subject='subject', message='message', from_email='hekevintran_test@webfaction.com', recipient_list=['recipient@yahoo.com'], fail_silently=False) ``` When I run the above it stalls a long time and then gives me this error: ``` SMTPServerDisconnected: Connection unexpectedly closed ``` What am I doing wrong?
I have a Django project on Webfaction right now that is properly sending emails. The only difference between your settings and mine is that I did not specify `EMAIL_PORT` or `EMAIL_USE_TLS`. Try it out without those settings and let Django use the default it has and see if it works. For reference's sake, [the default settings](http://docs.djangoproject.com/en/dev/ref/settings/#email-port) are: ``` EMAIL_PORT = 25 EMAIL_USE_TLS = False ```
I had this problem with my hosted account at asmallorange.com. There, it was a firewall problem. I would suggest contacting support and ensuring port 465 can get through the firewall.
Why is my send_mail() command not working in Django?
[ "", "python", "django", "email", "" ]
For example, The function could be something like def RandABCD(n, .25, .34, .25, .25): Where n is the length of the string to be generated and the following numbers are the desired probabilities of A, B, C, D. I would imagine this is quite simple, however i am having trouble creating a working program. Any help would be greatly appreciated.
Thank you all for your help, I was able to figure something out, mostly with this info. For my particular need, I did something like this: ``` import random #Create a function to randomize a given string def makerandom(seq): return ''.join(random.sample(seq, len(seq))) def randomDNA(n, probA=0.25, probC=0.25, probG=0.25, probT=0.25): notrandom='' A=int(n*probA) C=int(n*probC) T=int(n*probT) G=int(n*probG) #The remainder part here is used to make sure all n are used, as one cannot #have half an A for example. remainder='' for i in range(0, n-(A+G+C+T)): ramainder+=random.choice("ATGC") notrandom=notrandom+ 'A'*A+ 'C'*C+ 'G'*G+ 'T'*T + remainder return makerandom(notrandom) ```
Here's the code to select a single weighted value. You should be able to take it from here. It uses [bisect](http://docs.python.org/library/bisect.html#bisect.bisect) and [random](http://docs.python.org/library/random.html#random.random) to accomplish the work. ``` from bisect import bisect from random import random def WeightedABCD(*weights): chars = 'ABCD' breakpoints = [sum(weights[:x+1]) for x in range(4)] return chars[bisect(breakpoints, random())] ``` Call it like this: `WeightedABCD(.25, .34, .25, .25)`. **EDIT: Here is a version that works even if the weights don't add up to 1.0:** ``` from bisect import bisect_left from random import uniform def WeightedABCD(*weights): chars = 'ABCD' breakpoints = [sum(weights[:x+1]) for x in range(4)] return chars[bisect_left(breakpoints, uniform(0.0,breakpoints[-1]))] ```
I need a Python Function that will output a random string of 4 different characters when given the desired probabilites of the characters
[ "", "python", "random", "" ]
In .Net is there a class in .Net where you can get the DB name, and all the connection string info without acutally doing a substring on the connection string? EDIT: I am not creating a connection I am attempting to get info out of the connection string. So I am basicly looking for something that takes a connection string arg and has accessors to dbName, connection type, etc....
You can use the provider-specific ConnectionStringBuilder class (within the appropriate namespace), or `System.Data.Common.DbConnectionStringBuilder` to abstract the connection string object if you need to. You'd need to know the provider-specific keywords used to designate the information you're looking for, but for a SQL Server example you could do either of these two things: Given ``` string connectionString = "Data Source = .\\SQLEXPRESS;Database=Northwind;Integrated Security=True;"; ``` You could do... ``` System.Data.Common.DbConnectionStringBuilder builder = new System.Data.Common.DbConnectionStringBuilder(); builder.ConnectionString = connectionString; string server = builder["Data Source"] as string; string database = builder["Database"] as string; ``` Or ``` System.Data.SqlClient.SqlConnectionStringBuilder builder = new System.Data.SqlClient.SqlConnectionStringBuilder(); builder.ConnectionString = connectionString; string server = builder.DataSource; string database = builder.InitialCatalog; ```
After you initialize the connection with the connection string, you can get those information from properties of the initialized connection object. Check System.Data.Common.DbConnection.
Database Connection String Info
[ "", "c#", "" ]
I have some input checkboxes that are being dynamically generated in a `$.post` callback function. Then i have a `$().change()` call that does things when the value is changed (alerts some info). However, for the dynamically generated inputs, the .change() does not work. There are other inputs that work that are hardcoded into the html that work, but the other ones do not. Here is the code. ``` <html> <head> <script type="text/javascript" src="js/jquery.js"></script> <script> $(document).ready(function(){ $("#hideme").hide(); $.post("php/test.php",{},function(data){ writeMe = "<input type='checkbox' name='foo' value='" + data + "'>" + data; $("#insert").html(writeMe); }, "json"); $("input[name=foo]").change(function(){ alert($(this).attr("value")); }) }); </script> </head> <body> <div id="insert"></div> <input type="checkbox" name='foo' value='world'>world </body> </html> ``` php/test.php is simply: ``` echo json_encode("hello"); ```
The problem is that your statement: ``` $("input[name=foo]").change(function(){ alert($(this).attr("value")); }) ``` doesn't have any effect because at the time it executes, there are no elements that match $("input[name=foo]") because the $.post() callback hasn't happened yet.
In addition, if you do need to define the hooks before the $.post takes place, look at using [LiveQuery](http://docs.jquery.com/Plugins/livequery), as it allows you to listen for any new elements that match your selector and bind them too.
events not registering after html being generated with $.post callback
[ "", "javascript", "jquery", "json", "" ]
Suppose I have an interface for a service: ``` public interface IFooService { void DoSomething(); } ``` And a concrete implementation of that service that is a generic: ``` public class FooService<TRequestingClass> : IFooService { public virtual void DoSomething() { } } ``` And I have some other class that needs an instance of IFooService: ``` public class Bar { private IFooService _fooService; public Bar(IFooService fooService) { this._fooService = fooService; } } ``` I need to wire up my IoC container such that when Bar gets created, it gets passed a constructor argument of FooService<Bar>. There are many other classes just like Bar. Each might also need an instance of FooService<TRequestingClass> passed to them where TRequestingClass is the type of the class that needs the instance of IFooService. I don't need to expose this quirkiness to the consumers of IFooService. All they should care about is that they can call the methods of the IFooService they were passed. They should not need to know that the concrete implementation of IFooService they were passed needed anything special to be constructed. An acceptable alternatative to FooService<T> would to be a non-generic class that has a string argument in its constructur that contains the name of the class it is being created for. i.e: ``` public class FooService : IFooService { public FooService(string requestingClassName) { } } ``` **How can I wire up my IoC container to construct a dependency this way?** If you are confused why I would want such a wierd structure, consider how log4net works best when you get an ILog that gets created with log4net.LogManager.GetLogger(typeof(SomeClass)). I don't want to litter my code with references to log4net, so I'd like to write a simple ILogger interface, and implement it with something like this: ``` public class GenericLogger<T> : ILogger { private readonly ILog log; public GenericLogger() { this.log = log4net.LogManager.GetLogger(typeof(T)); } public void Debug(object message) { this.log.Debug(message); } /* .... etc .... */ } ```
The easiest way would be to create an `ILogger<T>` interface: ``` public class ILogger<T> : ILogger { } public class GenericLogger<T> : ILogger<T> { ... } ``` Then rely on generic type inference to get the correct type. For example, in Ninject, the following binding is all you'd need: ``` Bind(typeof(ILogger<>)).To(typeof(GenericLogger<>)); ``` Then your consuming types would look like this: ``` public class FooService : IFooService { public FooService(ILogger<FooService> logger) { ... } } ``` If you're adamantly against the `ILogger<T>` interface, you could do something more creative, like a custom provider, which reads the `IContext` to determine the parent type. ``` public class GenericLogger : ILogger { public class GenericLogger(Type type) { ... } } public class LoggerProvider : Provider<ILogger> { public override ILogger CreateInstance(IContext context) { return new GenericLogger(context.Target.Member.ReflectedType); } } ``` Then consuming types would work like this: ``` public class FooService : IFooService { public FooService(ILogger logger) { ... } } ```
If i'm not misunderstanding you, why not simply have your GericLogger Constructor take a parameter that is the type of the object. Then do this: ``` ILog = kernel.Get<ILog>(ParameterList); ``` I haven't read up completely yet on Ninject Parameter Lists, but it seems to be a way to inject a parameter type using an IParameterList. EDIT: Looks like this would work like this: ``` ILog = kernel.Get<ILog>(new ConstructorArgument[] { new ConstructorArgument("ClassName", this.GetType().Name) }) ``` Then you have your ILog ``` class GenericLogger : Ilog { GenericLogger(string ClassName) {}; } ``` I didn't test this, just what seems to be from the Ninject source (i'm looking at a recent Ninject2 tree) EDIT: You want to pass ConstructorArgument, not Parameter. Updated to reflect. This code Prints: "Called From Init" ``` class Init { public void Run() { StandardKernel kernel = new StandardKernel( new MyLoader() ); kernel.Get<Tester>( new ConstructorArgument[] { new ConstructorArgument( "ClassName", this.GetType().Name ) } ); } } public class Tester { public Tester(string ClassName) { Console.WriteLine("Called From {0}", ClassName); } } ``` EDIT: Another method which might be useful is to use The Bind().To().WithConstructorArgument() binding, which could be useful when used with either self-binding or with a .WhenInjectedInto() condition.
Using Ninject (or some other container) How can I find out the type that is requesting the service?
[ "", "c#", ".net", "inversion-of-control", "structuremap", "ninject", "" ]
I am using NuSOAP to try to consume a Web Service built in Java. I have this code so far: ``` <?php require_once('lib/nusoap.php'); $wsdl="http://localhost:8080/HelloWorldWS/sayHiService?WSDL"; $client=new nusoap_client($wsdl, 'wsdl'); $param='John';#array('name'=>'John'); echo $client->call('Hey', $param); unset($client); ?> ``` but when the web page gets loaded I get a blank page nothing not even in the code and I really don't know why. Am I doing something wrong?
although NuSOAP is a very common PHP SOAP library, it's main use in PHP4 applications I think. because PHP5 has a built-in SOAP extension that is faster (because it is a compiled extension). I also recommend using Zend Framework SOAP library. but I remember I wanted to use some web service (not written by me, implemented in Java) and none of these SOAP clients worked, but the NuSOAP. and I really could not figure out why. anyway, here is the thing that I did to use that web service back then: ``` $soapClient = new nusoap_client($wsdlFile, 'wsdl', '', '', '', ''); $soapClient->soap_defencoding = 'UTF-8'; $soapClient->debug_flag = false; $soapError = $soapClient->getError(); if (! empty($soapError)) { $errorMessage = 'Nusoap object creation failed: ' . $soapError; throw new Exception($errorMessage); } // calling verifyT method, using 2 parameters. $tResult = $soapClient->call( 'verifyT', array($param1, $param2) ); $soapError = $soapClient->getError(); if (! empty($soapError)) { $errorMessage = 'SOAP method invocation (verifyT) failed: ' . $soapError; throw new Exception($errorMessage); } if ($soapClient->fault) { $fault = "{$soapClient->faultcode}: {$soapClient->faultdetail} "; // handle fault situation } ```
Don't use NuSoap. PHP has had a [native soap client](http://www.php.net/soap) since version 5, which is far more stable, besides being faster. > .. when the web page gets loaded I get a blank page nothing not .. That's probably a fatal error. Try checking the error logs to see what went wrong. Or set [`display_errors = on`](http://www.php.net/manual/en/security.errors.php)
NuSOAP PHP Web Service
[ "", "php", "web-services", "" ]
Using a Jetty web server, started from maven, which includes iBatis, Spring, Jersey, a little of this and a little of that, I get logging output with a host of formats. Some are from maven: ``` [INFO] [war:war] [INFO] Exploding webapp... ``` Some are from Jetty: ``` 2009-03-25 21:01:27.781::INFO: jetty-6.1.15 2009-03-25 21:01:28.218:/example:INFO: Initializing Spring root WebApplicationContext ``` Some are from Spring: ``` INFO ContextLoader - Root WebApplicationContext: initialization started (189) INFO XmlBeanDefinitionReader - Loading XML bean definitions from ServletContext resource [/WEB-INF/applicationContext.xml] (323) ``` Some are from Jersey: ``` Mar 25, 2009 9:01:29 PM com.sun.jersey.spi.spring.container.SpringComponentProviderFactory register ``` still others are from my code: ``` INFO ExampleApp - [User@14ef239 ...stuff] (69) ``` I expect they're all using standard logging packages (log4j, commons-logging, java-logging...)- Is it possible, and what is the easiest way to configure all of them to use the same format?- Is there any benefit to leaving them in varying formats?
This is possible using the logback library and its bridges. It basically consists to remove any log4j commons or alike jars from the classpath, stick logback jar file and bridges jars for log4j and alike. Spring, jersey and maven will use the bridge factories to instantiate loggers which in turn will use logbak producing unified logging. Check <http://logback.qos.ch/> and <http://www.slf4j.org/legacy.html> The key are the bridges which link other log utilities with a single global logger.
The issue you have is that the applications are using different logging libraries. Jersey will use JUL, Spring will use commons-logging (which will in turn pick log4j if that's in your classpath), and Jetty uses its own logger. You can fix this by getting all your components to log through JUL. First you need to get log4j off your classpath. Use exclusions or other mechanisms to ensure that log4j is not included. This will prevent commons-logging from picking log4j over JUL and get Spring to log in the same format as Jersey. Next you'll need to configure Jetty to use commons-logging. You can find information about that on the [Maven Jetty Plugin documentation](http://docs.codehaus.org/display/JETTY/Maven+Jetty+Plugin "Maven Jetty Plugin document") page. If your application code is using log4j directly, you'll need to switch to either commons-logging or JUL. Maven I'm not so sure about, but it probably has a similar solution.
How do I unify logging formats from the java stack
[ "", "java", "logging", "formatting", "" ]
This has not happened to me before, but for some reason both the client and server side validation events are not being triggered: ``` <asp:TextBox ID="TextBoxDTownCity" runat="server" CssClass="contactfield" /> <asp:CustomValidator ID="CustomValidator2" runat="server" EnableClientScript="true" ErrorMessage="Delivery Town or City required" ClientValidationFunction="TextBoxDTownCityClient" ControlToValidate="TextBoxDTownCity" OnServerValidate="TextBoxDTownCity_Validate" Display="Dynamic" > </asp:CustomValidator> ``` Server-side validation event: ``` protected void TextBoxDTownCity_Validate(object source, ServerValidateEventArgs args) { args.IsValid = false; } ``` Client-side validation event: ``` function TextBoxDCountyClient(sender, args) { args.IsValid = false; alert("test"); } ``` I thought at the least the Server Side validation would fire but no. this has never happened to me before. This has really got me stumped. I looked at the output and ASP.NET is recognizing the client side function: ASP.NET JavaScript output: ``` var ctl00_ctl00_content_content_CustomValidator2 = document.all ? document.all["ctl00_ctl00_content_content_CustomValidator2"] : document.getElementById("ctl00_ctl00_content_content_CustomValidator2"); ctl00_ctl00_content_content_CustomValidator2.controltovalidate = "ctl00_ctl00_content_content_TextBoxDTownCity"; ctl00_ctl00_content_content_CustomValidator2.errormessage = "Delivery Town or City required"; ctl00_ctl00_content_content_CustomValidator2.display = "Dynamic"; ctl00_ctl00_content_content_CustomValidator2.evaluationfunction = "CustomValidatorEvaluateIsValid"; ctl00_ctl00_content_content_CustomValidator2.clientvalidationfunction = "TextBoxDTownCityClient"; ``` Rendered custom validator: ``` <span id="ctl00_ctl00_content_content_CustomValidator2" style="color:Red;display:none;">Delivery Town or City required</span> ``` Can any one shed some light as to why both client and server side validation would not be firing. **Edit: Typo I pasted in the wrong function, problem still the same** Just another update to the last comment: where by the TextBox cannot be empty. I tested this out and it is not true. On a blank page the CustomValidator fired my client side validation function fine without a value: ``` <asp:TextBox ID="TextBox1" runat="server" /> <asp:CustomValidator ID="CustomValidator1" runat="server" ErrorMessage="CustomValidator" ClientValidationFunction="TextBoxDAddress1Client"></asp:CustomValidator> <asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click" /> ```
Your `CustomValidator` will only fire when the `TextBox` isn't empty. If you need to ensure that it's not empty then you'll need a [`RequiredFieldValidator`](http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.requiredfieldvalidator.aspx) too. > [**Note:** If the input control is empty, > no validation functions are called and > validation succeeds. Use a > RequiredFieldValidator control to > require the user to enter data in the > input control.](http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.customvalidator.aspx) **EDIT:** If your `CustomValidator` specifies the `ControlToValidate` attribute (and your original example does) then your validation functions will only be called when the control isn't empty. If you don't specify `ControlToValidate` then your validation functions will be called every time. This opens up a second possible solution to the problem. Rather than using a separate `RequiredFieldValidator`, you could omit the `ControlToValidate` attribute from the `CustomValidator` and setup your validation functions to do something like this: Client Side code (Javascript): ``` function TextBoxDCountyClient(sender, args) { var v = document.getElementById('<%=TextBoxDTownCity.ClientID%>').value; if (v == '') { args.IsValid = false; // field is empty } else { // do your other validation tests here... } } ``` Server side code (C#): ``` protected void TextBoxDTownCity_Validate( object source, ServerValidateEventArgs args) { string v = TextBoxDTownCity.Text; if (v == string.Empty) { args.IsValid = false; // field is empty } else { // do your other validation tests here... } } ```
Use this: ``` <asp:CustomValidator runat="server" id="vld" ValidateEmptyText="true"/> ``` To validate an empty field. You don't need to add 2 validators !
ASP.NET Custom Validator Client side & Server Side validation not firing
[ "", "c#", ".net", "asp.net", "validation", "customvalidator", "" ]
I created a Java application which is the only application active on a workstation. (Similar to a kiosk system) The problem is that the application has to be up and running as fast as possible after starting the computer. I'm wondering **which one of the major operating systems can be configured to provide the shortest startup time?** I'm using 3rd party audio and graphics libraries so my choices are limited to Windows XP/Vista, Linux and Solaris. Currently on my dual-boot machine Fedora takes a little longer than Vista, but on the other hand I don't have much experience with tuning boot time of Linux. So if someone knows that Linux could have much better chances of a quick startup then I would put my time in there. I'd also appreciate general hints on tuning boot times and Java startup times.
If you're running your application inside of a kiosk like machine where you don't need any other applications running, and you know which drivers/modules you'll need to load ahead of time, I think your best boot time will come from Linux. It will just take some time to fine tune your boot process to load all the proper software in the fastest time possible.
I would look at [BootChart](http://www.bootchart.org/) to optimise your Fedora boot time. If you're running one app, then you can certainly remove a lot of the services that Fedora would normally come configured with. I would also point out that perhaps for the amount of time you're going to spend optimising this, you may be better off investing in the appropriate hardware (e.g. SSDS and similar, if boot time is governed by your disk). Optimising can be a major time sink.
Which one of the major operating systems is best suited for a quick boot and startup of a Java application?
[ "", "java", "windows", "linux", "operating-system", "solaris", "" ]
I get "Incorrect syntax" errors on every nested IF and ELSE statements in the following code... what's wrong ? ``` ALTER PROCEDURE [WTFAULT].[usp_WTFault_GetPartFaultStatus] ( @linxPartId int = -1, @faultStatus varchar(10) output ) AS BEGIN DECLARE @NbFaultsInParts int, @NbPartsReturned int SET @NbPartsReturned = (SELECT COUNT(*) FROM WTFAULT.PART, WTFAULT.FAULT WHERE WTFAULT.PART.FAULT_COID = WTFAULT.FAULT.COID AND WTFAULT.PART.LINX_PARTID = @linxPartId AND WTFAULT.FAULT.MATURITY = 'ALLOCATED') IF @NbPartsReturned > 0 BEGIN SET @faultStatus = 'ALLOCATED' END ELSE BEGIN SET @NbPartsReturned = (SELECT COUNT(*) FROM WTFAULT.PART, WTFAULT.FAULT WHERE WTFAULT.PART.FAULT_COID = WTFAULT.FAULT.COID AND WTFAULT.PART.LINX_PARTID = @linxPartId AND WTFAULT.FAULT.MATURITY = 'DRAFT') IF @NbPartsReturned > 0 BEGIN SET @faultStatus = 'DRAFT' END ELSE BEGIN SET @NbPartsReturned = (SELECT COUNT(*) FROM WTFAULT.PART, WTFAULT.FAULT WHERE WTFAULT.PART.FAULT_COID = WTFAULT.FAULT.COID AND WTFAULT.PART.LINX_PARTID = @linxPartId AND WTFAULT.FAULT.MATURITY = 'CLOSED') IF @NbPartsReturned > 0 BEGIN SET @faultStatus = 'CLOSED' END ELSE BEGIN SET @faultStatus = '' END END END END GO ```
Try this different method: ``` ALTER PROCEDURE [WTFAULT].[usp_WTFault_GetPartFaultStatus](@linxPartId int = -1, @faultStatus varchar(10) output) AS SELECT COUNT(*) as MaturityCount,WTFAULT.FAULT.MATURITY INTO #Temp FROM WTFAULT.PART JOIN WTFAULT.FAULT ON WTFAULT.PART.FAULT_COID = WTFAULT.FAULT.COID WHERE TFAULT.PART.LINX_PARTID = @linxPartId GROUP BY WTFAULT.FAULT.MATURITY If (select MaturityCount from #temp where WTFAULT.FAULT.MATURITY = 'ALLOCATED') >0 BEGIN SET @faultStatus = 'ALLOCATED' END ELSE IF (select MaturityCount from #temp where WTFAULT.FAULT.MATURITY = 'DRAFT') >0 BEGIN SET @faultStatus = 'DRAFT' END ELSE IF (select MaturityCount from #temp where WTFAULT.FAULT.MATURITY = 'CLOSED') >0 BEGIN SET @faultStatus = 'CLOSED' END ELSE BEGIN SET @faultStatus = '' END ``` I also changed your query to use ANSI standard joins. You should use them too from now on. They are clearer, easier to maintain and will not give wrong results when you use outer joins and are far less likely to result in a cross join by accident.
Try this: ``` DECLARE @faultStatus nvarchar(20) DECLARE @NbFaultsInParts int DECLARE @NbPartsReturned int SELECT @NbPartsReturned = COUNT(*) FROM WTFAULT.PART, WTFAULT.FAULT WHERE WTFAULT.PART.FAULT_COID = WTFAULT.FAULT.COID AND WTFAULT.PART.LINX_PARTID = @linxPartId AND WTFAULT.FAULT.MATURITY = 'ALLOCATED' IF @NbPartsReturned > 0 BEGIN SET @faultStatus = 'ALLOCATED' END ELSE BEGIN SELECT @NbPartsReturned = COUNT(*) FROM WTFAULT.PART, WTFAULT.FAULT WHERE WTFAULT.PART.FAULT_COID = WTFAULT.FAULT.COID AND WTFAULT.PART.LINX_PARTID = @linxPartId AND WTFAULT.FAULT.MATURITY = 'DRAFT' IF @NbPartsReturned > 0 BEGIN SET @faultStatus = 'DRAFT' END ELSE BEGIN SELECT @NbPartsReturned = COUNT(*) FROM WTFAULT.PART, WTFAULT.FAULT WHERE WTFAULT.PART.FAULT_COID = WTFAULT.FAULT.COID AND WTFAULT.PART.LINX_PARTID = @linxPartId AND WTFAULT.FAULT.MATURITY = 'CLOSED' IF @NbPartsReturned > 0 BEGIN SET @faultStatus = 'CLOSED' END ELSE BEGIN SET @faultStatus = '' END END END END GO ```
SQL Stored Procedure : Incorrect syntax within imbricated IFs
[ "", "sql", "stored-procedures", "syntax-error", "" ]
I got this question when I received a code review comment saying virtual functions need not be inline. I thought inline virtual functions could come in handy in scenarios where functions are called on objects directly. But the counter-argument came to my mind is -- why would one want to define virtual and then use objects to call methods? Is it best not to use inline virtual functions, since they're almost never expanded anyway? Code snippet I used for analysis: ``` class Temp { public: virtual ~Temp() { } virtual void myVirtualFunction() const { cout<<"Temp::myVirtualFunction"<<endl; } }; class TempDerived : public Temp { public: void myVirtualFunction() const { cout<<"TempDerived::myVirtualFunction"<<endl; } }; int main(void) { TempDerived aDerivedObj; //Compiler thinks it's safe to expand the virtual functions aDerivedObj.myVirtualFunction(); //type of object Temp points to is always known; //does compiler still expand virtual functions? //I doubt compiler would be this much intelligent! Temp* pTemp = &aDerivedObj; pTemp->myVirtualFunction(); return 0; } ```
Virtual functions can be inlined sometimes. An excerpt from the excellent [C++ faq](http://www.cs.technion.ac.il/users/yechiel/c++-faq/inline-virtuals.html): > "The only time an inline virtual call > can be inlined is when the compiler > knows the "exact class" of the object > which is the target of the virtual > function call. This can happen only > when the compiler has an actual object > rather than a pointer or reference to > an object. I.e., either with a local > object, a global/static object, or a > fully contained object inside a > composite."
C++11 has added `final`. This changes the accepted answer: it's no longer necessary to know the exact class of the object, it's sufficient to know the object has at least the class type in which the function was declared final: ``` class A { virtual void foo(); }; class B : public A { inline virtual void foo() final { } }; class C : public B { }; void bar(B const& b) { A const& a = b; // Allowed, every B is an A. a.foo(); // Call to B::foo() can be inlined, even if b is actually a class C. } ```
Are inline virtual functions really a non-sense?
[ "", "c++", "inline", "virtual-functions", "" ]
Please note that this question is intended to be a bit more on the theory side of the subject, but besides stripping whitespace what other techniques are used for [JavaScript Compression](http://compressorrater.thruhere.net/)?
Most of the compressors use a combination of different techniques: * stripping whitespaces * compress file by compression algorythm (gzip, deflate) * most of the space is saved renaming interall variables and function to shorter names, eg: This function: ``` function func (variable) { var temp = 2 * variable; return temp; } ``` will become: ``` function func (a) { var b = 2 * a; return b; } ``` * Dean Edwards [packer](http://dean.edwards.name/packer/) uses some internal compression. The script is decompressed whhen loaded on the page. * All the usual stuff to make a programmcode shorter: + delete unused code + function inlining
Off the top of my head... * Tokenizes local variables and then renames them to a minimally-sized variable. * Removes tons of whitespace. * Removes unnecessary braces (for example, single line executions after if-statements can remove braces and add a single semi-colon). * Removes unnecessary semi-colons (for example, right before an ending brace '}'). My most commonly used minifier is the [YUI Compressor](http://developer.yahoo.com/yui/compressor/), and [as they state](http://developer.yahoo.com/yui/compressor/#work), it's open source so you can take a look for yourself on exactly what they do. (I'm not sure what they mean by "micro-optimizations", probably a bunch of rare cases that gain you a character or two.)
What techniques do JavaScript compression libraries use to minimize file size?
[ "", "javascript", "optimization", "theory", "" ]
What's the best way to **externalize large quantities of HTML** in a GWT app? We have a rather complicated GWT app of about 30 "pages"; each page has a sort of guide at the bottom that is several paragraphs of HTML markup. I'd like to externalize the HTML so that it can remain as "unescaped" as possible. I know and understand how to use **property files** in GWT; that's certainly better than embedding the content in Java classes, but still kind of ugly for HTML (you need to backslashify everything, as well as escape quotes, etc.) **Normally this is the kind of thing you would put in a JSP**, but I don't see any equivalent to that in GWT. I'm considering just writing a widget that will simply fetch the content from html files on the server and then add the text to an HTML widget. But it seems there ought to be a simpler way.
You can use some templating mechanism. Try [FreeMarker](http://freemarker.org/) or [Velocity](http://velocity.apache.org/) templates. You'll be having your HTML in files that will be retrieved by templating libraries. These files can be named with proper extensions, e.g. .html, .css, .js obsearvable on their own.
I've used ClientBundle in a similar setting. I've created a package my.resources and put my HTML document and the following class there: ``` package my.resources; import com.google.gwt.core.client.GWT; import com.google.gwt.resources.client.ClientBundle; import com.google.gwt.resources.client.TextResource; public interface MyHtmlResources extends ClientBundle { public static final MyHtmlResources INSTANCE = GWT.create(MyHtmlResources.class); @Source("intro.html") public TextResource getIntroHtml(); } ``` Then I get the content of that file by calling the following from my GWT client code: ``` HTML htmlPanel = new HTML(); String html = MyHtmlResources.INSTANCE.getIntroHtml().getText(); htmlPanel.setHTML(html); ``` See <http://code.google.com/webtoolkit/doc/latest/DevGuideClientBundle.html> for further information.
best way to externalize HTML in GWT apps?
[ "", "java", "html", "gwt", "" ]
I want to give my users the option to use a textbox and press Enter. The challenge is that I have 5 textbox, and 2 options. 3 textbox belong to one button, and 2 textbox to the other. How do I trigger a particular Button according to the textbox the user was in when he press Enter?
I accomplished this on my own where I had a page with two different login forms for the different user types. What I did was separate the two forms into their own ASP Panel controls and on the panel setting the DefaultButton to whichever one I wished. That way when they finished typing in the form and hit the enter key, it would submit on the correct button. **Example**: ``` <asp:Panel id="panel1" DefaultButton="button1"> <asp:textbox id="textbox1"/> <asp:textbox id="textbox2"/> <asp:buton id="button1"/> </asp:panel> <asp:panel id="panel2" DefaultButton="button2"> <asp:textbox id="textbox3"/> <asp:textbox id="textbox4"/> <asp:button id="button2"/> </asp:panel> ``` **EDIT**: Here is [another method](http://weblogs.asp.net/rajbk/archive/2003/12/11/setting-the-default-button-for-a-textbox-in-asp-net.aspx) of how to do it by assigning an OnKeyPress property to your textboxes. **THIS IS A SEPARATE SOLUTION THAN THAT WHICH I DESCRIBED AT THE TOP** **Example**: ``` function clickButton(e, buttonid){ var evt = e ? e : window.event; var bt = document.getElementById(buttonid); if (bt){ if (evt.keyCode == 13){ bt.click(); return false; } } } //code behind TextBox1.Attributes.Add("onkeypress", "return clickButton(event,'" + Button1.ClientID + "')"); ``` The code behind generates the following code: ``` <input name="TextBox1" type="text" id="TextBox1" onkeypress="return clickButton(event,'Button1')" /> ```
In this situation I would group the related textboxes and the button in a Panel. Panel has a DefaultButton property you can use. DefaultButton="IdOfTheDefaultButtonForControlsInThisPanel" <http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.panel.defaultbutton.aspx>
5 Textbox, 2 Buttons. How to assign textBox to Button?
[ "", "c#", ".net", "asp.net", "" ]
I need to implement read-only access to a private member container. If I return a constant reference is it possible to const\_cast it and obtain a full access to the member? What's the technique to be used? Thanks.
Returning a const & is a sensible thing to do in many circumstances, particularly if the object being returned is large or cannot be copied. Regarding the const\_cast, remember the "private" access specifier in C++ is there as an aid to the programmer - it is not intended to be a security measure. If someone wants access to an object's private members, it can get them, no matter what you try to do to prevent it.
## Is it safe to return a const reference to a private member Yes as long as the lifetime of the reference does not exceed the lifetime of the object which returned it. If you must expose the private member you do not want modified, this is a good way to do so. It's not foolproof but it's one of the better ways to do so in C++ ## Is it possible to use const\_cast to actually mess around with member Yes and there is nothing you can do to prevent this. There is no way to prevent someone from casting away const in C++ at any time. It's a limitation / feature of C++. In general though, you should flag every use of const\_cast as a bug unless it contains a sufficiently detailed comment as to why it's necessary.
Is it OK to return a const reference to a private member?
[ "", "c++", "reference", "constants", "" ]
I'd like to configure the Windsor container so that a single, singleton-style instance can provide two or more services through the container. I've found that using the same type in multiple component declarations (XML-based config) will result in an instance of that type being created to provide each component's service interface, which is not the behaviour I desire. For example: ``` interface IA { } interface IB { } class AB : IA, IB { ... } ``` I want the one instance of AB to provide both the IA and IB services. The specific reason I want to do this is that my concrete DAO implementation extends multiple interfaces. On the flip side, I have several worker components which hold a reference to different interfaces. The concrete DAO instance respects this, but the constructors of these seperate worker components want the implementation of their seperate interfaces and I desire Castle.Windsor to pass the same object instance through to these worker containers via the respective service requests. lol, I think that was clear as mud! :P Does anyone understand what I mean, and has anyone got any ideas how I can acheive this through the XML configuration fo the components?
Have you checked out the answer to [this question](https://stackoverflow.com/questions/483515/how-does-castle-windsor-respond-to-a-class-which-implements-multiple-interfaces) (especially the forum post link) that appears to be what you are looking for. Some of the examples are using the Transient lifecycle but I think it will work with Singleton also. The main pay-off of the [forum post](http://forum.castleproject.org/viewtopic.php?p=14725&sid=f94e87a29e0f4b3c65c62ccd67a064b7) is: ``` container.Register(Component.For<IEntityIndexController, ISnippetController>() .ImplementedBy<SnippetController>() .LifeStyle.Transient); ``` The solution is uses the fluent interface (and a recent trunk build) and it wasn't possible to configure in xml last I saw. However, it [may be possible](https://stackoverflow.com/questions/274220/does-castle-windsor-support-forwardedtypes-via-xml-configuration) with a facility. Good luck!
Have you tried using the `Forward` method: ``` container.Register(Component.For<IEntityIndexController>() .ImplementedBy<SnippetController>() .Forward (typeof(ISnippetController)) .LifeStyle.Transient); ``` From my experiments and from the documentation: > register the service types on behalf of this component i think it shoud do the trick.
How do I configure a single component instance providing multiple services in Castle.Windsor?
[ "", "c#", "inversion-of-control", "castle-windsor", "" ]
I want to replicate the look and feel of Spybot Search & Destroy in my own applications. Is there a publicly-available framework, toolkit, or library to aid in this task?
AFAICR it's written in Delphi. With C++ Builder you can use Delphi libraries from C++.
In this blog post, they mention that they use Delphi: <http://www.safer-networking.org/en/news/2005-06-22.html>
Which GUI framework is used by the "Spybot Search & Destroy" application?
[ "", "c++", "" ]
I seem to remember that in PHP there is a way to pass an array as a list of arguments for a function, dereferencing the array into the standard `func($arg1, $arg2)` manner. But now I'm lost on how to do it. I recall the manner of passing by reference, how to "glob" incoming parameters ... but not how to de-list the array into a list of arguments. It may be as simple as `func(&$myArgs)`, but I'm pretty sure that isn't it. But, sadly, the php.net manual hasn't divulged anything so far. Not that I've had to use this particular feature for the last year or so.
**Note: this solution is outdated, please refer to [the answer by simonhamp](https://stackoverflow.com/questions/744145/passing-an-array-as-arguments-not-an-array-in-php#34049110) for newer information.** <http://www.php.net/manual/en/function.call-user-func-array.php> ``` call_user_func_array('func',$myArgs); ```
[As has been mentioned](https://stackoverflow.com/questions/744145/passing-an-array-as-arguments-not-an-array-in-php/34049110#comment37967053_744178), as of PHP 5.6+ you can (should!) use the `...` token (aka "splat operator", part of the [variadic functions](http://php.net/manual/en/functions.arguments.php#functions.variable-arg-list) functionality) to easily call a function with an array of arguments: ``` function variadic($arg1, $arg2) { // Do stuff echo $arg1.' '.$arg2; } $array = ['Hello', 'World']; // 'Splat' the $array in the function call variadic(...$array); // => 'Hello World' ``` NB: *Indexed* array items are mapped to arguments by their **position** in the array, not their keys. **As of PHP8, and [thanks to named arguments](https://stitcher.io/blog/php-8-named-arguments), it's possible to use the named keys of an *associative* array with unpacking:** ``` $array = [ 'arg2' => 'Hello', 'arg1' => 'World' ]; variadic(...$array); // => 'World Hello' ``` (Thanks to [mickmackusa](https://stackoverflow.com/questions/744145/passing-an-array-as-arguments-not-an-array-in-php/34049110?noredirect=1#comment134333933_34049110) for this note!) As per [CarlosCarucce's comment](https://stackoverflow.com/questions/744145/passing-an-array-as-arguments-not-an-array-in-php/34049110#comment65680057_34049110), this form of argument unpacking **is the fastest method by far** in all cases. In some comparisons, it's over 5x faster than `call_user_func_array`. ## Aside Because I think this is really useful (though not directly related to the question): you can [type-hint the splat operator parameter](http://php.net/manual/en/functions.arguments.php#example-151) in your function definition to make sure all of the passed values match a specific type. (Just remember that doing this it **MUST** be the *last* parameter you define and that it bundles all parameters passed to the function into the array.) This is great for making sure an array contains items of a specific type: ``` // Define the function... function variadic($var, SomeClass ...$items) { // $items will be an array of objects of type `SomeClass` } // Then you can call... variadic('Hello', new SomeClass, new SomeClass); // or even splat both ways $items = [ new SomeClass, new SomeClass, ]; variadic('Hello', ...$items); ```
Passing an Array as Arguments, not an Array, in PHP
[ "", "php", "arrays", "function", "arguments", "parameter-passing", "" ]
Is there a module written purely in Python that will allow a script to communicate with a MySQL database? I've already tried MySQLdb without success. It requires too much: GCC, zlib, and openssl. I do not have access to these tools; even if I did, I don't want to waste time getting them to work together. I'm looking for tools that will make my work easier. Can someone point me in the direction of a MySQL Python module written in Python? If not, tips on writing my own code for communicating with MySQL would be appreciated. Thanks, Tony --- Thanks everyone for your answers. Since I'm working with a small database (a few hundred records, mainly names and addresses) I've decided to use SQLite. I just discovered it. It seems to be perfectly suited for my purposes; it was simple to install (took about two minutes) and works well with Python. I'm stuck with Python 2.4 so I can't use the sqlite3 module, but I'm able to communicate with the database by using Python's 'subprocess.Popen' function and command-line parameters.
Oracle implemented a pure python mysql connector, aptly named [mysql-connector-python](https://github.com/mysql/mysql-connector-python). It can be pip-installed and receives plenty of updates. Note that it's GPL licensed, which may or may not be a problem for your prjoect. If you can't live with that, you can also pick up [PyMySQL](https://pypi.org/project/PyMySQL/) instead which is one of the few connectors that works well and is distributed under MIT.
You've looked at these? <http://wiki.python.org/moin/MySQL>
Python and MySQL: is there an alternative to MySQLdb?
[ "", "python", "mysql", "database", "" ]
In my C++ `main` function, for example, if I had a pointer to a variable which uses heap memory (as opposed to stack memory) - is this automatically deallocated after my application exits? I would assume so. Even so, is it good practice to always delete heap allocations even if you think they will never be used in a situation where the memory is automatically deallocated on exit? For example, is there any point in doing this? ``` int main(...) { A* a = new A(); a->DoSomething(); delete a; return 0; } ``` I was thinking *maybe* in case I refactor (or someone else refactors) that code and puts it elsewhere in the application, where `delete` is really necessary. As well as the answer by Brian R. Bondy (which talks specifically about the implications in C++), Paul Tomblin also has a [good answer to a C specific question](https://stackoverflow.com/questions/654754/what-really-happens-when-you-dont-free-after-malloc/654766#654766), which also talks about the C++ destructor.
It is important to explicitly call delete because you may have some code in the destructor that you want to execute. Like maybe writing some data to a log file. If you let the OS free your memory for you, your code in your destructor will not be executed. Most operating systems will deallocate the memory when your program ends. But it is good practice to deallocate it yourself and like I said above the OS won't call your destructor. As for calling delete in general, yes you always want to call delete, or else you will have a memory leak in your program, which will lead to new allocations failing.
Yes, it helps to eliminate false positives when you run your program through a memory leak detection tool.
Is there a reason to call delete in C++ when a program is exiting anyway?
[ "", "c++", "memory-management", "dynamic", "heap-memory", "" ]
I have a WCF Service and an application with a Service Reference to it, and with the application I have a loop and in each iteration it's making a call to a method in this wcf web-service. The problem is that after about 9 calls or so, it just stops...and if you hit `Pause` button of VS, you will see that it's stuck on the line where it makes the call. After some time waiting for it, this **TimeoutException** is thrown: > The request channel timed out while > waiting for a reply after > 00:00:59.9970000. Increase the timeout > value passed to the call to Request or > increase the SendTimeout value on the > Binding. The time allotted to this > operation may have been a portion of a > longer timeout. --- I researched a bit on this, and found some solutions that involved editing the app.config in the application, and here are excerpts of it: ``` <serviceBehaviors> <behavior name="ThrottlingIssue"> <serviceThrottling maxConcurrentCalls="500" maxConcurrentSessions="500" /> </behavior> </serviceBehaviors> ``` . ``` <readerQuotas maxDepth="2147483647" maxStringContentLength="2147483647" maxArrayLength="2147483647" maxBytesPerRead="2147483647" maxNameTableCharCount="2147483647" /> ``` Then, after I stop debugging, after a couple of minutes, an error message pops up telling me that a **Catastrophic failure** has occurred. How can I fix this problem? I did not have this issue when I was working with a normal Web Service. --- For reference, here is the whole `app.config`: ``` <?xml version="1.0" encoding="utf-8" ?> <configuration> <system.serviceModel> <behaviors> <serviceBehaviors> <behavior name="ThrottlingIssue"> <serviceThrottling maxConcurrentCalls="500" maxConcurrentSessions="500" /> </behavior> </serviceBehaviors> </behaviors> <bindings> <wsHttpBinding> <binding name="WSHttpBinding_IDBInteractionGateway" closeTimeout="00:01:00" openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00" bypassProxyOnLocal="false" transactionFlow="false" hostNameComparisonMode="StrongWildcard" maxBufferPoolSize="524288" maxReceivedMessageSize="65536" messageEncoding="Text" textEncoding="utf-8" useDefaultWebProxy="true" allowCookies="false"> <readerQuotas maxDepth="2147483647" maxStringContentLength="2147483647" maxArrayLength="2147483647" maxBytesPerRead="2147483647" maxNameTableCharCount="2147483647" /> <reliableSession ordered="true" inactivityTimeout="00:10:00" enabled="false" /> <security mode="Message"> <transport clientCredentialType="Windows" proxyCredentialType="None" realm="" /> <message clientCredentialType="Windows" negotiateServiceCredential="true" algorithmSuite="Default" establishSecurityContext="true" /> </security> </binding> </wsHttpBinding> </bindings> <client> <endpoint address="http://localhost:28918/DBInteractionGateway.svc" binding="wsHttpBinding" bindingConfiguration="WSHttpBinding_IDBInteractionGateway" contract="DBInteraction.IDBInteractionGateway" name="WSHttpBinding_IDBInteractionGateway"> <identity> <dns value="localhost" /> </identity> </endpoint> </client> </system.serviceModel> </configuration> ``` --- **[Update] Solution:** Apparently, **after each request you have to `Close` the connection**...I am now closing the connection after each request and it's working like a charm. *Although what I still can't understand is that in my app.config, I set my maxConcurrentCalls and maxConcurrentSessions to 500, and yet, I can only make 10. Anyone has any answer for that one? (maybe I have something wrong in my app.config posted above)* The answer for the above question (now dashed) is because I was editing the client `app.config`, not the service config file (`web.config`)
The default number of allowed concurrent connections is 10. Most likely your client is not closing the connections. To increase the number of concurrent calls, you will have to add your behavior to the service configuration, not the client.
A call to clientservice.close() will solve the problem.
WCF stops responding after about 10 or so calls (throttling)
[ "", "c#", "wcf", "web-services", "throttling", "" ]
I'm currently writing an app in Python and need to provide localization for it. I can use gettext and the utilities that come with it to generate .po and .mo files. But editing the .po files for each language, one-by-one, seems a bit tedious. Then, creating directories for each language and generating the .mo files, one-by-one, seems like overkill. The end result being something like: ``` /en_US/LC_MESSAGES/en_US.mo /en_CA/LC_MESSAGES/en_CA.mo etc. ``` I could be wrong, but it seems like there's got to be a better way to do this. Does anyone have any tools, tricks or general knowledge that I haven't found yet? Thanks in advance! EDIT: To be a little more clear, I'm looking for something that speeds up the process. since it's already pretty easy. For example, in .NET, I can generate all of the strings that need to be translated into an excel file. Then, translators can fill out the excel file and add columns for each language. Then, I can use xls2resx to generate the language resource files. Is there anything like that for gettext? I realize I could write a script to create and read from a csv and generate the files -- I was just hoping there is something already made.
I've just done this for a project I'm working on, for us the process is like this: First, I have a POTFILES.in file which contains a list of source files needing translation. We actually have two files (e.g. admin.in and user.in), as the admin interface doesn't always need translating. So we can send translators only the file containing strings the users see. Running the following command will create a .pot template from the POTFILES.in: ``` xgettext --files-from=POTFILES.in --directory=.. --output=messages.pot ``` Run the above command from the po/ directory, which should be a subdirectory of your project and contain the POTFILES.in file. The .pot file has the exact same format as a .po file, but it is a template containing no translations. You create a new template whenever new translatable strings have been added to your source files. To update the already translated .po files and add new strings to them, run: ``` msgmerge --update --no-fuzzy-matching --backup=off da.po messages.pot ``` In the above example I disable fuzzy matching, as our strings are a mess and it did more harm than good. I also disabled backup files, as everything is in subversion here. Run the above command for each language, in this case I updated the danish translation. Finally run msgfmt to create the .mo files from the .po files: ``` msgfmt nl.po --output-file nl.mo ``` Ofcourse, you wouldn't want to run this manually everytime, so create some scripts (or preferably one or more Makefiles) to do this for you. Note that your directory layout is slightly different from my situation, so you will have to adjust output filenames/paths a bit, but the steps should be the same.
You can use [Transifex](https://www.transifex.com/), used by quite a few Python projects (Django, Mercurial). It has a web-based editor and command-line client for automation and also supports .NET, if that can be of help. Disclaimer: I'm the Transifex project lead.
Easiest way to generate localization files
[ "", "python", "localization", "internationalization", "translation", "" ]
What are the pros and cons in using the either for achieving a given task. The million dollar question is which one to use and when? Many Thanks.
I use to associate BackgroundWorker as a wrapper for what Threads would do. So I use BackgroundWorker on GUI works, and Threads on more specialized or dirty jobs (Windows Services, etc)
If by "Threads" you mean explicitly using the System.Threading.Thread class to create, configure and kick off your own threads, then the answer is that doing this is more work on your part, involves more cpu cycles than just pulling a thread from the thread pool, (wjhich is what the other techniques do), but it gives you more flexibility, as it allows you to specify thread priority, and several other characteristics that using Thread Pool threads does not afford you. The "Thread Pool" approach is more appropriate when the number of threads required is not known at design time. The pool initially contains a small number of threads, “ready” for you to call upon them. It can dynamically create new threads on demand, and it manages creation, coordination, and deletion of unused threads for you. There are three mechanisms you can use to access and use threads from the pool. 1. Using Delegate.BeginInvoke() (the most common technique) 2. Using timers (several variations) 3. System.Threading.ThreadPool provides several other features (BackGroundWorker class, QueueUserWorkItem(), etc.).
BackgroundWorker and Threads
[ "", "c#", "multithreading", "backgroundworker", "" ]
What is the best approach for serializing java object graphs? My requirements for serialization library are 1) speed of deserialization 2) size - as small as possible (smaller than in java default serialization) 3) flexibility - annotation based definitions of what has to be serialized would be nice. the underlying file format is not important. I looked at Protocol Buffers and XStream, but the former is not flexible enough due to the need for mapping files and the later produces big files. Any help appreciated.
For serialization Hessian is one of the most efficient. This is about 2-3 times smaller and faster than Java Serialization, even using Externalizable classes. Whichever serialization you use, you can use compression fairly easily to make the data more compact. Beyond that you can write your own serialization. I wrote a serializer which writes to/from ByteBuffer which is about twice as fast and half the size of Hessian (about 5x faster/smaller than Java Serialization) This may be too much effort for little gain if existing serializations will do what you need. However it is as customizable as you like ;)
For small objects, the Java serialised form is likely to be dominated by the description of the serialised classes. You may be able to write out serialised data for commonly used classes, and then use that as a common prefix for a series of serialised streams. Note that this is very fragile, and you'll probably want to recompute and check it for each class loader instance.
efficient java object graph serialization
[ "", "java", "serialization", "" ]
I am trying to find a way to get the list of method calls inside a lambda expression in C# 3.5. For instance, in the code below, I would like to method LookAtThis(Action a) to analyze the content of the lambda expression. In other words, I want LookAtThis to return me the MethodInfo object of Create. ``` LookAtThis(() => Create(null, 0)); ``` Is it possible? Thanks!
This is fairly easy as long as you use `Expression<Action>` instead of `Action`. For full code, including how to get the actual values implied, [see here](http://code.google.com/p/protobuf-net/source/browse/trunk/protobuf-net.Extensions/ServiceModel/Client/ProtoClientExtensions.cs) - in particular `ResolveMethod` (and how it is used by `Invoke`). This is the code I use in protobuf-net to do RPC based on lambdas.
``` using System; using System.Linq; using System.Diagnostics; using System.Reflection; using System.Linq.Expressions; class Program { static void Create(object o, int n) { Debug.Print("Create!"); } static void LookAtThis(Expression expression) { //inspect: MethodInfo method = ((MethodCallExpression)expression.Body).Method; Debug.Print("Method = '{0}'", method.Name); //execute: Action action = expression.Compile(); action(); } static void Main(string[] args) { LookAtThis((Expression)(() => Create(null, 0))); } } ```
Reflection - Get the list of method calls inside a lambda expression
[ "", "c#", ".net", "reflection", "" ]
I'm not sure how to write this query in SQL. there are two tables ``` **GroupRecords** Id (int, primary key) Name (nvarchar) SchoolYear (datetime) RecordDate (datetime) IsUpdate (bit) **People** Id (int, primary key) GroupRecordsId (int, foreign key to GroupRecords.Id) Name (nvarchar) Bio (nvarchar) Location (nvarchar) ``` return a distinct list of people who belong to GroupRecords that have a SchoolYear of '2000'. In the returned list, people.name should be unique (no duplicate People.Name), in case of a duplication only the person who belong to the GroupRecords with the later RecordDate should be returned. It would probably be better to write a stored procedure for this right?
This is untested, but it should do what is required in the question. It selects all details about the person. The subquery will make it match only the latest RecordDate for a single name. It will also look only in the right GroupRecord because of the Match between the ids. ``` SELECT People.Id, People.GroupRecordsId, People.Name, People.Group, People.Bio, People.Location FROM People INNER JOIN GroupRecords ON GroupRecords.Id = People.GroupRecordsId WHERE GroupRecords.SchoolYear = '2000/1/1' AND GroupRecords.RecordDate = ( SELECT MAX(GR2.RecordDate) FROM People AS P2 INNER JOIN GroupRecords AS GR2 ON P2.GroupRecordsId = GR2.Id WHERE P2.Name = People.Name AND GR2.Id = GroupRecords.Id ) ```
``` Select Distinct ID From People Where GroupRecordsID In (Select Id From GroupRecords Where SchoolYear = '2000/1/1') ``` This will produce a distinct list of those individuals in the 2000 class... but I don't understand what you're getting at with the cpmment about duplicates... please elaborate... It reads as though you're talking about when two different people happen to have the same name you don't want them both listed... Is that really what you want?
complex sql query help needed
[ "", "sql", "" ]
I'm learning C# coming from C++ and have run into a wall. I have an abstract class AbstractWidget, an interface IDoesCoolThings, and a class which derives from AbstractWidget called RealWidget: ``` public interface IDoesCoolThings { void DoCool(); } public abstract class AbstractWidget : IDoesCoolThings { void IDoesCoolThings.DoCool() { Console.Write("I did something cool."); } } public class RealWidget : AbstractWidget { } ``` When I instantiate a RealWidget object and call DoCool() on it, the compiler gives me an error saying > 'RealWidget' does not contain a > definition for 'DoCool' I can cast RealWidget object to an IDoesCoolThings and then the call will work, but that seems unnecessary and I also lose polymorphism (AbstractWidget.DoCool() will always be called even if i define RealWidget.DoCool()). I imagine the solution is simple, but I've tried a variety of things and for the life of me can't figure this one out.
You're running into the issue because you used **[*explicit interface implementation*](http://msdn.microsoft.com/en-us/library/aa288461(VS.71).aspx)** (EII). When a member is explicitly implemented, it can't be accessed through a class instance -- only through an instance of the interface. In your example, that's why you can't call `DoCool()` unless you cast your instance to `IDoesCoolThings`. The solution is to make `DoCool()` public and remove the explicit interface implementation: ``` public abstract class AbstractWidget : IDoesCoolThings { public void DoCool() // DoCool() is part of the abstract class implementation. { Console.Write("I did something cool."); } } // ... var rw = new RealWidget(); rw.DoCool(); // Works! ``` In general, you use EII in two cases: * You have a class that must implement two interfaces, each of which contains a member that has an identical name/signature to another member in the other interface. * You want to *force* clients not to depend on the implementation details of your class, but rather on the interface that's being implemented by your class. (This is considered a good practice by some.)
Change your declaration to: ``` public abstract class AbstractWidget : IDoesCoolThings { public void DoCool() { Console.Write("I did something cool."); } } ```
Using interfaces on abstract classes in C#
[ "", "c#", "inheritance", "interface", "abstract-class", "" ]
I am trying to json\_encode an array which is returned from a Zend\_DB query. var\_dump gives: (Manually adding 0 member does not change the picture.) ``` array(3) { [1]=> array(3) { ["comment_id"]=> string(1) "1" ["erasable"]=> string(1) "1" ["comment"]=> string(6) "test 1" } [2]=> array(3) { ["comment_id"]=> string(1) "2" ["erasable"]=> string(1) "1" ["comment"]=> string(6) "test 1" } [3]=> array(3) { ["comment_id"]=> string(1) "3" ["erasable"]=> string(1) "1" ["comment"]=> string(6) "jhghjg" } } ``` The encoded string looks like: ``` {"1":{"comment_id":"1","erasable":"1","comment":"test 1"}, "2":{"comment_id":"2","erasable":"1","comment":"test 1"}, "3":{"comment_id":"3","erasable":"1","comment":"jhghjg"}} ``` What I need is: ``` [{"comment_id":"1","erasable":"1","comment":"test 1"}, {"comment_id":"2","erasable":"1","comment":"test 1"}, {"comment_id":"3","erasable":"1","comment":"jhghjg"}] ``` Which is what the php.ini/json\_encode documentation says it should look like.
How are you setting up your initial array? If you set it up like: ``` array( "1" => array(...), "2" => array(...), ); ``` then you don't have an array with numeric indexes but strings, and that's converted to an object in JS world. This can happen also if you don't set a strict order (i.e. starting at 0 instead of 1). This is a shot in the dark, however, because I can't see your original code: try setting your array without using keys at all in the first place: ``` array( array(...), array(...), ); ```
Added information that expands on [Seb](https://stackoverflow.com/questions/684262/encode-array-to-json-in-php-to-get-elm1-elm2-elm3-instead-of-elm1-elm2-e/684299#684299)'s answer. ``` php > print json_encode( array( 'a', 'b', 'c' ) ) ; ["a","b","c"] php > print json_encode( array( 0 => 'a', 1 => 'b', 2 => 'c' ) ) ; ["a","b","c"] php > print json_encode( array( 1 => 'a', 2 => 'b', 3 => 'c' ) ) ; {"1":"a","2":"b","3":"c"} php > ``` Note: its formatting it this way with good cause: If you were to send ``` {"1":"a","2":"b","3":"c"} ``` as ``` ["a","b","c"] ``` When you did `$data[1]` in Php you would get back "a", but on the JavaScript side, you would get back "b" .
How do I encode a PHP array to a JSON array, not object?
[ "", "php", "zend-framework", "json", "" ]
I am a fairly junior programmer and have the task of interviewing an experienced mainframe COBOL programmer for a position doing C++ development for Windows Mobile. By experienced I mean that the candidate's entire programming career has been COBOL. I am not biased against any particular language, just slightly concerned about my ability to do a thorough interview. Inside of an interview how can I, with no COBOL experience, get a good feel for the abilities of this interviewee? Are there any specific things I should ask or look for? I have already read up on a lot of general interview stuff on SO, what would be helpful are any specific things I look for given the nature of the candidate's background.
The best thing is, give him a task, similar to what he will have to do at your company. Tell him he can use pseudo code (So no Internet is needed). Also, The main problem Cobol people have is to grasp OO (Since Cobol is mostly procedural...I am aware of new OO versions). One more pitfall Cobol people have is grasping the scope concept, As traditional Cobol each variable live from start to bottom of the app he is in.
If this person is a good programmer at all, he/she have had experience with other languages. (Speaking as an old fart who started with COBOL and even worse RPG/II.) Even if this person have never had a job with anything else. Here are some things you might ask: * "How did you get started with computers?" * "Do you do any programming for fun?" * "Why do you want to move to a C++ environment?" (This is an especially good question because good COBOL programmers are actually hard to find now. I'll bet this person wants to learn something new.) * "Have you done any assembly language programming?" (Odds are much better they'll take to C/C++ quickly if they are comfortable with the machine.) * "Can you describe what 'object oriented programming' means?" (Keys: look for a description of what "objects" are, "inheritance", and "polymorphism". If that works out, ask when they'd use inheritance vs aggregation, ie, "is a" relations vs "has a" relations.) * "Do you have a Windows computer at home ~~or do you have a real computer~~?" If they claim any C++ knowledge, a really good set of screening questions are: * "What is the difference between a *declaration* and a *definition* in C?" * "What are the differences among 'private', 'protected' and 'public' declarations in a class?" * "What is a 'friend'?" (Extra credit if they know to say that "In C++ only your friends can access your private parts.") * "What is a virtual member function?" * "What is 'virtual inheritance'?"
Transiting from COBOL to C++
[ "", "c++", "cobol", "" ]
I found myself needing this function, and was wondering if it exists in PHP already. ``` /** * Truncates $str and returns it with $ending on the end, if $str is longer * than $limit characters * * @param string $str * @param int $length * @param string $ending * @return string */ function truncate_string($str, $length, $ending = "...") { if (strlen($str) <= $length) { return $str; } return substr($str, 0, $length - strlen($ending)).$ending; } ``` So if the limit is 40 and the string is "The quick fox jumped over the lazy brown dog", the output would be "The quick fox jumped over the lazy brow...". It seems like the sort of thing that would exist in PHP, so I was surprised when I couldn't find it.
No it does not exist. Many libraries provide it however as you're not the first to need it. e.g. Smarty
``` $suffix = '...'; $maxLength = 40; if(strlen($str) > $maxLength){ $str = substr_replace($str, $suffix, $maxLength); } ``` Your implementation may vary slightly depending on whether the suffix's length should be count towards the total string length.
Does this function exist in PHP?
[ "", "php", "string", "" ]
Running Fedora 9/10, Apache 2, PHP 5... Can I run a shell script as root, from a PHP script using exec()? Do I just give Apache root priveleges, and then add "sudo" in front of them command? Specifically, I'm trying to start and stop a background script. Currently I have a shell script that just runs the app, start.sh: ``` #!/bin/bash /path/to/my/app/appname ``` And a script that kills the app, stop.sh: ``` #!/bin/bash killall appname ``` Would I just do: ``` <?php exec("sudo start.sh"); ?> ``` Thanks in advance.
You can't just sudo like that, you need to setup passwordless sudo first in /etc/sudoers file. This can be done with visudo command for example. Make sure you set up privileges in sudoers file in such way to constrain the apache user to that single command you wish to run (i.e. your shell script). Even then, it poses a security risk, because anyone could create a PHP script and run your shell script in turn. So make sure that shell script itself is secure from alteration by Apache user. The second part, *killall*, is even more problematic. You shouldn't just allow Apache to run killall with root privileges. You should wrap killall in another shell script and grant access to that in sudoers. In the end: do not run Apache with root account and do not use setuid. Both open a can of worms, and since you are a newbie (given the question you asked) you are very likely to miss some of small details that would create potential problems.
1. Don't run Apache as `root`. Apache has been designed to cope very well with starting as `root` and then dropping its privileges just as soon as it can 2. Don't use `sudo` within your script either - it'll be too easy to end up with `sudo` misconfigured such that any script running on your server gets to run any program it likes with `root` privileges 3. Look at making your own program run "setuid", so that it gets root privileges, but then drops them (just like Apache does) when it doesn't need them any more 4. Make sure your "setuid" executable can't be run by anybody who isn't supposed to be able to run it.
How can I have a PHP script run a shell script as root?
[ "", "php", "scripting", "permissions", "shell", "sudo", "" ]
I know when Leopard came out everybody (well, everybody that was a Java developer and cared enough to do development on a Mac) was pissed that there was no Java 6 SDK support. I know somebody provided some kind of hack way a few months after Leopard was released, but I could have sworn that I read sometime later that Apple and/or Sun finally put out an official version of the Java 6 SDK. So now a year and a half later I am finally interested in doing some Java dev on the Mac (thank Google App Kit for that). But when I go to Apple's Java site... all I see is stuff about Java 5. So, can I do Java 6 on a Mac? **See also**: [Installing Java 6 on Mac OS](https://stackoverflow.com/questions/607945)
Yes, JDK6 is available. However, some versions of Eclipse do not support it. There is a new one (based on Cocoa) that should but it is not officially available.
Yes, JDK6 is available, and it is quite nice, for example it supports DTrace, which otherwise you only get on Solaris. The main drawback is that Apple is very aggressive in deprecating older hardware (and OS versions). Java6 will never be released for Mac versions before 10.5, and only works on 64bit Intel. That also kills native 32 bit libraries, such as SWT/Carbon, which is what Eclipse uses (they need to move to Cocoa now). *Update:* Snow Leopard [apparently has Java6 for 32bit Intel](https://superuser.com/questions/31526/does-snow-leopard-provide-java-6-for-32-bit-machines), too (in addition to 64bit).
Can I do Java 6 development in OS X?
[ "", "java", "macos", "" ]
I would like to find what people got the most out of using WPF, in particular: * The best and stunning UI examples out there * Dark corners that no other UI can implement with ease and style (say MFC or GTK) * Professional examples with code Suggestions? Probably the best book on the subject is [WPF in Action with Visual Studio 2008](http://manning.com/feldman2/)
see: <http://windowsclient.net/> especially: [HealtCare demo](http://windowsclient.net/downloads/folders/wpfsamples/entry3754.aspx)
Here's some of my favorites: * [Family.Show](http://www.vertigo.com/familyshow.aspx) - An genealogy application (with code) [![Family.Show](https://i.stack.imgur.com/gwNja.png)](https://i.stack.imgur.com/gwNja.png) (source: [blogcasts.de](http://blogcasts.de/dwalzen/blog/FamilyShow.png)) * [PhotoSuru](http://www.photosuru.com/) - A photo browser (with code) [![PhotoSuru](https://i.stack.imgur.com/RN31u.jpg)](https://i.stack.imgur.com/RN31u.jpg) (source: [photosuru.com](http://www.photosuru.com/default_files/image002.jpg)) * [Eikos Partners Products](http://72.32.149.120/index.html) - Just screenshots, but looks really nice [EP Trading http://72.32.149.120/screens/EP9.jpg](http://72.32.149.120/screens/EP9.jpg)
Help me find the best of WPF
[ "", "c#", ".net", "wpf", "user-interface", "" ]
I am trying to create a utility method to perform mail merge-like functionality on a template file. Since strings are immutable I'm unsure if I've written it properly - can somebody take a glance and give me feedback? ``` public static string LoadTemplateFile(string fileName, NameValueCollection mergeFields) { string result = System.IO.File.ReadAllText(fileName); if (mergeFields != null) { for (int index = 0; index < mergeFields.Count; index++) { result = result.Replace(mergeFields.Keys[index], mergeFields[index]); } } return result; } ```
It looks like you are attempting to 1. Read a file from disk 2. Do a search / replace based on a provided name / value map If that's the case then yes this will work just fine. The only real feedback I have is that depending on the number of replacement name / value pairs, you're going to be creating a lot of temporary strings. This is probably fine for small files but once you start loading relatively large files into your application you may see an appreciable difference. A better approach would be to use a StringBuilder and do the Replace calls on that object. It would reduce the unnecessary creation of temporary strings.
You'd probably do better to use a StringBuilder instead of a string. ``` public static string LoadTemplateFile( string fileName, NameValueCollection mergeFields) { System.Text.StringBuilder result = new System.Text.StringBuilder( System.IO.File.ReadAllText(fileName)); if (mergeFields != null) { for (int index = 0; index < mergeFields.Count; index++) { result.Replace(mergeFields.Keys[index], mergeFields[index]); } } return result.ToString(); } ```
Optimizing my method
[ "", "c#", "" ]
I have an opportunity to attend Sony licensed training classes to learn about programming with the PS3's cell architecture. However I only have a rudimentary knowledge of C++ and was wondering if the PS3 is a bit of an overkill for a starter aspiring game dev like me. And also what is the best resources to get me to a decent level in C++ graphics programming in about 2 months time?
The problem isn't so much that a PS3 is overkill, it's that the Cell processor is notoriously difficult to program to it's potential. The highly parallelized architecture is potentially quite powerful, but it's not easy to actually get that performance.
I bet it will be fun and whatever you learn in the course will help you become a better programmer.
Is the PS3's Cell architecture the wrong platform to be learning game programming?
[ "", "c++", "playstation3", "" ]
I am using ipython on Mac OS 10.5 with python 2.5.1 (I would actually like to use ipython for 2.6.1, but it doesn't seem to be available?) I installed ipython via easy\_install. It works but is missing gnu readline (needed for nice searching of command line history with ctrl-R, etc.) I found a [blog post](http://www.brianberliner.com/2008/04/18/ipython-on-mac-os-x-105-leopard/) and other sources saying this could be fixed by `sudo easy_install -f http://ipython.scipy.org/dist/ readline` However, this leads to build errors in `readline.c` , particularly undeclared functions like `rl_compentry_func_t` and `rl_catch_signals`. Has anyone seen these errors? Is there another way to get ipython installed with readline?
You can install everything you need with essentially one command using MacPorts. First download and install MacPorts from <http://www.macports.org/>. Then just do the following in the terminal: 1) sudo port -v selfupdate 2) sudo port -v install py26-ipython That will install python2.6, ipython for python 2.6 and readline for you. The command to start ipython will be located at /opt/local/bin/ipython2.6
To install ipython on Snow Leopard or Lion without using MacPorts, you can simply do: ``` sudo easy_install readline ipython ``` (Note that if you use the "pip" to install readline, then ipython won't see the readline library, not sure why). *Edit:* If you had ipython installed remove it with ``` sudo pip uninstall ipython ``` or ``` pip uninstall ipython #for virtualenvs ``` Then make sure you have installed readline first and reinstall iptyhon ``` pip install readline ipython ``` For some reasons, if readline wasn't present during the installation, it will install itself without support for readline or it use the default mac readline.
Installing ipython with readline on the mac
[ "", "python", "macos", "readline", "ipython", "" ]