Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
``` private IEnumerable<string> Tables { get { yield return "Foo"; yield return "Bar"; } } ``` Let's say I want iterate on those and write something like processing #n of #m. Is there a way I can find out the value of m without iterating before my main iteration? I hope I made myself clear.
`IEnumerable` doesn't support this. This is by design. `IEnumerable` uses lazy evaluation to get the elements you ask for just before you need them. If you want to know the number of items without iterating over them you can use `ICollection<T>`, it has a `Count` property.
The `System.Linq.Enumerable.Count` extension method on `IEnumerable<T>` has the following implementation: ``` ICollection<T> c = source as ICollection<TSource>; if (c != null) return c.Count; int result = 0; using (IEnumerator<T> enumerator = source.GetEnumerator()) { while (enumerator.MoveNext()) result++; } return result; ``` So it tries to cast to `ICollection<T>`, which has a `Count` property, and uses that if possible. Otherwise it iterates. So your best bet is to use the `Count()` extension method on your `IEnumerable<T>` object, as you will get the best performance possible that way.
Count the items from a IEnumerable<T> without iterating?
[ "", "c#", ".net", "ienumerable", "" ]
I need to show only one element at a time when a link is clicked on. Right now I'm cheating by hiding everything again and then toggling the element clicked on. This works, unless i want EVERYTHING to disappear again. Short of adding a "Hide All" button/link what can i do? I would like to be able to click on the link again, and hide it's content. EDIT: Pseudo's code would have worked, but the html here mistakenly led you to believe that all the links were in one div. instead of tracking down where they all were, it is easier to call them by their ID. Here's what I have so far: ``` $(document).ready(function(){ //hides everything $("#infocontent *").hide(); //now we show them by which they click on $("#linkjoedhit").click(function(event){ $("#infocontent *").hide(); $("#infojoedhit").toggle(); return false; }); $("#linkgarykhit").click(function(event){ $("#infocontent *").hide(); $("#infogarykhit").toggle(); return false; }); }); ``` and the html looks like: ``` <div id="theircrappycode"> <a id="linkjoedhit" href="">Joe D</a><br/> <a id="linkgarykhit" href="">Gary K</a> </div> <div id="infocontent"> <p id="infojoedhit">Information about Joe D Hitting.</p> <p id="infogarykhit">Information about Gary K Hitting.</p> </div ``` there are about 20 links like this. Because I am not coding the actual html, I have no control over the actual layout, which is horrendous. Suffice to say, this is the only way to organize the links/info.
``` $("#linkgarykhit").click(function(){ if($("#infogarykhit").css('display') != 'none'){ $("#infogarykhit").hide(); }else{ $("#infocontent *").hide(); $("#infogarykhit").show(); } return false; }); ``` --- We could also [DRY](http://en.wikipedia.org/wiki/Don%27t_repeat_yourself) this up a bit: ``` function toggleInfoContent(id){ if($('#' + id).css('display') != 'none'){ $('#' + id).hide(); }else{ $("#infocontent *").hide(); $('#' + id).show(); } } $("#linkgarykhit").click(function(){ toggleInfoContent('infogarykhit'); return false; }); $("#linkbobkhit").click(function(){ toggleInfoContent('infobobkhit'); return false; }); ```
If your markup "naming scheme" is accurate, you can avoid a lot of repetitious code by using a RegEx for your selector, and judicious use of jQuery's "not". You can attach a click event one time to a jQuery collection that should do what you want so you don't need to add any JavaScript as you add more Jim's or John's, as so: ``` $(document).ready( function () { $("#infocontent *").hide(); $("div#theircrappycode > a").click(function(event){ var toggleId = "#" + this.id.replace(/^link/,"info"); $("#infocontent *").not(toggleId).hide(); $(toggleId).toggle(); return false; }); }); ```
Show Only One Element with JQuery
[ "", "javascript", "jquery", "" ]
What is the best way to check for the existence of a session variable in ASP.NET C#? I like to use `String.IsNullOrEmpty()` works for strings and wondered if there was a similar method for `Session`. Currently the only way I know of is: ``` var session; if (Session["variable"] != null) { session = Session["variable"].ToString(); } else { session = "set this"; Session["variable"] = session; } ```
To follow on from what others have said. I tend to have two layers: **The core layer. This is within a DLL that is added to nearly all web app projects**. In this I have a SessionVars class which does the grunt work for Session state getters/setters. It contains code like the following: ``` public class SessionVar { static HttpSessionState Session { get { if (HttpContext.Current == null) throw new ApplicationException("No Http Context, No Session to Get!"); return HttpContext.Current.Session; } } public static T Get<T>(string key) { if (Session[key] == null) return default(T); else return (T)Session[key]; } public static void Set<T>(string key, T value) { Session[key] = value; } } ``` Note the generics for getting any type. I then also add Getters/Setters for specific types, especially string since I often prefer to work with string.Empty rather than null for variables presented to Users. e.g: ``` public static string GetString(string key) { string s = Get<string>(key); return s == null ? string.Empty : s; } public static void SetString(string key, string value) { Set<string>(key, value); } ``` And so on... **I then create wrappers to abstract that away and bring it up to the application model. For example, if we have customer details:** ``` public class CustomerInfo { public string Name { get { return SessionVar.GetString("CustomerInfo_Name"); } set { SessionVar.SetString("CustomerInfo_Name", value); } } } ``` You get the idea right? :) **NOTE:** Just had a thought when adding a comment to the accepted answer. Always ensure objects are serializable when storing them in Session when using a state server. It can be all too easy to try and save an object using the generics when on web farm and it go boom. I deploy on a web farm at work so added checks to my code in the core layer to see if the object is serializable, another benefit of encapsulating the Session Getters and Setters :)
That is pretty much how you do it. However, there is a shorter syntax you can use. ``` sSession = (string)Session["variable"] ?? "set this"; ``` This is saying if the session variables is null, set sSession to "set this"
What is the best way to determine a session variable is null or empty in C#?
[ "", "c#", "asp.net", "session", "" ]
I need a way to represent a 2-D array (a dense matrix) of doubles in C++, with absolute minimum accessing overhead. I've done some timing on various linux/unix machines and gcc versions. An STL vector of vectors, declared as: ``` vector<vector<double> > matrix(n,vector<double>(n)); ``` and accessed through `matrix[i][j]` is between 5% and 100% slower to access than an array declared as: ``` double *matrix = new double[n*n]; ``` accessed through an inlined index function `matrix[index(i,j)]`, where `index(i,j)` evaluates to i+n\*j. Other ways of arranging a 2-D array without STL - an array of n pointers to the start of each row, or defining the whole thing on the stack as a constant size `matrix[n][n]` - run at almost exactly the same speed as the index function method. Recent GCC versions (> 4.0) seem to be able to compile the STL vector-of-vectors to nearly the same efficiency as the non-STL code when optimisations are turned on, but this is somewhat machine-dependent. I'd like to use STL if possible, but will have to choose the fastest solution. Does anyone have any experience in optimising STL with GCC?
If you're using GCC the compiler can analyze your matrix accesses and change the order in memory in certain cases. The magic compiler flag is defined as: ``` -fipa-matrix-reorg ``` > Perform matrix flattening and > transposing. Matrix flattening tries > to replace a m-dimensional matrix with > its equivalent n-dimensional matrix, > where n < m. This reduces the level of > indirection needed for accessing the > elements of the matrix. The second > optimization is matrix transposing > that attemps to change the order of > the matrix's dimensions in order to > improve cache locality. Both > optimizations need fwhole-program > flag. Transposing is enabled only if > profiling information is avaliable. Note that this option is not enabled by -O2 or -O3. You have to pass it yourself.
My guess would be the fastest is, for a matrix, to use 1D STL array and override the () operator to use it as 2D matrix. However, the STL also defines a type specifically for non-resizeable numerical arrays: valarray. You also have various optimisations for in-place operations. valarray accept as argument a numerical type: ``` valarray<double> a; ``` Then, you can use slices, indirect arrays, ... and of course, you can inherit the valarray and define your own operator()(int i, int j) for 2D arrays ...
Optimising C++ 2-D arrays
[ "", "c++", "linux", "optimization", "gcc", "stl", "" ]
Ok, I'm using the term "Progressive Enhancement" kind of loosely here but basically I have a Flash-based website that supports deep linking and loads content dynamically - what I'd like to do is provide alternate content (text) for those either not having Flash and for search engine bots. So, for a user with flash they would navigate to: ``` http://www.samplesite.com/#specific_page ``` and they would see a flash site that would navigate to the "`specific_page`." Those without flash would see the "`specific_page`" rendered in text in the alternative content section. Basically, I would use php/mysql to create a backend to handle all of this since the swf is also using dynamic data. The question is, does something out there that does this already exist?
There's an inherent problem with what you're trying to achieve. The URL hash (or anchor) is client-side only - that token is not sent to the server. This means the only way (that I know of) to load the content you need for example.com/#some\_page is to use AJAX, which can read the hash and then request the page-specific data from the server. Done? No. Because this will kill search engine bots. A possible solution is to have example.com/some\_page serve the same content (in fact, that could easily be a REST service that you've already made to return the AJAX or Flash-requested content), and provide a [sitemap.xml](http://www.sitemaps.org/) which indexes those URIs to help out the search engines. I know of no existing framework that does specifically these tasks, although it certainly seems like one could be made w/o too much trouble.
Well, according to [OSFlash](http://osflash.org/open_source_flash_projects) (the open source flash people) both [CakePHP](http://cakephp.org/) and [PHPWCMS](http://www.phpwcms.de/) can do what you need, although from a first glance at their sites' feature list, it is not entirely obvious. Let us know if they ***do*** work!
Does anyone know of a php framework that would handle progressive enhancement for Flash/Flex content?
[ "", "php", "apache-flex", "flash", "actionscript-3", "progressive-enhancement", "" ]
Hibernate has a handful of methods that, one way or another, takes your object and puts it into the database. What are the differences between them, when to use which, and why isn't there just one intelligent method that knows when to use what? The methods that I have identified thus far are: * `save()` * `update()` * `saveOrUpdate()` * `saveOrUpdateCopy()` * `merge()` * `persist()`
Here's my understanding of the methods. Mainly these are based on the [API](http://www.hibernate.org/hib_docs/v3/api/org/hibernate/Session.html) though as I don't use all of these in practice. **saveOrUpdate** Calls either save or update depending on some checks. E.g. if no identifier exists, save is called. Otherwise update is called. **save** Persists an entity. Will assign an identifier if one doesn't exist. If one does, it's essentially doing an update. Returns the generated ID of the entity. **update** Attempts to persist the entity using an existing identifier. If no identifier exists, I believe an exception is thrown. **saveOrUpdateCopy** This is deprecated and should no longer be used. Instead there is... **merge** Now this is where my knowledge starts to falter. The important thing here is the difference between transient, detached and persistent entities. For more info on the object states, [take a look here](http://docs.jboss.org/hibernate/core/3.6/reference/en-US/html/objectstate.html). With save & update, you are dealing with persistent objects. They are linked to a Session so Hibernate knows what has changed. But when you have a transient object, there is no session involved. In these cases you need to use merge for updates and persist for saving. **persist** As mentioned above, this is used on transient objects. It does not return the generated ID.
``` ╔══════════════╦═══════════════════════════════╦════════════════════════════════╗ β•‘ METHOD β•‘ TRANSIENT β•‘ DETACHED β•‘ ╠══════════════╬═══════════════════════════════╬════════════════════════════════╣ β•‘ β•‘ sets id if doesn't β•‘ sets new id even if object β•‘ β•‘ save() β•‘ exist, persists to db, β•‘ already has it, persists β•‘ β•‘ β•‘ returns attached object β•‘ to DB, returns attached object β•‘ ╠══════════════╬═══════════════════════════════╬════════════════════════════════╣ β•‘ β•‘ sets id on object β•‘ throws β•‘ β•‘ persist() β•‘ persists object to DB β•‘ PersistenceException β•‘ β•‘ β•‘ β•‘ β•‘ ╠══════════════╬═══════════════════════════════╬════════════════════════════════╣ β•‘ β•‘ β•‘ β•‘ β•‘ update() β•‘ Exception β•‘ persists and reattaches β•‘ β•‘ β•‘ β•‘ β•‘ ╠══════════════╬═══════════════════════════════╬════════════════════════════════╣ β•‘ β•‘ copy the state of object in β•‘ copy the state of obj in β•‘ β•‘ merge() β•‘ DB, doesn't attach it, β•‘ DB, doesn't attach it, β•‘ β•‘ β•‘ returns attached object β•‘ returns attached object β•‘ ╠══════════════╬═══════════════════════════════╬════════════════════════════════╣ β•‘ β•‘ β•‘ β•‘ β•‘saveOrUpdate()β•‘ as save() β•‘ as update() β•‘ β•‘ β•‘ β•‘ β•‘ β•šβ•β•β•β•β•β•β•β•β•β•β•β•β•β•β•©β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•©β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β• ```
What are the differences between the different saving methods in Hibernate?
[ "", "java", "hibernate", "persistence", "" ]
--- **The [HttpRequestPool](http://docs.php.net/manual/en/class.httprequestpool.php) class provides a solution. Many thanks to those who pointed this out.** A brief tutorial can be found at: <http://www.phptutorial.info/?HttpRequestPool-construct> --- **Problem** I'd like to make concurrent/parallel/simultaneous HTTP requests in PHP. I'd like to avoid consecutive requests as: * a set of requests will take too long to complete; the more requests the longer * the timeout of one request midway through a set may cause later requests to not be made (if a script has an execution time limit) I have managed to find details for making [simultaneuos [sic] HTTP requests in PHP with cURL](http://www.phpied.com/simultaneuos-http-requests-in-php-with-curl/), however I'd like to explicitly use PHP's [HTTP functions](http://php.net/manual/en/book.http.php) if at all possible. Specifically, I need to POST data concurrently to a set of URLs. The URLs to which data are posted are beyond my control; they are user-set. I don't mind if I need to wait for all requests to finish before the responses can be processed. If I set a timeout of 30 seconds on each request and requests are made concurrently, I know I must wait a maximum of 30 seconds (perhaps a little more) for all requests to complete. I can find no details of how this might be achieved. However, I did recently notice a mention in the PHP manual of PHP5+ being able to handle concurrent HTTP requests - I intended to make a note of it at the time, forgot, and cannot find it again. **Single request example (works fine)** ``` <?php $request_1 = new HttpRequest($url_1, HTTP_METH_POST); $request_1->setRawPostData($dataSet_1); $request_1->send(); ?> ``` **Concurrent request example (incomplete, clearly)** ``` <?php $request_1 = new HttpRequest($url_1, HTTP_METH_POST); $request_1->setRawPostData($dataSet_1); $request_2 = new HttpRequest($url_2, HTTP_METH_POST); $request_2->setRawPostData($dataSet_2); // ... $request_N = new HttpRequest($url_N, HTTP_METH_POST); $request_N->setRawPostData($dataSet_N); // Do something to send() all requests at the same time ?> ``` Any thoughts would be most appreciated! **Clarification 1**: I'd like to stick to the PECL HTTP functions as: * they offer a nice OOP interface * they're used extensively in the application in question and sticking to what's already in use should be beneficial from a maintenance perspective * I generally have to write fewer lines of code to make an HTTP request using the PECL HTTP functions compared to using cURL - fewer lines of code should also be beneficial from a maintenance perspective **Clarification 2**: I realise PHP's HTTP functions aren't built in and perhaps I worded things wrongly there, which I shall correct. I have no concerns about people having to install extra stuff - this is not an application that is to be distributed, it's a web app with a server to itself. **Clarification 3**: I'd be perfectly happy if someone authoritatively states that the PECL HTTP cannot do this.
I'm pretty sure [HttpRequestPool](http://docs.php.net/manual/en/class.httprequestpool.php) is what you're looking for. To elaborate a little, you can use forking to achieve what you're looking for, but that seems unnecessarily complex and not very useful in a HTML context. While I haven't tested, this code should be it: ``` // let $requests be an array of requests to send $pool = new HttpRequestPool(); foreach ($requests as $request) { $pool->attach($request); } $pool->send(); foreach ($pool as $request) { // do stuff } ```
Did you try [HttpRequestPool](http://www.php.net/manual/en/class.httprequestpool.php) (it's part of Http)? It looks like it would pool up the request objects and work them. I know I read somewhere that Http would support simultaneous requests and aside from *pool* I can't find anything either.
Parallel HTTP requests in PHP using PECL HTTP classes [Answer: HttpRequestPool class]
[ "", "php", "http", "parallel-processing", "pecl", "simultaneous", "" ]
I need a (php) regex to match Yahoo's username rules: > Use 4 to 32 characters and start with a letter. You may use letters, numbers, underscores, and one dot (.).
``` /^[A-Za-z](?=[A-Za-z0-9_.]{3,31}$)[a-zA-Z0-9_]*\.?[a-zA-Z0-9_]*$/ ``` Or a little shorter: ``` /^[a-z](?=[\w.]{3,31}$)\w*\.?\w*$/i ```
``` /[a-zA-Z][a-zA-Z0-9_]*\.?[a-zA-Z0-9_]*/ ``` And check if strlen($username) >= 4 and <= 32.
Yahoo Username Regex
[ "", "php", "regex", "validation", "yahoo", "" ]
I need to get just the first item (actually, just the first key) off a rather large associative array in JavaScript. Here's how I'm doing it currently (using jQuery): ``` getKey = function (data) { var firstKey; $.each(data, function (key, val) { firstKey = key; return false; }); return firstKey; }; ``` Just guessing, but I'd say there's got to be a better (read: more efficient) way of doing this. Any suggestions? UPDATE: Thanks for the insightful answers and comments! I had forgotten my JavaScript 101, wherein the spec says you're not guaranteed a particular order in an associative array. It's interesting, though, that most browsers do implement it that way. I'd prefer not to sort the array before getting that first key, but it may be unavoidable given my use case.
There isn't really a **first** or **last** element in associative arrays (i.e. objects). The only order you can hope to acquire is the order the elements were saved by the parser -- and no guarantees for consistency with that. But, if you want ***the first to come up***, the classic manner might actually be a bit easier: ``` function getKey(data) { for (var prop in data) return prop; } ``` Want to avoid inheritance properties? ``` function getKey(data) { for (var prop in data) if (data.propertyIsEnumerable(prop)) return prop; } ```
You can avoid having to create a function by referencing the first entry returned from `Object.keys()`: ``` var firstKey = Object.keys(data)[0]; ``` For the first entry from a sorted key list, simply add a call to the `.sort()` method: ``` var firstKey = Object.keys(data).sort()[0]; ```
What is the most efficient way to get the first item from an associative array in JavaScript?
[ "", "javascript", "jquery", "arrays", "associative", "" ]
If I switch on the generating of debug info with Javac then the class files are 20-25% larger. Has this any performance effects on running the Java program? If yes on which conditions and how many. I expect a little impact on loading the classes because the files are larger but this should be minimal.
In any language, debugging information is meta information. It by its nature increases the size of the object files, thus increasing load time. During execution outside a debugger, this information is actually completely ignored. As outlined (although not clearly) in the [JVM spec](http://java.sun.com/docs/books/jvms/second_edition/html/ClassFile.doc.html#1546) the debug information is stored outside the bytecode stream. This means that at execution time there is no difference in the class file. If you want to be sure though, try it out :-). Ps. Often for debugging there is value in turning off optimization. That *does* have a performance impact.
Turning off debugging alone should not make a difference at all. But once you turn off debugging and turn on optimization, you should see a difference, as this makes some static optimizations at compile time. This way even your hot-spot optimized code gets faster at runtime. But so far, the tradeoff between getting meaning full stack-traces or having some more user-performance, I always voted for the stack-traces. After all, users are willing to spend 1000$ each year to get a faster machine, but are not willing to spend 15 minutes to give you meaningful error messages to you to solve their problems. After the years, I'm more willing to value my 15 minutes higher than the user's 1000$. :)
Is there a performance difference between Javac debug on and off?
[ "", "java", "performance", "debugging", "javac", "" ]
Similar to [this question](https://stackoverflow.com/questions/233030/worst-php-practice-found-in-your-experience)... What are the worst practices you actually found in Java code? Mine are: * using instance variables in servlets (it's not just bad practice but bug, actually) * using Collection implementations like HashMap, and not using the appropriate interfaces * using seemingly cryptic class names like SmsMaker (SmsFactory) or CommEnvironment (CommunicationContext)
I had to maintain java code, where most of the Exception handling was like: ``` catch( Exception e ) {} ```
Once I encountered 'singleton' exception: ``` class Singletons { public static final MyException myException = new MyException(); } class Test { public void doSomething() throws MyException { throw Singletons.myException; } } ``` **Same instance of exception** was thrown each time ... with exact same stacktrace, which had nothing to do with real code flow :-(
Worst Java practice found in your experience?
[ "", "java", "" ]
I need the "Select Data Source" dialog added to my application so that the user can manually select a range (or ranges) in Excel and the range is pasted in my text box. This functionality is everywhere in Excel (most notably when selecting a range for a chart). How can I easily do this?
have you tried using the refedit control? [How to Use the RefEdit Control with a UserForm](http://support.microsoft.com/kb/213776)
``` Dim myRange As Range On Error Resume Next Set myRange = Application.InputBox(prompt:="Select the cells you want", Type:=8) On Error GoTo 0 If myRange Is Nothing Then MsgBox "User cancelled" Else MsgBox "User selected " & myRange.Address End If ``` This will show an input dialog. Don't type anything into it, but instead, select cells with the mouse, and their address will appear in the dialog textbox. When you press OK,they should be assigned to the variable myRange. Notes: The "Type:=8" at the end of the InputBox line tells VBA this must be a range of cells The On Error bit prevents an error if the user cancels
How to add "Select Data Source" to my Excel application?
[ "", "c#", "excel", "user-interface", "" ]
I'm matching identifiers, but now I have a problem: my identifiers are allowed to contain unicode characters. Therefore the old way to do things is not enough: ``` t_IDENTIFIER = r"[A-Za-z](\\.|[A-Za-z_0-9])*" ``` In [my markup language](http://freehg.org/u/cheery/aml/) parser I match unicode characters by allowing all the characters except those I explicitly use, because my markup language only has two or three of characters I need to escape that way. How do I match all unicode characters with python regexs and ply? Also is this a good idea at all? I'd want to let people use identifiers like Ξ© Β» Β« Β° fooΒ² vΓ€li Ο€ as an identifiers (variable names and such) in their programs. Heck! I want that people could write programs in their own language if it's practical! Anyway unicode is supported nowadays in wide variety of places, and it should spread. Edit: POSIX character classes doesnt seem to be recognised by python regexes. ``` >>> import re >>> item = re.compile(r'[[:word:]]') >>> print item.match('e') None ``` Edit: To explain better what I need. I'd need a regex -thing that matches all the unicode printable characters but not ASCII characters at all. Edit: r"\w" does a bit stuff what I want, but it does not match Β« Β», and I also need a regex that does not match numbers.
the [re](http://docs.python.org/library/re#regular-expression-syntax) module supports the \w syntax which: > If UNICODE is set, this will match the > characters [0-9\_] plus whatever is > classified as alphanumeric in the > Unicode character properties database. therefore the following examples shows how to match unicode identifiers: ``` >>> import re >>> m = re.compile('(?u)[^\W0-9]\w*') >>> m.match('a') <_sre.SRE_Match object at 0xb7d75410> >>> m.match('9') >>> m.match('ab') <_sre.SRE_Match object at 0xb7c258e0> >>> m.match('a9') <_sre.SRE_Match object at 0xb7d75410> >>> m.match('unicΓΆde') <_sre.SRE_Match object at 0xb7c258e0> >>> m.match('ΓΆdipus') <_sre.SRE_Match object at 0xb7d75410> ``` So the expression you look for is: (?u)[^\W0-9]\w\*
You need pass pass parameter reflags in lex.lex: ``` lex.lex(reflags=re.UNICODE) ```
Match unicode in ply's regexes
[ "", "python", "regex", "unicode", "ply", "character-properties", "" ]
I have seen various rules for naming stored procedures. Some people prefix the sproc name with usp\_, others with an abbreviation for the app name, and still others with an owner name. You shouldn't use sp\_ in SQL Server unless you really mean it. Some start the proc name with a verb (Get, Add, Save, Remove). Others emphasize the entity name(s). On a database with hundreds of sprocs, it can be very hard to scroll around and find a suitable sproc when you think one already exists. Naming conventions can make locating a sproc easier. Do you use a naming convention? Please describe it, and explain why you prefer it over other choices. **Summary of replies:** * Everybody seems to advocate consistency of naming, that it might be more important for everyone to use the same naming convention than which particular one is used. * Prefixes: While a lot of folks use usp\_ or something similar (but rarely sp\_), many others use database or app name. One clever DBA uses gen, rpt and tsk to distinguish general CRUD sprocs from those used for reporting or tasks. * Verb + Noun seems to be slightly more popular than Noun + Verb. Some people use the SQL keywords (Select, Insert, Update, Delete) for the verbs, while others use non-SQL verbs (or abbreviations for them) like Get and Add. Some distinguish between singluar and plural nouns to indicate whether one or many records are being retrieved. * An additional phrase is suggested at the end, where appropriate. GetCustomerById, GetCustomerBySaleDate. * Some people use underscores between the name segments, and some avoid underscores. app\_ Get\_Customer vs. appGetCustomer -- I guess it's a matter of readability. * Large collections of sprocs can be segregated into Oracle packages or Management Studio (SQL Server) solutions and projects, or SQL Server schemas. * Inscrutable abbreviations should be avoided. **Why I choose the answer I did:** There are SO many good responses. Thank you all! As you can see, it would be very hard to choose just one. The one I chose resonated with me. I have followed the same path he describes -- trying to use Verb + Noun and then not being able to find all of the sprocs that apply to Customer. Being able to locate an existing sproc, or to determine if one even exists, is very important. Serious problems can arise if someone inadvertently creates a duplicate sproc with another name. Since I generally work on very large apps with hundreds of sprocs, I have a preference for the easiest-to-find naming method. For a smaller app, I might advocate Verb + Noun, as it follows the general coding convention for method names. He also advocates prefixing with app name instead of the not very useful usp\_. As several people pointed out, sometimes the database contains sprocs for multiple apps. So, prefixing with app name helps to segregate the sprocs AND helps DBAs and others to determine which app the sproc is used for.
For my last project i used usp\_[Action][Object][Process] so for example, usp\_AddProduct or usp\_GetProductList, usp\_GetProductDetail. However now the database is at 700 procedures plus, it becomes a lot harder to find all procedures on a specific object. For example i now have to search 50 odd Add procedures for the Product add, and 50 odd for the Get etc. Because of this in my new application I'm planning on grouping procedure names by object, I'm also dropping the usp as I feel it is somewhat redundant, other than to tell me its a procedure, something I can deduct from the name of the procedure itself. The new format is as follows ``` [App]_[Object]_[Action][Process] App_Tags_AddTag App_Tags_AddTagRelations App_Product_Add App_Product_GetList App_Product_GetSingle ``` It helps to group things for easier finding later, especially if there are a large amount of sprocs. Regarding where more than one object is used, I find that most instances have a primary and secondary object, so the primary object is used in the normal instance, and the secondary is refered to in the process section, for example App\_Product\_AddAttribute.
**Here's some clarification about the sp\_ prefix issue in SQL Server.** Stored procedures named with the prefix sp\_ are system sprocs stored in the Master database. If you give your sproc this prefix, SQL Server looks for them in the Master database first, then the context database, thus unnecessarily wasting resources. And, if the user-created sproc has the same name as a system sproc, the user-created sproc won't be executed. The sp\_ prefix indicates that the sproc is accessible from all databases, but that it should be executed in the context of the current database. [Here's](http://www.sqlmag.com/Article/ArticleID/23011/sql_server_23011.html) a nice explanation, which includes a demo of the performance hit. [Here's](http://rakph.wordpress.com/2008/04/19/tips-store-procedure/) another helpful source provided by Ant in a comment.
What is your naming convention for stored procedures?
[ "", "sql", "stored-procedures", "naming-conventions", "" ]
What is the difference between UTF and UCS. What are the best ways to represent not European character sets (using UTF) in C++ strings. I would like to know your recommendations for: * Internal representation inside the code + For string manipulation at run-time + For using the string for display purposes. * Best storage representation (**i.e.** In file) * Best on wire transport format (Transfer between application that may be on different architectures and have a different standard locale)
> What is the difference between UTF and UCS. UCS encodings are fixed width, and are marked by how many bytes are used for each character. For example, UCS-2 requires 2 bytes per character. Characters with code points outside the available range can't be encoded in a UCS encoding. UTF encodings are variable width, and marked by the minimum number of bits to store a character. For example, UTF-16 requires at least 16 bits (2 bytes) per character. Characters with large code points are encoded using a larger number of bytes -- 4 bytes for astral characters in UTF-16. > * Internal representation inside the code > * Best storage representation (i.e. In file) > * Best on wire transport format (Transfer between application that may > be on different architectures and have > a different standard locale) For modern systems, the most reasonable storage and transport encoding is UTF-8. There are special cases where others might be appropriate -- UTF-7 for old mail servers, UTF-16 for poorly-written text editors -- but UTF-8 is most common. Preferred internal representation will depend on your platform. In Windows, it is UTF-16. In UNIX, it is UCS-4. Each has its good points: * UTF-16 strings never use more memory than a UCS-4 string. If you store many large strings with characters primarily in the basic multi-lingual plane (BMP), UTF-16 will require much less space than UCS-4. Outside the BMP, it will use the same amount. * UCS-4 is easier to reason about. Because UTF-16 characters might be split over multiple "surrogate pairs", it can be challenging to correctly split or render a string. UCS-4 text does not have this issue. UCS-4 also acts much like ASCII text in "char" arrays, so existing text algorithms can be ported easily. Finally, some systems use UTF-8 as an internal format. This is good if you need to inter-operate with existing ASCII- or ISO-8859-based systems because NULL bytes are not present in the middle of UTF-8 text -- they are in UTF-16 or UCS-4.
Have you read Joel Spolsky's article on [The Absolute Minimum Every Software Developer Absolutely, Positively Must Know About Unicode and Character Sets (No Excuses!)](http://www.joelonsoftware.com/articles/Unicode.html)?
UTF usage in C++ code
[ "", "c++", "unicode", "locale", "utf", "ucs", "" ]
In my javascript experience, I found that is a very common task "searching the nearest ancestor of an element with some condition (tag name, class,...)". Can the parents() method of jquery do the job? The order of returned elements of parents() is predictable? Is top-to-bottom or bottom-to-top? For the moment I use this utility function: ``` function ancestor(elem, selector) { var $elem = $( elem ).parent(); while( $elem.size() > 0 ) { if( $elem.is( selector ) ) return $elem; else $elem = $elem.parent(); } return null; } ``` Can someone tell me if there is a clever way to do the job?
**Edit**: Since jQuery 1.3, this has been built in as the [`closest()`](http://api.jquery.com/closest) function. eg: `$('#foo').closest('.bar');` --- yep - parents() traverses up the tree. ``` <div id="a"> <div id="b"> <p id="c"> <a id="d"></a> </p> </div> </div> ``` `$('#d').parents("div:first");` will select div b.
*Adding to @[nickf](https://stackoverflow.com/users/9021/nickf)'s answer:* jQuery 1.3 simplifyed this task with `closest`. Given a DOM: ``` <div id="a"> <div id="b"> <p id="c"> <a id="d"></a> </p> </div> </div> ``` You can do: ``` $('#d').closest("div"); // returns [ div#b ] ``` > [[Closest](http://docs.jquery.com/Traversing/closest) returns a] set of > elements containing the closest parent > element that matches the specified > selector, the starting element > included.
nearest ancestor node in jQuery
[ "", "javascript", "jquery", "dom", "" ]
Let's say I have the following ruby code : ``` def use_object(object) puts object.some_method end ``` and , this will work on any object that responds to **some\_method**,right? Assuming that the following java interface exists : ``` interface TestInterface { public String some_method(); } ``` Am I right to presume that interfaces are java's way to achieving the same thing ( with the only difference that the parameter's type would be **TestInterface** ) ?
You are right except that you can not define the body of a function in Java Interfaces, only prototypes. Interfaces are the only way to implemente a pseudo multi-derivation in Java, since normal class derivation is only simple (just one parent).
No, interfaces in are not implemented. You can have multiple implementations of it though. An interface would look more like: ``` interface TestInterface { public String some_method(); } ``` And it could be implemented in a class: ``` public class TestClass implements TestInterface { public String some_method() { return "test"; } } ``` And maybe more classes that implement this method differently. All classes that implement an interface have to implement the methods as declared by an interface. With interfaces you can't achive exactly the same as in your Ruby example since Java is static typed.
question about java interfaces
[ "", "java", "ruby", "" ]
I am trying to place a big number in a C++ variable. The number is 600851475143 I tried unsigned long long int but got an error saying it the constant was too big. I then tried a bigInt library called BigInt -> <http://mattmccutchen.net/bigint/> The problem is I can't compile the code as I get many errors regarding the lib. undefined reference to `BigInteger::BigInteger(int)' <-- lot's of these. Here is my code so far: ``` #include "string" #include "iostream" #include "bigint/NumberlikeArray.hh" #include "bigint/BigUnsigned.hh" #include "bigint/BigInteger.hh" #include "bigint/BigIntegerAlgorithms.hh" #include "bigint/BigUnsignedInABase.hh" #include "bigint/BigIntegerUtils.hh" using namespace std; int main() { //unsigned long int num = 13195; //unsigned long long int num = 600851475143; BigInteger num = 13195; int divider = 2; //num = 600851475143; while (1) { if ((num % divider) == 0) { cout << divider << '\n'; num /= divider; } else divider++; if (num == 1) break; } } ``` If I put a smaller number and don't use the BigInt lib this program runs fine. Any help will be appreciated :D
You can specify an integer literal as long by the suffix L. You can specify an integer literal as long long by the suffix LL. ``` #include <iostream> int main() { long long num = 600851475143LL; std::cout << num; } ```
The number is 600851475143 isn't too large for a long long int but you need to use the LL suffix when using a long long constants (ULL for unsigned long long int): ``` unsigned long long int num = 600851475143ULL; ```
Big number in C++
[ "", "c++", "biginteger", "" ]
I'm trying to get authentication working to my liking in a CakePHP app and running into a snag. I want to let the user login from either the home page or from a dedicated login page. I'm using the Auth component to manage login and right now the login itself works. I am submitting the form on the home page to /Users/Login and it does log them in and create session. The problem is it then redirects the user back to the home page. I'd rather they redirect to the location specified in loginRedirect. If i login from /users/login directly it does forward to loginRedirect. I think the problem has something to do with posting the form from one page to another page instead of to itself, auth automatically thinks you want to go back to the previous page. Any thoughts?
in the AppController ``` public function beforeFilter( ) { $this->Auth->autoRedirect = false; } ``` in UsersController ``` public function login( ) { if( $this->Auth->user( ) ) { $this->redirect( array( 'controller' => 'users' , 'action' => 'index' , )); } } ``` Also, if you haven't already you should move the form into an element, so that you can make absolutely certain that the login form is identical between the 2 login views.
Yes auth has a feature where it will redirect you to the page you tried to access before logging in. If setting the loging redirect did not work, you can try to set the loginRedirect to false and do a manual ($this->redirect([..] ) in the UsersController::login action.
How do I get the loginRedirect from multiple login locations in CakePHP?
[ "", "php", "cakephp", "" ]
I am writing my own Joomla component (MVC), its based heavily on the newsflash module, because I want to display the latest 5 content items in a sliding tabbed interface, all the hard work is done, but I am having real difficult getting content out of the for loop. Here is the code I have so far default.php ``` <ul id="handles" class="tabs"> <?php for ($i = 0, $n = count($list); $i < $n; $i ++) : modSankeSlideHelper::getTabs($list[$i]); endfor; ?> <li class="end"></li> </ul> ``` helper.php ``` function getTabs(&$item) { global $mainframe; $item->created = $item->created; list($year, $month, $day) = split("-", $item->created); $tabdate = date('d\/m\/y', mktime(0, 0, 0, $month, $day, $year)); require(JModuleHelper::getLayoutPath('mod_sankeslide', '_tab')); } ``` \_tab.php ``` <li><a href="#tab"><span><?php echo 'Shout ' . $tabdate; ?></span><b></b></a></li> ``` The first item needs to have different value and a class item added to the a: item, so I need to be able to identify which is the first item and do something during that loop. I tried to use if $i = 0 else statement in the default.php, but it resulted in a page timeout for some reason! Any ideas?
You said, you tried `if $i = 0`, the [comparison operator](http://www.php.net/operators.comparison) in PHP is `==`, with your if you have an endless loop, because in each iteration you assign 0 to $i, and it never reaches $n, you should do inside your loop: ``` if ($i == 0){ // First Item here... }else{ // Other Items... } ```
I think @CMS is correct. You might also want to think about handling the first item outside the loop and letting the loop handle the rest of the items. This way you don't have to make the check on each pass through the loop.
Getting the first item out of a For loop
[ "", "php", "joomla", "for-loop", "" ]
I am trying to use Lambda Expressions in a project to map to a third party query API. So, I'm parsing the Expression tree by hand. If I pass in a lambda expression like: ``` p => p.Title == "title" ``` everything works. However, if my lambda expression looks like: ``` p => p.Title == myaspdropdown.SelectedValue ``` Using the .NET debugger, I don't see the actual value of that funciton. Instead I see something like: ``` p => p.Title = (value(ASP.usercontrols_myaspusercontrol_ascx).myaspdropdown.SelectedValue) ``` What gives? And when I try to grab the right side of the expression as a string, I get `(value(ASP.usercontrols_myaspusercontrol_ascx).myaspdropdown.SelectedValue)` instead of the actual value. **How do I get the actual value?**
Remember that when you're dealing with the lambda expression as an expression tree, you don't have executable code. Rather you have a tree of expression elements, that make up the expression you wrote. Charlie Calvert has [a good post](https://learn.microsoft.com/en-us/archive/blogs/charlie/expression-tree-basics) that discusses this in detail. Included is an example of using an expression visualiser for debugging expressions. In your case, to get the value of the righthand side of the equality expression, you'll need to create a new lambda expression, compile it and then invoke it. I've hacked together a quick example of this - hope it delivers what you need. ``` public class Class1 { public string Selection { get; set; } public void Sample() { Selection = "Example"; Example<Book, bool>(p => p.Title == Selection); } public void Example<T,TResult>(Expression<Func<T,TResult>> exp) { BinaryExpression equality = (BinaryExpression)exp.Body; Debug.Assert(equality.NodeType == ExpressionType.Equal); // Note that you need to know the type of the rhs of the equality var accessorExpression = Expression.Lambda<Func<string>>(equality.Right); Func<string> accessor = accessorExpression.Compile(); var value = accessor(); Debug.Assert(value == Selection); } } public class Book { public string Title { get; set; } } ```
To get the actual value, you need to apply the logic of the expression tree to whatever context you've got. The whole point of expression trees is that they represent the *logic* as data rather than evaluating the expression. You'll need to work out what the lambda expression truly means. That may mean evaluating some parts of it against local data - you'll need to decide that for yourself. Expression trees are very powerful, but it's not a simple matter to parse and use them. (Ask anyone who's written a LINQ provider... Frans Bouma has bemoaned the difficulties several times.)
Lambda Expression Tree Parsing
[ "", "c#", "lambda", "expression-trees", "" ]
I have worked on projects for embedded systems in the past where we have rearranged the order of declaration of stack variables to decrease the size of the resulting executable. For instance, if we had: ``` void func() { char c; int i; short s; ... } ``` We would reorder this to be: ``` void func() { int i; short s; char c; ... } ``` Because of alignment issues the first one resulted in 12 bytes of stack space being used and the second one resulted in only 8 bytes. Is this standard behavior for C compilers or just a shortcoming of the compiler we were using? It seems to me that a compiler should be able to reorder stack variables to favor smaller executable size if it wanted to. It has been suggested to me that some aspect of the C standard prevents this, but I haven't been able to find a reputable source either way. As a bonus question, does this also apply to C++ compilers? **Edit** If the answer is yes, C/C++ compilers can rearrange stack variables, can you give an example of a compiler that definitely does this? I'd like to see compiler documentation or something similar that backs this up. **Edit Again** Thanks everybody for your help. For documentation, the best thing I've been able to find is the paper [Optimal Stack Slot Assignment in GCC](http://mirror-fpt-telecom.fpt.net/gcc/summit/2003/Optimal%20Stack%20Slot%20Assignment.pdf)(pdf), by Naveen Sharma and Sanjiv Kumar Gupta, which was presented at the GCC summit proceedings in 2003. The project in question here was using the ADS compiler for ARM development. It is mentioned in the documentation for that compiler that ordering declarations like I've shown can improve performance, as well as stack size, because of how the ARM-Thumb architecture calculates addresses in the local stack frame. That compiler didn't automatically rearrange locals to take advantage of this. The paper linked here says that as of 2003 GCC also didn't rearrange the stack frame to improve locality of reference for ARM-Thumb processors, but it implies that you could. I can't find anything that definitely says this was ever implemented in GCC, but I think this paper counts as proof that you're all correct. Thanks again.
As there is nothing in the standard prohibiting that for C or C++ compilers, yes, the compiler can do that. It is different for aggregates (i.e. structs), where the relative order must be maintained, but still the compiler may insert pad bytes to achieve preferable alignment. IIRC newer MSVC compilers use that freedom in their fight against buffer overflows of locals. As a side note, in C++, the order of destruction must be reverse order of declaration, even if the compiler reorders the memory layout. (I can't quote chapter and verse, though, this is from memory.)
Not only can the compiler reorder the stack layout of the local variables, it can assign them to registers, assign them to live sometimes in registers and sometimes on the stack, it can assign two locals to the same slot in memory (if their live ranges do not overlap) and it can even completely eliminate variables.
Can a C compiler rearrange stack variables?
[ "", "c++", "c", "compiler-construction", "alignment", "callstack", "" ]
I am trying to insert about 50,000 objects (and therefore 50,000 keys) into a `java.util.HashMap<java.awt.Point, Segment>`. However, I keep getting an OutOfMemory exception. (`Segment` is my own class - very light weight - one `String` field, and 3 `int` fields). ``` Exception in thread "main" java.lang.OutOfMemoryError: Java heap space at java.util.HashMap.resize(HashMap.java:508) at java.util.HashMap.addEntry(HashMap.java:799) at java.util.HashMap.put(HashMap.java:431) at bus.tools.UpdateMap.putSegment(UpdateMap.java:168) ``` This seems quite ridiculous since I see that there is plenty of memory available on the machine - both in free RAM and HD space for virtual memory. Is it possible Java is running with some stringent memory requirements? Can I increase these? Is there some weird limitation with `HashMap`? Am I going to have to implement my own? Are there any other classes worth looking at? (I am running Java 5 under OS X 10.5 on an Intel machine with 2GB RAM.)
You can increase the maximum heap size by passing -Xmx128m (where 128 is the number of megabytes) to java. I can't remember the default size, but it strikes me that it was something rather small. You can programmatically check how much memory is available by using the [Runtime](http://java.sun.com/javase/6/docs/api/java/lang/Runtime.html) class. ``` // Get current size of heap in bytes long heapSize = Runtime.getRuntime().totalMemory(); // Get maximum size of heap in bytes. The heap cannot grow beyond this size. // Any attempt will result in an OutOfMemoryException. long heapMaxSize = Runtime.getRuntime().maxMemory(); // Get amount of free memory within the heap in bytes. This size will increase // after garbage collection and decrease as new objects are created. long heapFreeSize = Runtime.getRuntime().freeMemory(); ``` (Example from [Java Developers Almanac](http://www.exampledepot.com/egs/java.lang/GetHeapSize.html)) This is also partially addressed in [Frequently Asked Questions About the Java HotSpot VM](http://java.sun.com/docs/hotspot/HotSpotFAQ.html), and in the [Java 6 GC Tuning page](http://java.sun.com/javase/technologies/hotspot/gc/gc_tuning_6.html).
Some people are suggesting changing the parameters of the HashMap to tighten up the memory requirements. I would suggest to **measure instead of guessing**; it might be something else causing the OOME. In particular, I'd suggest using either [NetBeans Profiler](http://profiler.netbeans.org/) or [VisualVM](https://visualvm.dev.java.net/) (which comes with Java 6, but I see you're stuck with Java 5).
Why do I get an OutOfMemoryError when inserting 50,000 objects into HashMap?
[ "", "java", "hashmap", "out-of-memory", "" ]
Back in the 90s when I first started out with MFC I used to dynamically link my apps and shipped the relevant MFC DLLs. This caused me a few issues (DLL hell!) and I switched to statically linking instead - not just for MFC, but for the CRT and ATL. Other than larger EXE files, statically linking has never caused me any problems at all - so are there any downsides that other people have come across? Is there a good reason for revisiting dynamic linking again? My apps are mainly STL/Boost nowadays FWIW.
There are some downsides: * Bigger exe size (esp if you ship multiple exe's) * Problems using other DLL's which rely on or assume dynamic linking (eg: 3rd party DLL's which you cannot get as static libraries) * Different c-runtimes between DLL's with independent static linkage (no cross-module allocate/deallocate) * No automatic servicing of shared components (no ability to have 3rd party module supplier update their code to fix issues without recompiling and updating your application) We do static linking for our Windows apps, primarily because it allows xcopy deployment, which is just not possible with installing or relying on SxS DLL's in a way which works, since the process and mechanism is not well documented or easily remotable. If you use local DLL's in the install directory it will kinda work, but it's not well supported. The inability to easily do remote installation without going through a MSI on the remote system is the primary reason why we don't use dynamic linking, but (as you pointed out) there are many other benefits to static linking. There are pros and cons to each; hopefully this helps enumerate them.
Most of the answers I hear about this involve sharing your dll's with other programs, or having those dll's be updated without the need to patch your software. Frankly I consider those to be downsides, not upsides. When a third party dll is updated, it can change enough to break your software. And these days, hard drive space isn't as precious as it once was, an extra 500k in your executable? Who cares? * Being 100% sure of the version of dll that your software is using is a good thing. * Being 100% sure that the client is not going to have a dependency headache is a good thing. The upsides far outweigh the downsides in my opinion
Static or dynamic linking the CRT, MFC, ATL, etc
[ "", "c++", "mfc", "linker", "" ]
I have intermittent crashes occurring in my ActiveMQ libraries due to the way I'm using the activemq-cpp API. It'd be much easier to debug the issue if I could observe every function being called leading up to the crash. Are there any quick ways to trace the entry and exit of functions in a Visual Studio 2005 c++ multithreaded program? Thanks in advance!
Use a Tracer object. Something like this: ``` class Tracer { public: Tracer(const char *functionName) : functionName_(functionName) { cout << "Entering function " << functionName_ << endl; } ~Tracer() { cout << "Exiting function " << functionName_ << endl; } const char *functionName_; }; ``` Now you can simply instantiate a Tracer object at the top the function, and it will automatically print "exiting... " when the function exits and the destructor is called: ``` void foo() { Tracer t("foo"); ... } ```
While the debugger is attached to a process, you can rightclick in the source code and select "breakpoint->add TracePoint", with the text you want (even some macro's are supplied). The Tracepoint is in fact a BreakPoint with the "When Hit" field on some message printer functionality, and it doesn't actually break the process. I found it mighty useful: it also has a macro $FUNCTION, which does exactly what you need: print the function it is in (provided it has the debug info available...), and a $THREADID.
What's a quick way to trace the entry and exit of functions in a Visual Studio 2005 c++ multithreaded program?
[ "", "c++", "visual-studio-2005", "trace", "activemq-classic", "visual-c++-2005", "" ]
Accidentally I may forget to describe some parameters or exception throwing (or something else) when documenting methods or classes, etc. Is it possible to run javadoc in such a way that it warns me about missing documentation items? (I use ant script for generating documentation)
Use [Checkstyle](http://checkstyle.sourceforge.net/)! It has awesome Ant integration and supports 100s of other important checks to your source code too. The [JavadocType checker](http://checkstyle.sourceforge.net/config_javadoc.html) is what you'll need though.
I do not know of any javadoc option that will issue a warning about non-documented items. However, if You happen to use Eclipse, take a look at the settings in Window -> Preferences -> Java -> Compiler -> Javadoc There, You can tell Eclipse to issue warnings on undocumented items.
Is it possible to obtain warnings from javadoc when something missed in javadoc-comments?
[ "", "java", "documentation", "javadoc", "" ]
While developing a C++ application, I had to use a third-party library which produced a huge amount of warnings related with a harmless #pragma directive being used. ``` ../File.hpp:1: warning: ignoring #pragma ident In file included from ../File2.hpp:47, from ../File3.hpp:57, from File4.h:49, ``` Is it possible to disable this kind of warnings, when using the GNU C++ compiler?
I believe you can compile with ``` -Wno-unknown-pragmas ``` to suppress these.
In GCC, compile with -Wno-unknown-pragmas In MS Visual Studio 2005 (this question isn't tagged with gcc, so I'm adding this for reference), you can disable globally in Project Settings->C/C++->Advanced. Enter 4068 in "Disable Specific Warnings" or you can add this to any file to disable warnings locally ``` #pragma warning (disable : 4068 ) /* disable unknown pragma warnings */ ```
How can I disable #pragma warnings?
[ "", "c++", "warnings", "pragma", "" ]
I've been running the built-in [Ant](http://ant.apache.org/) from the command line on a Macintosh (10.5.5) and have run into some trouble with the **Mail** task. Running the Mail task produces the following message: ``` [mail] Failed to initialise MIME mail: org.apache.tools.ant.taskdefs.email.MimeMailer ``` This is most likely due to a missing ant-javamail.jar file in the /usr/share/ant/lib directory. I see a "ant-javamail-1.7.0.pom" file in this directory but not the appropriate jar file. Anyone know why this jar file might be missing and what the best way to resolve the problem is?
Here's what I ended up doing to resolve the problem: 1. Downloaded the latest version of Ant from <http://ant.apache.org/> 2. The "built-in" Ant is installed in /usr/share/ant; I didn't want to overwrite that version so I extracted the new, full version into /usr/***local***/share/apache-ant-1.7.1/ 3. As [npellow](https://stackoverflow.com/users/17333/npellow) points out, the the Mac doesn't include mail.jar or activation.jar -- these files can be downloaded and extracted from [JavaMail API](http://java.sun.com/products/javamail/downloads/index.html) and [JavaBeans Activation Framework](http://java.sun.com/products/javabeans/glasgow/jaf.html) respectively and copied to the *new* ant lib folder (same folder as all the ant-\*.jar files) 4. The ant command (/usr/bin/ant) is a symbolic link to /usr/share/ant/bin/ant; I updated this link to point to the new version (`ln -s /usr/local/share/apache-ant-1.7.1/bin/ant /usr/bin/ant`) If for some reason you need to make the old version of Ant the default again, just use `ln -s /usr/share/ant/bin/ant /usr/bin/ant` Steps 2-4 were done at the command prompt as root. That's it -- the Mac now has the latest, *complete* version of Ant and the Mail task works just fine.
Download the Java Mail libraries from: <http://java.sun.com/products/javamail/> . You will also need <http://java.sun.com/products/javabeans/glasgow/jaf.html> A list of all external dependencies required by Ant's optional tasks are outlined here <http://ant.apache.org/manual/index.html> . Another way to get dependencies for Ant very easily, is to run: ``` ant -f fetch all ``` from $ANT\_HOME. You can also run -projecthelp for a full list of targets: ``` all load all the libraries antlr load antlr libraries bcel load bcel libraries beanshell load beanshell support bsf load bsf libraries debugging internal ant debugging get-m2 Download the Maven2 Ant tasks jdepend load jdepend libraries jruby load jruby junit load junit libraries jython load jython logging load logging libraries networking load networking libraries (commons-net; jsch) regexp load regexp libraries rhino load rhino script load script languages xerces load an updated version of Xerces xml load full XML libraries (xalan, resolver) ```
Missing ant-javamail.jar file on Macintosh
[ "", "java", "macos", "ant", "" ]
Is it more efficient for a class to access member variables or local variables? For example, suppose you have a (callback) method whose sole responsibility is to receive data, perform calculations on it, then pass it off to other classes. Performance-wise, would it make more sense to have a list of member variables that the method populates as it receives data? Or just declare local variables each time the callback method is called? Assume this method would be called hundreds of times a second... In case I'm not being clear, here's some quick examples: ``` // use local variables class thisClass { public: void callback( msg& msg ) { int varA; double varB; std::string varC; varA = msg.getInt(); varB = msg.getDouble(); varC = msg.getString(); // do a bunch of calculations } }; // use member variables class thisClass { public: void callback( msg& msg ) { m_varA = msg.getInt(); m_varB = msg.getDouble(); m_varC = msg.getString(); // do a bunch of calculations } private: int m_varA; double m_varB; std::string m_varC; }; ```
Executive summary: In virtually all scenarios, it doesn't matter, but there is a slight advantage for local variables. Warning: You are micro-optimizing. You will end up spending hours trying to understand code that is supposed to win a nanosecond. Warning: In your scenario, performance shouldn't be the question, but the role of the variables - are they temporary, or state of thisClass? Warning: First, second and last rule of optimization: measure! --- First of all, look at the typical assembly generated for x86 (your platform may vary): ``` // stack variable: load into eax mov eax, [esp+10] // member variable: load into eax mov ecx, [adress of object] mov eax, [ecx+4] ``` Once the address of the object is loaded, int a register, the instructions are identical. Loading the object address can usually be paired with an earlier instruction and doesn't hit execution time. But this means the ecx register isn't available for other optimizations. *However*, modern CPUs do some intense trickery to make that less of an issue. Also, when accessing many objects this may cost you extra. *However*, this is less than one cycle average, and there are often more opprtunities for pairing instructions. Memory locality: here's a chance for the stack to win big time. Top of stack is virtually always in the L1 cache, so the load takes one cycle. The object is more likely to be pushed back to L2 cache (rule of thumb, 10 cycles) or main memory (100 cycles). *However*, you pay this only for the first access. if all you have is a single access, the 10 or 100 cycles are unnoticable. if you have thousands of accesses, the object data will be in L1 cache, too. In summary, the gain is so small that it virtually never makes sense to copy member variables into locals to achieve better performance.
I'd prefer the local variables on general principles, because they minimize evil mutable state in your program. As for performance, your profiler will tell you all you need to know. Locals should be faster for ints and perhaps other builtins, because they can be put in registers.
C++ performance of accessing member variables versus local variables
[ "", "c++", "performance", "" ]
Does the C++ compiler optimize the multiply by two operation `x*2` to a bitshift operation `x<<1`? I would love to believe that yes.
Actually VS2008 optimizes this to x+x: ``` 01391000 push ecx int x = 0; scanf("%d", &x); 01391001 lea eax,[esp] 01391004 push eax 01391005 push offset string "%d" (13920F4h) 0139100A mov dword ptr [esp+8],0 01391012 call dword ptr [__imp__scanf (13920A4h)] int y = x * 2; 01391018 mov ecx,dword ptr [esp+8] 0139101C lea edx,[ecx+ecx] ``` In an x64 build it is even more explicit and uses: ``` int y = x * 2; 000000013FB9101E mov edx,dword ptr [x] printf("%d", y); 000000013FB91022 lea rcx,[string "%d" (13FB921B0h)] 000000013FB91029 add edx,edx ``` This is will the optimization settings on 'Maximize speed' (/O2)
This article from Raymond Chen could be interesting: **When is x/2 different from x>>1?** : <http://blogs.msdn.com/oldnewthing/archive/2005/05/27/422551.aspx> Quoting Raymond: > > Of course, the compiler is free to recognize this and rewrite your multiplication or shift operation. In fact, it is very likely to do this, because x+x is more easily pairable than a multiplication or shift. Your shift or multiply-by-two is probably going to be rewritten as something closer to an add eax, eax instruction. > > > > [...] > > > > Even if you assume that the shift fills with the sign bit, The result of the shift and the divide are different if x is negative. > > > > (-1) / 2 ≑ 0 > > (-1) >> 1 ≑ -1 > > > > [...] > > > > **The moral of the story is to write what you mean. If you want to divide by two, then write "/2", not ">>1".** We can only assume it is wise to tell the compiler what you want, not what you want him to do: **The compiler is better than an human is at optimizing** small scale code (thanks for Daemin to point this subtle point): If you really want optimization, use a profiler, and study your algorithms' efficiency.
Do modern compilers optimize the x * 2 operation to x << 1?
[ "", "c++", "optimization", "compiler-construction", "" ]
I would like to be able to fetch a web page's html and save it to a `String`, so I can do some processing on it. Also, how could I handle various types of compression. How would I go about doing that using Java?
Here's some tested code using Java's [URL](http://java.sun.com/javase/6/docs/api/java/net/URL.html) class. I'd recommend do a better job than I do here of handling the exceptions or passing them up the call stack, though. ``` public static void main(String[] args) { URL url; InputStream is = null; BufferedReader br; String line; try { url = new URL("http://stackoverflow.com/"); is = url.openStream(); // throws an IOException br = new BufferedReader(new InputStreamReader(is)); while ((line = br.readLine()) != null) { System.out.println(line); } } catch (MalformedURLException mue) { mue.printStackTrace(); } catch (IOException ioe) { ioe.printStackTrace(); } finally { try { if (is != null) is.close(); } catch (IOException ioe) { // nothing to see here } } } ```
I'd use a decent HTML parser like [Jsoup](http://jsoup.org). It's then as easy as: ``` String html = Jsoup.connect("http://stackoverflow.com").get().html(); ``` It handles GZIP and chunked responses and character encoding fully transparently. It offers more advantages as well, like HTML [traversing](http://jsoup.org/cookbook/extracting-data/selector-syntax) and [manipulation](http://jsoup.org/cookbook/modifying-data/set-html) by CSS selectors like as jQuery can do. You only have to grab it as `Document`, not as a `String`. ``` Document document = Jsoup.connect("http://google.com").get(); ``` You really [don't](http://www.codinghorror.com/blog/2009/11/parsing-html-the-cthulhu-way.html) want to run basic String methods or even regex on HTML to process it. ### See also: * [What are the pros and cons of leading HTML parsers in Java?](https://stackoverflow.com/questions/3152138/what-are-the-pros-and-cons-of-the-leading-java-html-parsers)
How do you Programmatically Download a Webpage in Java
[ "", "java", "http", "compression", "" ]
What's the most efficient way to select the last n number of rows in a table using mySQL? The table contains millions of rows, and at any given time I don't know how large the table is (it is constantly growing). The table does have a column that is automatically incremented and used as a unique identifier for each row.
``` SELECT * FROM table_name ORDER BY auto_incremented_id DESC LIMIT n ```
Actually the right way to get last n rows in order is to use a subquery: ``` (SELECT id, title, description FROM my_table ORDER BY id DESC LIMIT 5) ORDER BY tbl.id ASC ``` As this way is the only I know that will return them in right order. The accepted answer is actually a solution for "*Select first 5 rows from a set ordered by descending ID*", but that is most probably what you need.
What's the most efficient way to select the last n rows in a table without changing the table's structure?
[ "", "mysql", "sql", "" ]
I'm trying to learn about catamorphisms and I've read [the Wikipedia article](http://en.wikipedia.org/wiki/Catamorphism) and the first couple posts in [the series of the topic for F#](http://lorgonblog.spaces.live.com/Blog/cns!701679AD17B6D310!256.entry) on the *Inside F#* blog. I understand that it's a generalization of folds (i.e., mapping a structure of many values to one value, including a list of values to another list). And I gather that the fold-list and fold-tree is a canonical example. Can this be shown to be done in C#, using LINQ's `Aggregate` operator or some other higher-order method?
LINQ's `Aggregate()` is just for `IEnumerables`. Catamorphisms in general refer to the pattern of folding for an arbitrary data type. So `Aggregate()` is to `IEnumerables` what `FoldTree` (below) is to `Trees` (below); both are catamorphisms for their respective data types. I translated some of the code in [part 4 of the series](http://lorgonblog.spaces.live.com/blog/cns!701679AD17B6D310!248.entry) into C#. The code is below. Note that the equivalent F# used three less-than characters (for generic type parameter annotations), whereas this C# code uses more than 60. This is evidence why no one writes such code in C# - there are too many type annotations. I present the code in case it helps people who know C# but not F# play with this. But the code is so dense in C#, it's very hard to make sense of. Given the following definition for a binary tree: ``` using System; using System.Collections.Generic; using System.Windows; using System.Windows.Controls; using System.Windows.Input; using System.Windows.Media; using System.Windows.Shapes; class Tree<T> // use null for Leaf { public T Data { get; private set; } public Tree<T> Left { get; private set; } public Tree<T> Right { get; private set; } public Tree(T data, Tree<T> left, Tree<T> rright) { this.Data = data; this.Left = left; this.Right = right; } public static Tree<T> Node<T>(T data, Tree<T> left, Tree<T> right) { return new Tree<T>(data, left, right); } } ``` One can fold trees and e.g. measure if two trees have different nodes: ``` class Tree { public static Tree<int> Tree7 = Node(4, Node(2, Node(1, null, null), Node(3, null, null)), Node(6, Node(5, null, null), Node(7, null, null))); public static R XFoldTree<A, R>(Func<A, R, R, Tree<A>, R> nodeF, Func<Tree<A>, R> leafV, Tree<A> tree) { return Loop(nodeF, leafV, tree, x => x); } public static R Loop<A, R>(Func<A, R, R, Tree<A>, R> nodeF, Func<Tree<A>, R> leafV, Tree<A> t, Func<R, R> cont) { if (t == null) return cont(leafV(t)); else return Loop(nodeF, leafV, t.Left, lacc => Loop(nodeF, leafV, t.Right, racc => cont(nodeF(t.Data, lacc, racc, t)))); } public static R FoldTree<A, R>(Func<A, R, R, R> nodeF, R leafV, Tree<A> tree) { return XFoldTree((x, l, r, _) => nodeF(x, l, r), _ => leafV, tree); } public static Func<Tree<A>, Tree<A>> XNode<A>(A x, Tree<A> l, Tree<A> r) { return (Tree<A> t) => x.Equals(t.Data) && l == t.Left && r == t.Right ? t : Node(x, l, r); } // DiffTree: Tree<'a> * Tree<'a> -> Tree<'a * bool> // return second tree with extra bool // the bool signifies whether the Node "ReferenceEquals" the first tree public static Tree<KeyValuePair<A, bool>> DiffTree<A>(Tree<A> tree, Tree<A> tree2) { return XFoldTree((A x, Func<Tree<A>, Tree<KeyValuePair<A, bool>>> l, Func<Tree<A>, Tree<KeyValuePair<A, bool>>> r, Tree<A> t) => (Tree<A> t2) => Node(new KeyValuePair<A, bool>(t2.Data, object.ReferenceEquals(t, t2)), l(t2.Left), r(t2.Right)), x => y => null, tree)(tree2); } } ``` In this second example, another tree is reconstructed differently: ``` class Example { // original version recreates entire tree, yuck public static Tree<int> Change5to0(Tree<int> tree) { return Tree.FoldTree((int x, Tree<int> l, Tree<int> r) => Tree.Node(x == 5 ? 0 : x, l, r), null, tree); } // here it is with XFold - same as original, only with Xs public static Tree<int> XChange5to0(Tree<int> tree) { return Tree.XFoldTree((int x, Tree<int> l, Tree<int> r, Tree<int> orig) => Tree.XNode(x == 5 ? 0 : x, l, r)(orig), _ => null, tree); } } ``` And in this third example, folding a tree is used for drawing: ``` class MyWPFWindow : Window { void Draw(Canvas canvas, Tree<KeyValuePair<int, bool>> tree) { // assumes canvas is normalized to 1.0 x 1.0 Tree.FoldTree((KeyValuePair<int, bool> kvp, Func<Transform, Transform> l, Func<Transform, Transform> r) => trans => { // current node in top half, centered left-to-right var tb = new TextBox(); tb.Width = 100.0; tb.Height = 100.0; tb.FontSize = 70.0; // the tree is a "diff tree" where the bool represents // "ReferenceEquals" differences, so color diffs Red tb.Foreground = (kvp.Value ? Brushes.Black : Brushes.Red); tb.HorizontalContentAlignment = HorizontalAlignment.Center; tb.VerticalContentAlignment = VerticalAlignment.Center; tb.RenderTransform = AddT(trans, TranslateT(0.25, 0.0, ScaleT(0.005, 0.005, new TransformGroup()))); tb.Text = kvp.Key.ToString(); canvas.Children.Add(tb); // left child in bottom-left quadrant l(AddT(trans, TranslateT(0.0, 0.5, ScaleT(0.5, 0.5, new TransformGroup())))); // right child in bottom-right quadrant r(AddT(trans, TranslateT(0.5, 0.5, ScaleT(0.5, 0.5, new TransformGroup())))); return null; }, _ => null, tree)(new TransformGroup()); } public MyWPFWindow(Tree<KeyValuePair<int, bool>> tree) { var canvas = new Canvas(); canvas.Width=1.0; canvas.Height=1.0; canvas.Background = Brushes.Blue; canvas.LayoutTransform=new ScaleTransform(200.0, 200.0); Draw(canvas, tree); this.Content = canvas; this.Title = "MyWPFWindow"; this.SizeToContent = SizeToContent.WidthAndHeight; } TransformGroup AddT(Transform t, TransformGroup tg) { tg.Children.Add(t); return tg; } TransformGroup ScaleT(double x, double y, TransformGroup tg) { tg.Children.Add(new ScaleTransform(x,y)); return tg; } TransformGroup TranslateT(double x, double y, TransformGroup tg) { tg.Children.Add(new TranslateTransform(x,y)); return tg; } [STAThread] static void Main(string[] args) { var app = new Application(); //app.Run(new MyWPFWindow(Tree.DiffTree(Tree.Tree7,Example.Change5to0(Tree.Tree7)))); app.Run(new MyWPFWindow(Tree.DiffTree(Tree.Tree7, Example.XChange5to0(Tree.Tree7)))); } } ```
I've been doing more reading, including a Micorosft Research paper on [functional programming with catamorphisms ("bananas")](http://research.microsoft.com/~emeijer/Papers/fpca91.pdf), and it seems that ***catamorphism*** just refers to any function that takes a list and typically breaks it down to a single value (`IEnumerable<A> => B`), like `Max()`, `Min()`, and in the general case, `Aggregate()`, would all be a catamorphisms for lists. I was previously under the impression that it refefred to a way of creating a function that can generalize different folds, so that it can fold a tree *and* a list. There may actually still be such a thing, some kind of *functor* or *arrow* maybe but right now that's beyond my level of understanding.
What is a catamorphism and can it be implemented in C# 3.0?
[ "", "c#", "f#", "functional-programming", "catamorphism", "recursion-schemes", "" ]
What would you recommend for class that needs to keep a list of unique integers? I'm going to want to Add() integers to the collection and also check for existence e.g. Contains(). Would be nice to also get them in a list as a string for display, ie. "1, 5, 10, 21".
[HashSet](http://msdn.microsoft.com/en-us/library/bb359438.aspx): > The `HashSet<T>` class provides high-performance set operations. A set is a collection that contains no duplicate elements, and whose elements are in no particular order... > > The capacity of a `HashSet<T>` object is the number of elements that the object can hold. A `HashSet<T>` object's capacity automatically increases as elements are added to the object. > > The `HashSet<T>` class is based on the model of mathematical sets and provides high-performance set operations similar to accessing the keys of the [`Dictionary<TKey, TValue>`](https://msdn.microsoft.com/en-us/library/xfhwa508.aspx) or [`Hashtable`](https://msdn.microsoft.com/en-us/library/system.collections.hashtable.aspx) collections. In simple terms, the `HashSet<T>` class can be thought of as a [`Dictionary<TKey, TValue>`](https://msdn.microsoft.com/en-us/library/xfhwa508.aspx) collection without values. > > A `HashSet<T>` collection is not sorted and cannot contain duplicate elements...
In my testing, I have found that a Dictionary with a dummy value is faster than a HashSet, when dealing with very large sets of data (100,000+ in my case). I expect this is because the Dictionary allows you to set an initial capacity, but I don't really know. In the case you're describing, I would probably use the Dictionary if I was expecting a very large set of numbers, and then (or as I was adding to the Dictionary, depending on the intent) iterate over it using a string builder, to create the output string.
Recommended .NET Class for a collection of unique integers?
[ "", "c#", ".net", "" ]
We all know you can't do the following because of `ConcurrentModificationException`: ``` for (Object i : l) { if (condition(i)) { l.remove(i); } } ``` But this apparently works sometimes, but not always. Here's some specific code: ``` public static void main(String[] args) { Collection<Integer> l = new ArrayList<>(); for (int i = 0; i < 10; ++i) { l.add(4); l.add(5); l.add(6); } for (int i : l) { if (i == 5) { l.remove(i); } } System.out.println(l); } ``` This, of course, results in: ``` Exception in thread "main" java.util.ConcurrentModificationException ``` Even though multiple threads aren't doing it. Anyway. What's the best solution to this problem? How can I remove an item from the collection in a loop without throwing this exception? I'm also using an arbitrary `Collection` here, not necessarily an `ArrayList`, so you can't rely on `get`.
[`Iterator.remove()`](https://docs.oracle.com/javase/9/docs/api/java/util/Iterator.html#remove--) is safe, you can use it like this: ``` List<String> list = new ArrayList<>(); // This is a clever way to create the iterator and call iterator.hasNext() like // you would do in a while-loop. It would be the same as doing: // Iterator<String> iterator = list.iterator(); // while (iterator.hasNext()) { for (Iterator<String> iterator = list.iterator(); iterator.hasNext();) { String string = iterator.next(); if (string.isEmpty()) { // Remove the current element from the iterator and the list. iterator.remove(); } } ``` Note that [`Iterator.remove()`](https://docs.oracle.com/javase/9/docs/api/java/util/Iterator.html#remove--) is the only safe way to modify a collection during iteration; the behavior is unspecified if the underlying collection is modified **in any other way** while the iteration is in progress. Source: [docs.oracle > The Collection Interface](http://docs.oracle.com/javase/tutorial/collections/interfaces/collection.html) --- And similarly, if you have a `ListIterator` and want to *add* items, you can use [`ListIterator#add`](http://docs.oracle.com/javase/8/docs/api/java/util/ListIterator.html#add-E-), for the same reason you can use `Iterator#remove`Β β€” it's designed to allow it. --- In your case you tried to remove from a list, but the same restriction applies if trying to `put` into a `Map` while iterating its content.
This works: ``` Iterator<Integer> iter = l.iterator(); while (iter.hasNext()) { if (iter.next() == 5) { iter.remove(); } } ``` I assumed that since a foreach loop is syntactic sugar for iterating, using an iterator wouldn't help... but it gives you this `.remove()` functionality.
Iterating through a Collection, avoiding ConcurrentModificationException when removing objects in a loop
[ "", "java", "collections", "iteration", "" ]
I've figured out how to set VC++ to compile code into a .lib file instead of a .exe, but I'm having trouble getting a lib to link together with my other .obj files. Here is how I have the library and application folders set up. (I'm not sure if this is right) ``` AppFolder App.sln App.ncb *.h *.cpp Debug *.obj App.exe ``` and somewhere else on the hard drive... ``` LibraryFolder lib Library.lib include LibrarySolutionFolder Library.sln Library.ncb *.h *.cpp Debug *.obj Library.lib ``` I've been #including the library \*.h files from my app's cpp files, and everything compiles fine. It's just when it links I get a list of all the .lib files that are being searched, and Library.lib isn't on there even though I have it listed in VC++ directories. How can I get this to link? (And am I structuring the library folders correctly?)
On the project properties: Configuration Properties -> Linker -> Input -> Additional Dependancies Add it in there. Or, in your .h file for the library, add: ``` #pragma comment(lib, "Library") ``` This will do it automatically for you.
The VC++ directories is the list of directory locations to searched during linking. It is not a list of libraries to be linked in. You need to add the lib file to the ***Additional Dependencies*** field of the ***Project Linker*** settings.
Having trouble linking a static library C++
[ "", "c++", "static", "linker", "" ]
I have the following code: ``` class IncidentTag: def __init__(self,tag): self.tag = tag def equals(self,obj): return self.tag.equals(obj.tag) def hashCode(self): return self.tag.hashCode() from java.lang import String from java.util import HashMap from java.util import HashSet tag1 = IncidentTag(String("email")) tag1copy = IncidentTag(String("email")) tag2 = IncidentTag(String("notemail")) print tag1.equals(tag1copy) print tag2.equals(tag2) print "Now with HashSet:" hSet = HashSet() hSet.add(tag1) hSet.add(tag2) print hSet.contains(tag1) print hSet.contains(tag2) print hSet.contains(tag1copy) ``` The output is: 1 1 Now with HashSet: 1 1 0 However, I would have expected the last line to be `true`(1) as well. Is there something obvious that I am missing. (yes, I know that my `equals` method and `hashcode` methods do not take some issues into account... they are deliberately simple, but do let me know if the issues there are causing this problem.)
You shouldn't implemented the Java-Style equals and hashCode method, but instead the Python equivaltents `__eq__` and `__hash__`. Adding ``` def __hash__(self): return self.hashCode() def __eq__(self, o): return self.equals(o) ``` helps. These python methods are - as far as I know - dynamically bound to hashCode and equals() by Jython. This ensures that you can put Python classes into Java's collections. Now the code prints five "1".
I wrote equivalent code in Java and it does produce true for all three contains() calls. So I think this must be an oddity in Jython. Maybe the underlying Java objects are not exactly what you see them as in Python.
HashSet problem -- equals and hashCode with contains working differently than I'd expect
[ "", "java", "collections", "jython", "hashset", "" ]
I am trying to sort a list using delegates but I am getting a signature match error. The compiler says I cannot convert from an 'anonymous method' ``` List<MyType> myList = GetMyList(); myList.Sort( delegate (MyType t1, MyType t2) { return (t1.ID < t2.ID); } ); ``` What am I missing? Here are some references I found and they do it the same way. [Developer Fusion Reference](http://www.developerfusion.com/code/5513/sorting-and-searching-using-c-lists/) [Microsoft Reference](http://blogs.msdn.com/devdev/archive/2006/06/30/652802.aspx)
I think you want: ``` myList.Sort( delegate (MyType t1, MyType t2) { return (t1.ID.CompareTo(t2.ID)); } ); ``` To sort you need something other than "true/false", you need to know if its equal to, greater than, or less than.
The Sort doesn't take a binary predicate, it takes a `Comparison<T>` delegate which returns an `int` not a `bool`. The return values are `0` for when the items are equal, `<0` for when the first item is less than the second, and `>0` for when the first item is greater than the second.
Problem sorting lists using delegates
[ "", "c#", ".net", "closures", "" ]
Here's the XML code I'm working with: ``` <inventory> <drink> <lemonade supplier="mother" id="1"> <price>$2.50</price> <amount>20</amount> </lemonade> <lemonade supplier="mike" id="4"> <price>$3.00</price> <amount>20</amount> </lemonade> <pop supplier="store" id="2"> <price>$1.50</price> <amount>10</amount> </pop> </drink> </inventory> ``` Then I wrote a simple code to practice working with XPath: ``` <?php $xmldoc = new DOMDocument(); $xmldoc->load('sample.xml'); $xpathvar = new Domxpath($xmldoc); $queryResult = $xpathvar->query('//lemonade/price'); foreach($queryResult as $result) { echo $result->textContent; } ?> ``` That code is working well, outputting all the lemonade price values as expected. Now when i change the query string to select only the elements with an attribute set to a certain value, like > //lemonade[supplier="mother"]/price or > //lemonade[id="1"]/price it won't work, no output at all. What am i doing wrong?
Try this: ``` //lemonade[@id="1"]/price ``` or ``` //lemonade[@supplier="mother"]/price ``` Without the "@" it looks for child elements with that name instead of attributes.
This is only tangentially related, but when you use XPath on a document for which you know the structure, *don't* use "//some-element-name". It's very nice for a quick example, but when you hit a huge xml file with that query, particularly if it is followed by something complex, you will quickly run into performance issues. inventory/drink/lemonade[@supplier="mother"]/price
XPath query with PHP
[ "", "php", "xml", "xpath", "" ]
Is there a way to create an instance of a class based on the fact I know the name of the class at runtime. Basically I would have the name of the class in a string.
Take a look at the [Activator.CreateInstance](http://msdn.microsoft.com/en-us/library/system.activator.createinstance.aspx) method.
Its pretty simple. Assume that your classname is `Car` and the namespace is `Vehicles`, then pass the parameter as `Vehicles.Car` which returns object of type `Car`. Like this you can create any instance of any class dynamically. ``` public object GetInstance(string strFullyQualifiedName) { Type t = Type.GetType(strFullyQualifiedName); return Activator.CreateInstance(t); } ``` If your [Fully Qualified Name](https://msdn.microsoft.com/en-us/library/dfb3cx8s%28v=vs.71%29.aspx)(ie, `Vehicles.Car` in this case) is in another assembly, the `Type.GetType` will be null. In such cases, you have loop through all assemblies and find the `Type`. For that you can use the below code ``` public object GetInstance(string strFullyQualifiedName) { Type type = Type.GetType(strFullyQualifiedName); if (type != null) return Activator.CreateInstance(type); foreach (var asm in AppDomain.CurrentDomain.GetAssemblies()) { type = asm.GetType(strFullyQualifiedName); if (type != null) return Activator.CreateInstance(type); } return null; } ``` Now if you want to call a **parameterized constructor** do the following ``` Activator.CreateInstance(t,17); // Incase you are calling a constructor of int type ``` instead of ``` Activator.CreateInstance(t); ```
Create an instance of a class from a string
[ "", "c#", ".net", "instantiation", "system.type", "" ]
Without routing, `HttpContext.Current.Session` is there so I know that the `StateServer` is working. When I route my requests, `HttpContext.Current.Session` is `null` in the routed page. I am using .NET 3.5 sp1 on IIS 7.0, without the MVC previews. It appears that `AcquireRequestState` is never fired when using the routes and so the session variable isn't instantiated/filled. When I try to access the Session variables, I get this error: `base {System.Runtime.InteropServices.ExternalException} = {"Session state can only be used when enableSessionState is set to true, either in a configuration file or in the Page directive. Please also make sure that System.Web.SessionStateModule or a custom session state module is included in the <configuration>.` While debugging, I also get the error that the `HttpContext.Current.Session` is not accessible in that context. -- My `web.config` looks like this: ``` <configuration> ... <system.web> <pages enableSessionState="true"> <controls> ... </controls> </pages> ... </system.web> <sessionState cookieless="AutoDetect" mode="StateServer" timeout="22" /> ... </configuration> ``` Here's the IRouteHandler implementation: ``` public class WebPageRouteHandler : IRouteHandler, IRequiresSessionState { public string m_VirtualPath { get; private set; } public bool m_CheckPhysicalUrlAccess { get; set; } public WebPageRouteHandler(string virtualPath) : this(virtualPath, false) { } public WebPageRouteHandler(string virtualPath, bool checkPhysicalUrlAccess) { m_VirtualPath = virtualPath; m_CheckPhysicalUrlAccess = checkPhysicalUrlAccess; } public IHttpHandler GetHttpHandler(RequestContext requestContext) { if (m_CheckPhysicalUrlAccess && !UrlAuthorizationModule.CheckUrlAccessForPrincipal( m_VirtualPath, requestContext.HttpContext.User, requestContext.HttpContext.Request.HttpMethod)) { throw new SecurityException(); } string var = String.Empty; foreach (var value in requestContext.RouteData.Values) { requestContext.HttpContext.Items[value.Key] = value.Value; } Page page = BuildManager.CreateInstanceFromVirtualPath( m_VirtualPath, typeof(Page)) as Page;// IHttpHandler; if (page != null) { return page; } return page; } } ``` I've also tried to put `EnableSessionState="True"` on the top of the aspx pages but still, nothing. Any insights? Should I write another `HttpRequestHandler` that implements `IRequiresSessionState`? Thanks.
Got it. Quite stupid, actually. It worked after I removed & added the SessionStateModule like so: ``` <configuration> ... <system.webServer> ... <modules> <remove name="Session" /> <add name="Session" type="System.Web.SessionState.SessionStateModule"/> ... </modules> </system.webServer> </configuration> ``` Simply adding it won't work since "Session" should have already been defined in the `machine.config`. Now, I wonder if that is the usual thing to do. It surely doesn't seem so since it seems so crude...
Just add attribute `runAllManagedModulesForAllRequests="true"` to `system.webServer\modules` in web.config. This attribute is enabled by default in MVC and Dynamic Data projects.
HttpContext.Current.Session is null when routing requests
[ "", "c#", "asp.net", "routes", "session-variables", "" ]
Is there a class in the standard library of .NET that gives me the functionality to create random variables that follow Gaussian distribution?
Jarrett's suggestion of using a Box-Muller transform is good for a quick-and-dirty solution. A simple implementation: ``` Random rand = new Random(); //reuse this if you are generating many double u1 = 1.0-rand.NextDouble(); //uniform(0,1] random doubles double u2 = 1.0-rand.NextDouble(); double randStdNormal = Math.Sqrt(-2.0 * Math.Log(u1)) * Math.Sin(2.0 * Math.PI * u2); //random normal(0,1) double randNormal = mean + stdDev * randStdNormal; //random normal(mean,stdDev^2) ```
This question appears to have moved on top of Google for .NET Gaussian generation, so I figured I'd post an answer. I've made some [extension methods for the .NET Random class](https://bitbucket.org/Superbest/superbest-random), including an implementation of the Box-Muller transform. Since they're extensions, so long as the project is included (or you reference the compiled DLL), you can still do ``` var r = new Random(); var x = r.NextGaussian(); ``` Hope nobody minds the shameless plug. Sample histogram of results (a demo app for drawing this is included): ![enter image description here](https://i.stack.imgur.com/Np1ed.png)
Random Gaussian Variables
[ "", "c#", ".net", "" ]
Sometime I see many application such as msn, windows media player etc that are single instance applications (when user executes while application is running a new application instance will not created). In C#, I use `Mutex` class for this but I don't know how to do this in Java.
If I believe this [article](http://www.rbgrn.net/blog/2008/05/java-single-application-instance.html), by : > having the first instance attempt to open a listening socket on the localhost interface. If it's able to open the socket, it is assumed that this is the first instance of the application to be launched. If not, the assumption is that an instance of this application is already running. The new instance must notify the existing instance that a launch was attempted, then exit. The existing instance takes over after receiving the notification and fires an event to the listener that handles the action. Note: [Ahe](https://stackoverflow.com/users/4427/ahe) mentions in the comment that using `InetAddress.getLocalHost()` can be tricky: > * it does not work as expected in DHCP-environment because address returned depends on whether the computer has network access. > Solution was to open connection with **`InetAddress.getByAddress(new byte[] {127, 0, 0, 1})`**; > Probably related to [bug 4435662](https://bugs.java.com/bugdatabase/view_bug?bug_id=4435662). * I also found [bug 4665037](https://bugs.java.com/bugdatabase/view_bug?bug_id=4665037) which reports than Expected results of `getLocalHost`: return IP address of machine, vs. Actual results : return `127.0.0.1`. > it is surprising to have `getLocalHost` return `127.0.0.1` on Linux but not on windows. --- Or you may use [`ManagementFactory`](http://web.archive.org/web/20090529082521/http://www.trap17.com/index.php/how-implement-single-instance-application-java_t59760.html) object. As explained [here](http://web.archive.org/web/20081203154345/http://www.trap17.com/forums/how-implement-single-instance-application-java-t59760.html): > The `getMonitoredVMs(int processPid)` method receives as parameter the current application PID, and catch the application name that is called from command line, for example, the application was started from `c:\java\app\test.jar` path, then the value variable is "`c:\\java\\app\\test.jar`". This way, we will catch just application name on the line 17 of the code below. > After that, we search JVM for another process with the same name, if we found it and the application PID is different, it means that is the second application instance. JNLP offers also a [`SingleInstanceListener`](http://forums.sun.com/thread.jspa?messageID=9509621)
I use the following method in the main method. This is the simplest, most robust, and least intrusive method I have seen so I thought that I'd share it. ``` private static boolean lockInstance(final String lockFile) { try { final File file = new File(lockFile); final RandomAccessFile randomAccessFile = new RandomAccessFile(file, "rw"); final FileLock fileLock = randomAccessFile.getChannel().tryLock(); if (fileLock != null) { Runtime.getRuntime().addShutdownHook(new Thread() { public void run() { try { fileLock.release(); randomAccessFile.close(); file.delete(); } catch (Exception e) { log.error("Unable to remove lock file: " + lockFile, e); } } }); return true; } } catch (Exception e) { log.error("Unable to create and/or lock file: " + lockFile, e); } return false; } ```
How to implement a single instance Java application?
[ "", "java", "single-instance", "" ]
I am using a List Control to display a representation of elements within a vector. When the list is clicked on another control shows information about that element. The index of the element is currently determined by its index in the control, however if I wish to sort or filter the results this will no longer work. I have been told that I could use a virtual list control, but the MSDN is not very friendly, can someone run me through how I could use a virtual list control for this?
Frankly - tying data (the position in your data vector) to the presentation of the data in the list control (the position in the list ctrl) is something I would stay away from. In MFC each control has a "Data" DWORD member variable - when coding in MFC I Always called "SetItemData" for each item added and passed in a pointer that the relevant row referred to e.g. `YourListCtrl.SetItemData((DWORDPTR)&YourData);` Then when the ListCtrl item is selected, you just call `DataTypeYouWant* pData = (DataTypeYouWant*)(YourListCtrl.GetItemData(indexofselecteditem));` Or somesuch thing. Alternatively - if you don't want to use pointers - hold the index of the item in your original vector in the itemdata for your row (just pass it into the above fns).
The purpose of virtual list controls is totally different: You should use it for performance reason when you have A LOT of items in your list (I'd say 2500+). In your case, all you need is to store the vector index in the list item data as NotJarvis explains.
Virtual List Controls (MFC)
[ "", "c++", "windows", "user-interface", "mfc", "controls", "" ]
Please write a list of tasks that a copy constructor and assignment operator need to do in C++ to keep exception safety, avoid memory leaks etc.
First be sure you really need to support copy. Most of the time it is not the case, and thus disabling both is the way to go. Sometimes, you'll still need to provide duplication on a class from a polymorphic hierarchy, in that case: disable the assignment operator, write a (protected?) copy constructor, and provide a virtual clone() function. Otherwise, in the case you are writing a value class, you're back into the land of the Orthogonal Canonical Form of Coplien. If you have a member that can't be trivially copied, you'll need to provide a copy-constructor, a destructor, an assignment-operator and a default constructor. This rule can be refined, see for instance: [The Law of The Big Two](http://www.artima.com/cppsource/bigtwo.html) I'd also recommend to have a look at [C++ FAQ regarding assignment operators](http://www.parashift.com/c++-faq/assignment-operators.html), and at the [copy-and-swap idiom](http://en.wikibooks.org/wiki/More_C%2B%2B_Idioms/Copy-and-swap) and at [GOTW](http://www.gotw.ca/gotw/059.htm).
The compiler generated versions work in most situations. You need to think a bit harder about the problem when your object contains a RAW pointer (an argument for not having RAW pointers). So you have a RAW pointer, the second question is do you own the pointer (is it being deleted by you)? If so then you will need to apply the rule of 4. Owning more than 1 RAW pointer becomes increasingly hard to do correctly (The increase in complexity is not linear either [but that is observational and I have no real stats to back that statement up]). So if you have more than 1 RAW pointer think about wrapping each in its own class (some form of smart pointer). Rule of 4: If an object is the owner of a RAW pointer then you need to define the following 4 members to make sure you handle the memory management correctly: * Constructor * Copy Constructor * Assignment Operator * Destructor How you define these will depend on the situations. But things to watch out for: * Default Construction: Set pointer to NULL * Copy Constructor: Use the Copy and Swap ideum to provide to the "Strong Exception Guarantee" * Assignment operator: Check for assignment to self * Destructor: Guard against exceptions propagating out of the destructor.
Checklist for writing copy constructor and assignment operator in C++
[ "", "c++", "copy-constructor", "assignment-operator", "" ]
Is it possible, with Javascript or some other technology to determine which hyperlink a user has clicked on, without changing the hyperlink source code. For example: Can you click on a 'tag' button, then click on a hyperlink hosted in a different iframe, and be able to calculate which hyperlink the user clicked on, without changing any of the source code in that iframe?
Using jQuery, you are able to set the context of your selection. i.e. $('a', $('#iframe-id')).click(function() {...}); You can then implement an event handler that will handle the iFrame hyperlink clicks. The *"this"* property within the handler will allow you to interrogate the hyperlink and obtain properties such as innerText etc.
you need to put an event on each a link , and then you will get all the information about the specific click. this will work only in the some document, so if you try to do a test between the link inside an iframe and a link in your page you will not get an event for the iframe link. in order to attach the event for all link you need to run on all the links in the page , the best way to do that is by jQuery selector. or other js framework like YUI $("a").click(function () { alert('') }); getElementsByTagName("a") - will give you all the links in the page.
How do you determine html clicked on with javascript?
[ "", "javascript", "" ]
We are monitoring the progress of a customized app (whose source is not under our control) which writes to a XML Manifest. At times , the application is stuck due to unable to write into the Manifest file. Although we are covering our traces by explicitly closing the file handle using File.Close and also creating the file variables in Using Blocks. But somehow it keeps happening. ( Our application is multithreaded and at most three threads might be accessing the file. ) Another interesting thing is that their app updates this manifest at three different events(add items, deleting items, completion of items) but we are only suffering about one event (completion of items). My code is listed here ``` using (var st = new FileStream(MenifestPath, FileMode.Open, FileAccess.Read)) { using (TextReader r = new StreamReader(st)) { var xml = r.ReadToEnd(); r.Close(); st.Close(); //................ Rest of our operations } } ```
If you are only reading from the file, then you should be able to pass a flag to specify the sharing mode. I don't know how you specify this in .NET, but in WinAPI you'd pass `FILE_SHARE_READ | FILE_SHARE_WRITE` to `CreateFile()`. I suggest you check your file API documentation to see where it mentions sharing modes.
Two things: 1. You should do the rest of your operations outside the scopes of the `using` statements. This way, you won't risk using the closed stream and reader. Also, you needn't use the `Close` methods, because when you exit the scope of the `using` statement, `Dispose` is called, which is equivalent. 2. You should use the overload that has the `FileShare` enumeration. Locking is paranoid in nature, so the file may be locked automatically to protect you from yourself. :) HTH.
How to avoid File Blocking
[ "", "c#", ".net", "multithreading", "file-io", "" ]
I have a series of ASCII flat files coming in from a mainframe to be processed by a C# application. A new feed has been introduced with a Packed Decimal (COMP-3) field, which needs to be converted to a numerical value. The files are being transferred via FTP, using ASCII transfer mode. I am concerned that the binary field may contain what will be interpreted as very-low ASCII codes or control characters instead of a value - Or worse, may be lost in the FTP process. What's more, the fields are being read as strings. I may have the flexibility to work around this part (i.e. a stream of some sort), but the business will give me pushback. The requirement read "Convert from HEX to ASCII", but clearly that didn't yield the correct values. Any help would be appreciated; it need not be language-specific as long as you can explain the logic of the conversion process.
First of all you must eliminate the end of line (EOL) translation problems that will be caused by ASCII transfer mode. You are absolutely right to be concerned about data corruption when the BCD values happen to correspond to EOL characters. The worst aspect of this problem is that it will occur rarely and unexpectedly. The best solution is to change the transfer mode to BIN. This is appropriate since the data you are transferring is binary. If it is not possible to use the correct FTP transfer mode, you can undo the ASCII mode damage in code. All you have to do is convert \r\n pairs back to \n. If I were you I would make sure this is well tested. Once you've dealt with the EOL problem, the COMP-3 conversion is pretty straigtforward. I was able to find [this article](http://support.microsoft.com/kb/65323) in the MS knowledgebase with sample code in BASIC. See below for a VB.NET port of this code. Since you're dealing with COMP-3 values, the file format you're reading almost surely has fixed record sizes with fixed field lengths. If I were you, I would get my hands of a file format specification before you go any further with this. You should be using a BinaryReader to work with this data. If someone is pushing back on this point, I would walk away. Let them find someone else to indulge their folly. Here's a VB.NET port of the BASIC sample code. I haven't tested this because I don't have access to a COMP-3 file. If this doesn't work, I would refer back to the original MS sample code for guidance, or to references in the other answers to this question. ``` Imports Microsoft.VisualBasic Module Module1 'Sample COMP-3 conversion code 'Adapted from http://support.microsoft.com/kb/65323 'This code has not been tested Sub Main() Dim Digits%(15) 'Holds the digits for each number (max = 16). Dim Basiceqv#(1000) 'Holds the Basic equivalent of each COMP-3 number. 'Added to make code compile Dim MyByte As Char, HighPower%, HighNibble% Dim LowNibble%, Digit%, E%, Decimal%, FileName$ 'Clear the screen, get the filename and the amount of decimal places 'desired for each number, and open the file for sequential input: FileName$ = InputBox("Enter the COBOL data file name: ") Decimal% = InputBox("Enter the number of decimal places desired: ") FileOpen(1, FileName$, OpenMode.Binary) Do Until EOF(1) 'Loop until the end of the file is reached. Input(1, MyByte) If MyByte = Chr(0) Then 'Check if byte is 0 (ASC won't work on 0). Digits%(HighPower%) = 0 'Make next two digits 0. Increment Digits%(HighPower% + 1) = 0 'the high power to reflect the HighPower% = HighPower% + 2 'number of digits in the number 'plus 1. Else HighNibble% = Asc(MyByte) \ 16 'Extract the high and low LowNibble% = Asc(MyByte) And &HF 'nibbles from the byte. The Digits%(HighPower%) = HighNibble% 'high nibble will always be a 'digit. If LowNibble% <= 9 Then 'If low nibble is a 'digit, assign it and Digits%(HighPower% + 1) = LowNibble% 'increment the high HighPower% = HighPower% + 2 'power accordingly. Else HighPower% = HighPower% + 1 'Low nibble was not a digit but a Digit% = 0 '+ or - signals end of number. 'Start at the highest power of 10 for the number and multiply 'each digit by the power of 10 place it occupies. For Power% = (HighPower% - 1) To 0 Step -1 Basiceqv#(E%) = Basiceqv#(E%) + (Digits%(Digit%) * (10 ^ Power%)) Digit% = Digit% + 1 Next 'If the sign read was negative, make the number negative. If LowNibble% = 13 Then Basiceqv#(E%) = Basiceqv#(E%) - (2 * Basiceqv#(E%)) End If 'Give the number the desired amount of decimal places, print 'the number, increment E% to point to the next number to be 'converted, and reinitialize the highest power. Basiceqv#(E%) = Basiceqv#(E%) / (10 ^ Decimal%) Print(Basiceqv#(E%)) E% = E% + 1 HighPower% = 0 End If End If Loop FileClose() 'Close the COBOL data file, and end. End Sub End Module ```
I have been watching the posts on numerous boards concerning converting Comp-3 BCD data from "legacy" mainframe files to something useable in C#. First, I would like to say that I am less than enamoured by the responses that some of these posts have received - especially those that have said essentially "why are you bothering us with these non-C#/C++ related posts" and also "If you need an answer about some sort of COBOL convention, why don't you go visit a COBOL oriented site". This, to me, is complete BS as there is going to be a need for probably many years to come, (unfortunately), for software developers to understand how to deal with some of these legacy issues that exist in THE REAL WORLD. So, even if I get slammed on this post for the following code, I am going to share with you a REAL WORLD experience that I had to deal with regarding COMP-3/EBCDIC conversion (and yes, I am he who talks of "floppy disks, paper-tape, Disc Packs etc... - I have been a software engineer since 1979"). First - understand that any file that you read from a legacy main-frame system like IBM is going to present the data to you in EBCDIC format and in order to convert any of that data to a C#/C++ string you can deal with you are going to have to use the proper code page translation to get the data into ASCII format. A good example of how to handle this would be: StreamReader readFile = new StreamReader(path, Encoding.GetEncoding(037); // 037 = EBCDIC to ASCII translation. This will ensure that anything that you read from this stream will then be converted to ASCII and can be used in a string format. This includes "Zoned Decimal" (Pic 9) and "Text" (Pic X) fields as declared by COBOL. However, this does not necessarily convert COMP-3 fields to the correct "binary" equivelant when read into a char[] or byte[] array. To do this, the only way that you are ever going to get this translated properly (even using UTF-8, UTF-16, Default or whatever) code pages, you are going to want to open the file like this: FileStream fileStream = new FileStream(path, FIleMode.Open, FIleAccess.Read, FileShare.Read); Of course, the "FileShare.Read" option is "optional". When you have isolated the field that you want to convert to a decimal value (and then subsequently to an ASCII string if need be), you can use the following code - and this has been basically stolen from the MicroSoft "UnpackDecimal" posting that you can get at: <http://www.microsoft.com/downloads/details.aspx?familyid=0e4bba52-cc52-4d89-8590-cda297ff7fbd&displaylang=en> I have isolated (I think) what are the most important parts of this logic and consolidated it into two a method that you can do with what you want. For my purposes, I chose to leave this as returning a Decimal value which I could then do with what I wanted. Basically, the method is called "unpack" and you pass it a byte[] array (no longer than 12 bytes) and the scale as an int, which is the number of decimal places you want to have returned in the Decimal value. I hope this works for you as well as it did for me. ``` private Decimal Unpack(byte[] inp, int scale) { long lo = 0; long mid = 0; long hi = 0; bool isNegative; // this nybble stores only the sign, not a digit. // "C" hex is positive, "D" hex is negative, and "F" hex is unsigned. switch (nibble(inp, 0)) { case 0x0D: isNegative = true; break; case 0x0F: case 0x0C: isNegative = false; break; default: throw new Exception("Bad sign nibble"); } long intermediate; long carry; long digit; for (int j = inp.Length * 2 - 1; j > 0; j--) { // multiply by 10 intermediate = lo * 10; lo = intermediate & 0xffffffff; carry = intermediate >> 32; intermediate = mid * 10 + carry; mid = intermediate & 0xffffffff; carry = intermediate >> 32; intermediate = hi * 10 + carry; hi = intermediate & 0xffffffff; carry = intermediate >> 32; // By limiting input length to 14, we ensure overflow will never occur digit = nibble(inp, j); if (digit > 9) { throw new Exception("Bad digit"); } intermediate = lo + digit; lo = intermediate & 0xffffffff; carry = intermediate >> 32; if (carry > 0) { intermediate = mid + carry; mid = intermediate & 0xffffffff; carry = intermediate >> 32; if (carry > 0) { intermediate = hi + carry; hi = intermediate & 0xffffffff; carry = intermediate >> 32; // carry should never be non-zero. Back up with validation } } } return new Decimal((int)lo, (int)mid, (int)hi, isNegative, (byte)scale); } private int nibble(byte[] inp, int nibbleNo) { int b = inp[inp.Length - 1 - nibbleNo / 2]; return (nibbleNo % 2 == 0) ? (b & 0x0000000F) : (b >> 4); } ``` If you have any questions, post them on here - because I suspect that I am going to get "flamed" like everyone else who has chosen to post questions that are pertinent to todays issues... Thanks, John - The Elder.
C#: Convert COMP-3 Packed Decimal to Human-Readable Value
[ "", "c#", ".net", "ibm-midrange", "flat-file", "comp-3", "" ]
One thing that always been a pain is to log SQL (JDBC) errors when you have a PreparedStatement instead of the query itself. You always end up with messages like: ``` 2008-10-20 09:19:48,114 ERROR LoggingQueueConsumer-52 [Logger.error:168] Error executing SQL: [INSERT INTO private_rooms_bans (room_id, name, user_id, msisdn, nickname) VALUES (?, ?, ?, ?, ?) ON DUPLICATE KEY UPDATE room_id = ?, name = ?, user_id = ?, msisdn = ?, nickname = ?] ``` Of course I could write a helper method for retrieving the values and parsing/substitute the question marks with real values (and probably will go down that path if I don't get an outcome of this question), but I just wanted to know if this problem was resolved before by someone else and/or if is there any generic logging helper that would do that automagically for me. **Edited after a few answers:** The libraries provided so far seems to be suitable to logging the statements for debugging, which no doubt is useful. However, I am looking to a way of taking a PreparedStatement itself (not some subclass) and logging its SQL statement whenever an error occur. I wouldn't like to deploy a production app with an alternate implementation of PreparedStatement. I guess what I am looking for an utility class, not a PreparedStatement specialization. Thanks!
I tried [log4jdbc](http://code.google.com/p/log4jdbc/) and it did the job for me. *SECURITY NOTE: As of today August 2011, the logged results of a log4jdbc prepared statement are NOT SAFE to execute. They can be used for analysis, but should NEVER be fed back into a DBMS.* **Example** of log generated by logjdbc: > 2010/08/12 16:30:56 jdbc.sqlonly > org.apache.commons.dbcp.DelegatingPreparedStatement.executeUpdate(DelegatingPreparedStatement.java:105) > 8. INSERT INTO A\_TABLE > (ID\_FILE,CODE1,ID\_G,ID\_SEQUENCE,REF,NAME,BAR,DRINK\_ID,AMOUNT,DESCRIPTION,STATUS,CODE2,REJECT\_DESCR,ID\_CUST\_REJ) > VALUES > (2,'123',1,'2','aa','awe',null,'0123',4317.95,'Rccc','0',null,null,null) The library is very easy to setup: --- My configuration with **HSQLDB** : ``` jdbc.url=jdbc:log4jdbc:hsqldb:mem:sample ``` With **Oracle** : ``` jdbc.url=jdbc:log4jdbc:oracle:thin:@mybdd:1521:smt jdbc.driverClass=net.sf.log4jdbc.DriverSpy ``` logback.xml : ``` <logger name="jdbc.sqlonly" level="DEBUG"/> ``` Too bad it wasn't on a maven repository, but still useful. From what I tried, if you set You will only get the statements in error, however, I don't know if this library has an impact on performance.
This is very database-dependent. For example, I understand that some JDBC drivers (e.g. sybase, maybe ms-sql) handle prepared statements by create a temporary stored procedure on the server, and then invoking that procedure with the supplied arguments. So the complete SQL is never actually passed from the client. As a result, the JDBC API does not expose the information you are after. You may be able to cast your statement objects the internal driver implementation, but probably not - your appserver may well wrap the statements in its own implementation. I think you may just have to bite the bullet and write your own class which interpolates the arguments into the placeholder SQL. This will be awkward, because you can't ask PreparedStatement for the parameters that have been set, so you'll have to remember them in a helper object, before passing them to the statement. It seems to me that one of the utility libraries which wrap your driver's implementation objects is the most practical way of doing what you're trying to achieve, but it's going to be unpleasant either way.
Logging PreparedStatements in Java
[ "", "java", "logging", "jdbc", "prepared-statement", "" ]
I'm working on a configuration script for a JNI wrapper. One of the configuration parameters is the path to `jni.h`. What's a good quick-and-dirty Autoconf test for whether this parameter is set correctly for C++ compilation? You can assume you're running on Linux and `g++` is available. Alternatively, is there a way to get `javah` (or a supporting tool) to give me this path directly?
Checking for headers is easy; just use `AC_CHECK_HEADER`. If it's in a weird place (i.e., one the compiler doesn't know about), it's entirely reasonable to expect users to set `CPPFLAGS`. The hard part is actually locating `libjvm`. You typically don't want to link with this; but you may want to default to a location to `dlopen` it from if `JAVA_HOME` is not set at run time. But I don't have a better solution than requiring that `JAVA_HOME` be set at configure time. There's just too much variation in how this stuff is deployed across various OSes (even just Linux distributions). This is what I do: ``` AC_CHECK_HEADER([jni.h], [have_jni=yes]) AC_ARG_VAR([JAVA_HOME], [Java Runtime Environment (JRE) location]) AC_ARG_ENABLE([java-feature], [AC_HELP_STRING([--disable-java-feature], [disable Java feature])]) case $target_cpu in x86_64) JVM_ARCH=amd64 ;; i?86) JVM_ARCH=i386 ;; *) JVM_ARCH=$target_cpu ;; esac AC_SUBST([JVM_ARCH]) AS_IF([test X$enable_java_feature != Xno], [AS_IF([test X$have_jni != Xyes], [AC_MSG_FAILURE([The Java Native Interface is required for Java feature.])]) AS_IF([test -z "$JAVA_HOME"], [AC_MSG_WARN([JAVA_HOME has not been set. JAVA_HOME must be set at run time to locate libjvm.])], [save_LDFLAGS=$LDFLAGS LDFLAGS="-L$JAVA_HOME/lib/$JVM_ARCH/client -L$JAVA_HOME/lib/$JVM_ARCH/server $LDFLAGS" AC_CHECK_LIB([jvm], [JNI_CreateJavaVM], [LIBS=$LIBS], [AC_MSG_WARN([no libjvm found at JAVA_HOME])]) LDFLAGS=$save_LDFLAGS ])]) ```
Then there is the easy way: <http://www.gnu.org/software/autoconf-archive/ax_jni_include_dir.html> Sometimes it is best to just use the standard recipies.
Autoconf test for JNI include dir
[ "", "java", "java-native-interface", "autoconf", "" ]
Having recently discovered this method of development, I'm finding it a rather nice methodology. So, for my first project, I have a small DLL's worth of code (in C#.NET, for what it's worth), and I want to make a set of tests for this code, but I am a bit lost as to how and where to start. I'm using NUnit, and VS 2008, any tips on what sort of classes to start with, what to write tests for, and any tips on generally how to go about moving code across to test based development would be greatly appreciated.
See the book [Working Effectively with Legacy Code](http://www.amazon.co.uk/Working-Effectively-Legacy-Robert-Martin/dp/0131177052) by Michael Feathers. In summary, it's a lot of work to refactor existing code into testable and tested code; Sometimes it's too much work to be practical. It depends on how large the codebase is, and how much the various classes and functions depend upon each other. Refactoring without tests will introduce changes in behaviour (i.e. bugs). And purists will say it's not really refactoring because of the lack of tests to check that the behaviour doesn't change. Rather than adding test across the board to your whole application at once, add tests when you work in an area of code. Most likely you'll have to return to these "hotspots" again. Add tests from the bottom up: test little, independent classes and functions for correctness. Add tests from the top down: Test whole subsystems as black boxes to see if their behaviour changes with changes in code. And so you can step through them to find out what's going on. This approach will probably get you the most benefit. Don't be too concerned at first with what the "correct" behaviour is while you are adding tests, look to detect and avoid changes in behaviour. Large, untested systems often have internal behaviours that may seem incorrect, but that other parts of the system depend on. Think about isolating dependencies such as database, filesystem, network, so that they can be swapped out for mock data providers during testing. If the program doesn't have internal interfaces, lines which define the boundary between one subsystem/layer and another, then you may have to try to introduce these, and test at them. Also, automatic mocking frameworks like [Rhinomocks](http://ayende.com/projects/rhino-mocks.aspx) or [Moq](http://code.google.com/p/moq/) might help mock existing classes here. I haven't really found the need for them in code designed for testability.
I call it "Test Driven Reverse Engineering". Start "at the bottom" -- each class can be separately examined and a test written for it. When in doubt, guess. When you're doing ordinary TDD in the forward direction, you treat the test as sacred and assume that the code is probably broken. Sometimes the test is wrong, but your starting-off position is that it's the code. When you're doing TDRE, the code is sacred -- until you can **prove** that the code has a long-standing bug. In the reverse case, you write tests around the code, tweaking the tests until they work and claim the code works. Then, you can dig into the bad code. Some bad cade will have sensible test cases -- this just needs to be cleaned up. Some bad code, however, will also have a test case that's senseless. This may be a bug, or clumsy design that you may be able to rectify. To judge if the code's actually wrong, you also need to start at the top with overall test cases. Live data that actually works is a start. Also, live data that produces any of the known bugs, also a good place to start. I've written little code generators to turn live data into unittest cases. That way, I have a consistent basis for testing and refactoring.
Moving existing code to Test Driven Development
[ "", "c#", "tdd", "nunit", "" ]
I want to deserialize an object but don't know the class up front. So, consider the following code... ``` IFormatter formatter = new BinaryFormatter(); Stream stream = new FileStream("MyFile.bin", FileMode.Open, FileAccess.Read, FileShare.Read); MyObject obj = (MyObject)formatter.Deserialize(stream); ``` What could I do if I don't know the class up front? Say, for example "MyFile.bin" was a MyObject or a MyFoo. How do I determine which object to instantiate? Something like... ``` if (magic happens here == typeof(MyObject)) MyObject obj = (MyObject) formatter.Deserialize(stream); else if (more magic happens here == typeof(MyFoo)) MyFoo foo = (MyFoo)formatter.Deserialize(stream); ```
Just do: ``` object result = formatter.Deserialize(stream); Type t = result.GetType(); ```
Mainly as leppie says... If you want to test it for a few known types, you can use "is"/"as": ``` MyFoo foo = result As MyFoo; if(foo != null) { // it was one of those // special code } ``` But in general, you would let the serializer worry about such details... It is very different with xml-based serializers, of course, since you need to tell the serializer what is expected, rather than the serializer telling you what it got.
C# BinaryFormatter - How can I find out the class of the binary data?
[ "", "c#", "serialization", "binary", "" ]
It is a bit of a "chicken or egg" kind of query, but can someone dreamup a query that can return the name of the current database instance in which the query executes? Believe me when I say I understand the paradox: why do you need to know the name of the database instance if you're already connected to execute the query? Auditing in a multi-database environment. I've looked at all the @@ globals in Books Online. "`SELECT @@servername`" comes close, but I want the name of the database instance rather than the server.
``` SELECT @@servername AS 'Server Name' -- The database server's machine name ,@@servicename AS 'Instance Name' -- e.g.: MSSQLSERVER ,DB_NAME() AS 'Database Name' ,HOST_NAME() AS 'Host Name' -- The database client's machine name ```
``` SELECT DB_NAME() ``` Returns the database name.
How to query the name of the current SQL Server database instance?
[ "", "sql", "sql-server", "database", "t-sql", "ssms", "" ]
If I need to throw an exception from within my application which of the built-in .NET exception classes can I use? Are they all fair game? When should I derive my own?
See [Creating and Throwing Exceptions](http://msdn.microsoft.com/en-us/library/ms173163.aspx). On throwing built-in exceptions, it says: > Do not throw System.Exception, System.SystemException, System.NullReferenceException, or System.IndexOutOfRangeException intentionally from your own source code. and > Do Not Throw General Exceptions > > If you throw a general exception type, such as Exception or SystemException in a library or framework, it forces consumers to catch all exceptions, including unknown exceptions that they do not know how to handle. > > Instead, either throw a more derived type that already exists in the framework, or create your own type that derives from Exception." This [blog entry](http://blogs.msdn.com/fxcop/archive/2007/01/22/faq-what-exception-should-i-throw-instead-of-the-reserved-exceptions-found-by-donotraisereservedexceptiontypes.aspx) also has some useful guidelines. Also, FxCop code analysis defines a list of "do not raise exceptions" as [described here](http://msdn.microsoft.com/en-us/library/ms182338.aspx). It recommends: > The following exception types are too general to provide sufficient information to the user: > > * System.Exception > * System.ApplicationException > * System.SystemException > > The following exception types are reserved and should be thrown only by the common language runtime: > > * System.ExecutionEngineException > * System.IndexOutOfRangeException > * System.NullReferenceException > * System.OutOfMemoryException So in theory you can raise any other framework exception type, providing you clearly understand the intent of the exception as described by Microsoft (see MSDN documentation). Note, these are "guidelines" and as some others have said, there is debate around System.IndexOutOfRangeException (ie many developers throw this exception).
On the subject of `System.Exception` and `System.ApplicationException`: The latter was meant to be used as the base class of all custom exceptions. However, this hasn't been enforced consistently from the beginning. Consequently, there's a controversy whether this class should be used at all rather than using `System.Exception` as the base class for all exceptions. Whichever way you decide, *never* throw an instance of these two classes directly. It's actually a pity that they aren't `abstact`. For what it's worth, always try using the most specific exception possible. If there is none to meet your requirement, feel free to create your own. In this case, however, make sure that your exception has a benefit over existing exceptions. In particular, it should convey its meaning perfectly and provide all the information necessary to handle the situation in a meaningful manner. Avoid to create stub exceptions that don't do anything meaningful. In the same vein, avoid creating huge exception class hierarchies, they're rarely useful (although I can imagine a situation or two where I would use them … a parser being one of them).
Which built-in .NET exceptions can I throw from my application?
[ "", "c#", ".net", "exception", "" ]
To put it simple, there's a simple java swing app that consists of JFrame with some components in it. One of the components is a JPanel that is meant to be replaced by another JPanel on user action. So, what's the correct way of doing such a thing? I've tried ``` panel = new CustomJPanelWithComponentsOnIt(); parentFrameJPanelBelongsTo.pack(); ``` but this won't work. What would you suggest?
Your use case, seems perfect for [CardLayout](http://java.sun.com/docs/books/tutorial/uiswing/layout/card.html). In card layout you can add multiple panels in the same place, but then show or hide, one panel at a time.
1) Setting the first Panel: ``` JFrame frame=new JFrame(); frame.getContentPane().add(new JPanel()); ``` 2)Replacing the panel: ``` frame.getContentPane().removeAll(); frame.getContentPane().add(new JPanel()); ``` Also notice that you must do this in the Event's Thread, to ensure this use the [SwingUtilities.invokeLater](http://java.sun.com/javase/6/docs/api/javax/swing/SwingUtilities.html#invokeLater(java.lang.Runnable)) or the [SwingWorker](http://java.sun.com/javase/6/docs/api/javax/swing/SwingWorker.html)
How do I change JPanel inside a JFrame on the fly?
[ "", "java", "swing", "jpanel", "layout-manager", "cardlayout", "" ]
I have the following arrays in PHP (okay they are a bit bigger but the idea is what counts). ``` $array1 = array(1 => 'a', 2 => 'b'); $array2 = array(3 => 'c', 4 => 'd'); ``` Essentially I want to combine the two arrays as if it were something like this ``` $array3 = array(1 => 'a', 2 => 'b', 3 => 'c', 4 => 'd'); ``` Thanks
Use ``` $array3 = $array1 + $array2; ``` See [Array Operators](http://de3.php.net/manual/en/language.operators.array.php) By the way: [array\_merge()](http://de3.php.net/array_merge) does something different with the arrays given in the example: ``` $a1=array(1 => 'a', 2 => 'b'); $a2=array(3 => 'c', 4 => 'd'); print_r($a1+$a2); Array ( [1] => a [2] => b [3] => c [4] => d ) print_r(array_merge($a1, $a2)); Array ( [0] => a [1] => b [2] => c [3] => d ) ``` Note the different indexing.
You can check array\_combine function.
Combining php arrays
[ "", "php", "arrays", "" ]
I have a hidden embedded QuickTime object on my page that I'm trying to control via JavaScript, but it's not working. The object looks like this: ``` <object id="myPlayer" data="" type="audio/mpeg" pluginspage="http://www.apple.com/quicktime/download" width="0" height="0"> <param name="autoPlay" value="false" /> <param name="controller" value="false" /> <param name="enablejavascript" value="true" /> </object> ``` There is nothing in the data parameter because at render time, I don't know the URL that's going to be loaded. I set it like this: ``` var player = document.getElementById("myPlayer"); player.SetURL(url); ``` The audio will later be played back with: ``` player.Play(); ``` Firefox 3.0.3 produces no error in the JavaScript console, but no playback occurs when `Play()` is called. Safari 3.0.4 produces the following error in the console: ``` "Value undefined (result of expression player.SetURL) is not object." ``` Internet Explorer 7.0.5730.11 gives the following extremely helpful error message: ``` "Unspecified error." ``` I have QuickTime version 7.4 installed on my machine. [Apple's documentation](http://developer.apple.com/documentation/QuickTime/Conceptual/QTScripting_JavaScript/bQTScripting_JavaScri_Document/chapter_1000_section_5.html) says that `SetURL()` is correct, so why does it not work?
Try giving the object element some width and height (1px by 1px) and make it visible within the viewport when you attempt to communicate with the plugin via JavaScript. I've noticed that if the plugin area is not visible on screen it's unresponsive to JS commands. This might explain why this isn't working for you in IE. Safari and Opera should work, but FireFox will definitely require the Netscape style embed element, and really you should provide both. Additionally, once you have both, you need to ascertain which element (the object versus the embed) to address in which browser.
I don't know the QuickTime API, but this might be worth a shot: ``` player.attributes.getNamedItem('data').value = 'http://yoururlhere'; ```
SetURL method of QuickTime object undefined?
[ "", "javascript", "quicktime", "" ]
I have created an **application which needs 'hand-over'** to the support group in the next month. The application is **fairly small** (2 months development), and consists of two client side applications and a database, it's written in c# for the windows platform. **I have a broad idea** of what to include in a support document, but I haven't needed to make very many support documents so far in my career and I want a solid list of items to include. I guess my **goal** is to make the **lives of everyone** in the support group **easier** and as stress free as possible. **So I guess my questions are:** 1. What should a support document absolutely contain 2. What additional things have you put in support documents to make them extra useful. 3. What other activities can be done before hand-over to make all our lives easier?
Having been on both sides of this process professionally, I can say that the following should be ***mandatory***: * the documentation of the code (javadoc, doxygen, etc) * details on build process + where to get current source + how to file bugs (they will happen) + route to provide patches either to the source or to customers * how it works (simple, but often overlooked) * user-customizable portions (eg there is a scripting component) * primary contacts for each component, aka escalation path * encouragement for feedback from Support as to what else they want to see I'm sure lots of other things can be added, but these are the top priority in my mind.
1. Functional Specification (If you have one) 2. User Manual. Create one if you don't have 3. Technical Manual, Containing * Deployment Diagram * Softwares Used * Configuration and build details * Deatils of Server ip and admin / oracle / websphere passwords 4. Testing Document 5. Over view document giving out * Where all documents are kept * Version Control repository and its project/ user details * Application usernames / password 6. Any support SQL's/tools etc created by the development team, for analysis, loading data etc.
What are the core elements to include in Support Documentation?
[ "", "c#", ".net", "documentation", "" ]
On our live/production database I'm trying to add a trigger to a table, but have been unsuccessful. I have tried a few times, but it has taken more than 30 minutes for the create trigger statement to complete and I've cancelled it. The table is one that gets read/written to often by a couple different processes. I have disabled the scheduled jobs that update the table and attempted at times when there is less activity on the table, but I'm not able to stop everything that accesses the table. I do not believe there is a problem with the create trigger statement itself. The create trigger statement was successful and quick in a test environment, and the trigger works correctly when rows are inserted/updated to the table. Although when I created the trigger on the test database there was no load on the table and it had considerably less rows, which is different than on the live/production database (100 vs. 13,000,000+). Here is the create trigger statement that I'm trying to run ``` CREATE TRIGGER [OnItem_Updated] ON [Item] AFTER UPDATE AS BEGIN SET NOCOUNT ON; IF update(State) BEGIN /* do some stuff including for each row updated call a stored procedure that increments a value in table based on the UserId of the updated row */ END END ``` Can there be issues with creating a trigger on a table while rows are being updated or if it has many rows? In SQLServer triggers are created enabled by default. Is it possible to create the trigger disabled by default? Any other ideas?
The problem may not be in the table itself, but in the system tables that have to be updated in order to create the trigger. If you're doing any other kind of DDL as part of your normal processes they could be holding it up. Use sp\_who to find out where the block is coming from then investigate from there.
I believe the CREATE Trigger will attempt to put a lock on the entire table. If you have a lots of activity on that table it might have to wait a long time and you could be creating a deadlock. For any schema changes you should really get everyone of the database. That said it is tempting to put in "small" changes with active connections. You should take a look at the locks / connections to see where the lock contention is.
CREATE TRIGGER is taking more than 30 minutes on SQL Server 2005
[ "", "sql", "sql-server", "triggers", "" ]
## Question I'm looking for a Java in-memory object caching API. Any recommendations? What solutions have you used in the past? ## Current Right now, I'm just using a Map: ``` Map cache = new HashMap<String, Object>(); cache.put("key", value); ``` ## Requirements I need to extend the cache to include basic features like: * Max size * Time to live However, I don't need more sophisticated features like: * Access from multiple processes (caching server) * Persistence (to disk) ## Suggestions In-Memory caching: * [Guava](http://guava-libraries.googlecode.com) CacheBuilder - active development. See this [presentation](https://github.com/liubo404/it-ebooks/blob/master/pdf/JavaCachingwithGuava.pdf). * [LRUMap](http://commons.apache.org/collections/apidocs/org/apache/commons/collections/map/LRUMap.html) - Config via API. No TTL. Not purpose built for caching. * [whirlycache](http://whirlycache.dev.java.net/) - XML config. Mailing list. Last updated 2006. * [cache4j](http://cache4j.sourceforge.net/) - XML config. Documentation in Russian. Last updated 2006. Enterprise caching: * [JCS](http://jakarta.apache.org/jcs) - Properties config. Extensive documentation. * [Ehcache](http://ehcache.sourceforge.net) - XML config. Extensive documentation. By far the most popular according to Google hits.
[EHCache](http://ehcache.sourceforge.net/) is very nice. You can create an in memory cache. Check out their [code samples](http://ehcache.sourceforge.net/documentation/samples.html) for an example of creating an in memory cache. You can specify a max size, and a time to live. EHCache does offer some advanced features, but if your not interested in using them - don't. But it's nice to know they are there if your requirements ever change. Here is an in memory cache. Created in code, with no configuration files. ``` CacheManager cacheManager = CacheManager.getInstance(); int oneDay = 24 * 60 * 60; Cache memoryOnlyCache = new Cache("name", 200, false, false, oneDay, oneDay); cacheManager.addCache(memoryOnlyCache); ``` Creates a cache that will hold 200 elements, and has a ttl of 24 hours.
I really like the [`MapMaker`](https://google.github.io/guava/releases/snapshot/api/docs/com/google/common/collect/MapMaker.html) that comes with [Google Guava](https://github.com/google/guava) ([API](https://google.github.io/guava/releases/snapshot/api/docs/)) The JavaDoc has a pretty neat example that demonstrates both its ease of use and its power: ``` ConcurrentMap<Key, Graph> graphs = new MapMaker() .concurrencyLevel(32) .softKeys() .weakValues() .expiration(30, TimeUnit.MINUTES) .makeComputingMap( new Function<Key, Graph>() { public Graph apply(Key key) { return createExpensiveGraph(key); } }); ``` Furthermore, release 10.0 of Guava introduced the much more extensive [`com.google.common.cache` package](https://google.github.io/guava/releases/snapshot/api/docs/com/google/common/cache/package-summary.html) (there's a [nice wiki entry on how to use them](https://github.com/google/guava/wiki/CachesExplained)).
Lightweight Java Object cache API
[ "", "java", "caching", "" ]
When using C++ namespaces, do you prefer to explicitly name them, like this: ``` std::cout << "Hello, world!\n"; ``` Or do you prefer `using namespace`: ``` using namespace std; cout << "Hello, world!\n"; ``` And if if you prefer the latter, do you declare your usings at file or function scope? Personally I prefer to explicitly name them - it's more typing but when using a mixture of namespaces (e.g. `std` and `boost`) I find it more readable.
I always use `using namespace` for std & boost. Everything else I tend to use an explicit namespace unless it is used so much that it would clutter up the code. In headers, I never use `using namespace` to avoid polluting the global namespace of the #including source.
I use always explicit ones. Writing std does not hurt me and I clearly see where is it from. It's useful when you have some legacy project to take care of with it's own "strings", "vectors" etc to maintain. The more information the code carries with it, the better.
Do you prefer explicit namespaces or 'using' in C++?
[ "", "c++", "namespaces", "using", "" ]
PHP has a very nice function, isset($variableName). It checks if $variableName is already defined in the program or not. Can we build similar feature for C/C++ (some kind of symbol table lookup)?
I'm a C++ guy, but I remember in PHP isset is used to check if a variable contains a value when passed in through a get/post request (I'm sure there are other uses, but that's a common one I believe). You don't really have dynamic typing in C++. So you can't suddenly use a variable name that you haven't previously explicitly defined. There really is no such thing as an "unset" variable in C++. Even if you say "int var;" and do not initialize it, the variable has a value, usually garbage, but it's still "set" in the PHP sense. The closes I suppose would be the preprocessor's #ifdef and #ifndef which only checks to see if you've defined a variable using #define. But in my experience this is mostly used for omitting or adding code based on flags. For example: ``` // code code code #ifdef DEBUG // debug only code that will not be included in final product. #endif // more code more code ``` You can define DEBUG using #define to determine whether to include "DEBUG" code now. Perhaps telling a bit more about what you're trying to do with the C++ equivalent of isset will give you a better idea of how to go about doing it "The C++ Way".
There is no direct means of doing this in the language. However, it is possible to do this sort of thing by using a map such as the following: ``` typedef std::map<std::string, int> variables_type; variables_type variables; variables["var"] = 1; if(variables.find("jon") == variables.end()) std::cout << "variable, \"jon\" not set\n"; ``` In order to make this a variable like those used in PHP or javascript, the implementation would need to use some sort of variant type.
Counterpart of PHP's isset() in C/C++
[ "", "c++", "c", "compiler-construction", "" ]
I'm working on a project in C and it requires memalign(). Really, posix\_memalign() would do as well, but darwin/OSX lacks both of them. What is a good solution to shoehorn-in memalign? I don't understand the licensing for posix-C code if I were to rip off memalign.c and put it in my project- I don't want any viral-type licensing LGPL-ing my whole project.
Mac OS X appears to be [16-byte mem aligned.](http://www.taybin.com/2007/04/03/macos-x-memory-alignment/) Quote from the website: > I had a hard time finding a definitive > statement on MacOS X memory alignment > so I did my own tests. On 10.4/intel, > both stack and heap memory is 16 byte > aligned. So people porting software > can stop looking for memalign() and > posix\_memalign(). It’s not needed.
### update: OSX now has `posix_memalign()` Late to the party, but newer versions of OSX *do* have `posix_memalign()`. You might want this when aligning to page boundaries. For example: ``` #include <stdlib.h> char *buffer; int pagesize; pagesize = sysconf(_SC_PAGE_SIZE); if (pagesize == -1) handle_error("sysconf"); if (posix_memalign((void **)&buffer, pagesize, 4 * pagesize) != 0) { handle_error("posix_memalign"); } ``` One thing to note is that, unlike `memalign()`, `posix_memalign()` takes `**buffer` as an argument and returns an integer error code.
OSX lacks memalign
[ "", "c++", "c", "macos", "posix", "" ]
I want to I check whether a string is in ASCII or not. I am aware of `ord()`, however when I try `ord('Γ©')`, I have `TypeError: ord() expected a character, but string of length 2 found`. I understood it is caused by the way I built Python (as explained in [`ord()`'s documentation](http://docs.python.org/library/functions.html#ord)). Is there another way to check?
``` def is_ascii(s): return all(ord(c) < 128 for c in s) ```
I think you are not asking the right question-- A string in python has no property corresponding to 'ascii', utf-8, or any other encoding. The source of your string (whether you read it from a file, input from a keyboard, etc.) may have encoded a unicode string in ascii to produce your string, but that's where you need to go for an answer. Perhaps the question you can ask is: "Is this string the result of encoding a unicode string in ascii?" -- This you can answer by trying: ``` try: mystring.decode('ascii') except UnicodeDecodeError: print "it was not a ascii-encoded unicode string" else: print "It may have been an ascii-encoded unicode string" ```
How to check if a string in Python is in ASCII?
[ "", "python", "string", "unicode", "ascii", "" ]
Would it suppose any difference regarding overhead to write an import loading all the types within one package (`import java.*`); than just a specific type (i.e. `import java.lang.ClassLoader`)? Would the second one be a more advisable way to use than the other one?
There is not a performance or overhead cost to doing import .\* vs importing specific types. However, I consider it to be a best practice to never use import .\* My primary reason for this is I just like to keep things straightward, clean and with as little ambiguity as possible, and I think with a .\* import you lose that.
Take a look at the java API, and you'll see many classes and interfaces with the same name in different packages. For example: ``` java.lang.reflect.Array java.sql.Array ``` So, if you import `java.lang.reflect.*` and `java.sql.*` you'll have a collision on the Array type, and have to fully qualify them in your code. Importing specific classes instead will save you this hassle.
Import package.* vs import package.SpecificType
[ "", "java", "import", "overhead", "" ]
How can I count the number of elements in an array, because contrary to logic array.count(string) does not count all the elements in the array, it just searches for the number of occurrences of string.
The method len() returns the number of elements in the list. Syntax: ``` len(myArray) ``` Eg: ``` myArray = [1, 2, 3] len(myArray) ``` Output: ``` 3 ```
`len` is a built-in function that calls the given container object's `__len__` member function to get the number of elements in the object. Functions encased with double underscores are usually "special methods" implementing one of the standard interfaces in Python (container, number, etc). Special methods are used via syntactic sugar (object creation, container indexing and slicing, attribute access, built-in functions, etc.). Using `obj.__len__()` wouldn't be the correct way of using the special method, but I don't see why the others were modded down so much.
Counting array elements in Python
[ "", "python", "arrays", "" ]
Any ideas how i can best drive a USB POS printer from c#. POS printers are usually serial, TCP/IP or USB based. I know how to accomplish serial and TCP/IP but have no idea about communications through USB in C#. I know that there is a layer available from Microsoft called POS.NET, but I want to try and avoid using this. Any ideas or any C# libraries that people can recomend would be really appreciated. Thanks
You should really consider using POS for .NET and OPOS or .NET service objects (Epson, for example provides both). POS for .NET conforms to the UnifiedPOS industry standard for interfacing with these devices.
If the printer registers itself as a Human Interface Device, you can [P/INVOKE into the appropriate Win32 APIs](http://www.lvr.com/hidpage.htm "The HID Page"). Here are the signatures: ``` [ DllImport( "hid.dll", SetLastError=true ) ] public static extern Boolean HidD_FlushQueue( SafeFileHandle HidDeviceObject ); [ DllImport( "hid.dll", SetLastError=true ) ] public static extern Boolean HidD_FreePreparsedData( ref IntPtr PreparsedData ); [ DllImport( "hid.dll", SetLastError=true ) ] public static extern Boolean HidD_GetAttributes( SafeFileHandle HidDeviceObject , ref HIDD_ATTRIBUTES Attributes ); [ DllImport( "hid.dll", SetLastError=true ) ] public static extern Boolean HidD_GetFeature( SafeFileHandle HidDeviceObject , ref Byte lpReportBuffer , Int32 ReportBufferLength ); [ DllImport( "hid.dll", SetLastError=true ) ] public static extern Boolean HidD_GetInputReport( SafeFileHandle HidDeviceObject ,ref Byte lpReportBuffer ,Int32 ReportBufferLength ); [ DllImport( "hid.dll", SetLastError=true ) ] public static extern void HidD_GetHidGuid( ref System.Guid HidGuid ); [ DllImport( "hid.dll", SetLastError=true ) ] public static extern Boolean HidD_GetNumInputBuffers( SafeFileHandle HidDeviceObject , ref Int32 NumberBuffers ); [ DllImport( "hid.dll", SetLastError=true ) ] public static extern Boolean HidD_GetPreparsedData( SafeFileHandle HidDeviceObject ,ref IntPtr PreparsedData ); [ DllImport( "hid.dll", SetLastError=true ) ] public static extern Boolean HidD_SetFeature( SafeFileHandle HidDeviceObject , ref Byte lpReportBuffer , Int32 ReportBufferLength ); [ DllImport( "hid.dll", SetLastError=true ) ] public static extern Boolean HidD_SetNumInputBuffers( SafeFileHandle HidDeviceObject ,Int32 NumberBuffers ); [ DllImport( "hid.dll", SetLastError=true ) ] public static extern Boolean HidD_SetOutputReport( SafeFileHandle HidDeviceObject ,ref Byte lpReportBuffer ,Int32 ReportBufferLength ); [ DllImport( "hid.dll", SetLastError=true ) ] public static extern Int32 HidP_GetCaps( IntPtr PreparsedData, ref HIDP_CAPS Capabilities ); [ DllImport( "hid.dll", SetLastError=true ) ] public static extern Int32 HidP_GetValueCaps( Int16 ReportType , ref Byte ValueCaps , ref Int16 ValueCapsLength , IntPtr PreparsedData ); ```
Drive a POS printer via USB in c#
[ "", "c#", "usb", "point-of-sale", "" ]
I'd like a consistent and simple way to throw exceptions in JNI code; something that handles chained exceptions (implicitly from the env->ExceptionOccurred method, or explicitly by parameters, either way is good) and saves me looking up constructors every time I want to do this. All of the above is preferably in C, although I could translate it from C++ at need. Does anyone on SO have something like this that they can share?
We just code utility methods for each of the types of exceptions we want to throw. Here are some examples: ``` jint throwNoClassDefError( JNIEnv *env, char *message ) { jclass exClass; char *className = "java/lang/NoClassDefFoundError"; exClass = (*env)->FindClass( env, className); if (exClass == NULL) { return throwNoClassDefError( env, className ); } return (*env)->ThrowNew( env, exClass, message ); } jint throwNoSuchMethodError( JNIEnv *env, char *className, char *methodName, char *signature ) { jclass exClass; char *exClassName = "java/lang/NoSuchMethodError" ; LPTSTR msgBuf; jint retCode; size_t nMallocSize; exClass = (*env)->FindClass( env, exClassName ); if ( exClass == NULL ) { return throwNoClassDefError( env, exClassName ); } nMallocSize = strlen(className) + strlen(methodName) + strlen(signature) + 8; msgBuf = malloc( nMallocSize ); if ( msgBuf == NULL ) { return throwOutOfMemoryError ( env, "throwNoSuchMethodError: allocating msgBuf" ); } memset( msgBuf, 0, nMallocSize ); strcpy( msgBuf, className ); strcat( msgBuf, "." ); strcat( msgBuf, methodName ); strcat( msgBuf, "." ); strcat( msgBuf, signature ); retCode = (*env)->ThrowNew( env, exClass, msgBuf ); free ( msgBuf ); return retCode; } jint throwNoSuchFieldError( JNIEnv *env, char *message ) { jclass exClass; char *className = "java/lang/NoSuchFieldError" ; exClass = (*env)->FindClass( env, className ); if ( exClass == NULL ) { return throwNoClassDefError( env, className ); } return (*env)->ThrowNew( env, exClass, message ); } jint throwOutOfMemoryError( JNIEnv *env, char *message ) { jclass exClass; char *className = "java/lang/OutOfMemoryError" ; exClass = (*env)->FindClass( env, className ); if ( exClass == NULL ) { return throwNoClassDefError( env, className ); } return (*env)->ThrowNew( env, exClass, message ); } ``` That way, it's easy to find them, your code-completion editor will help you to type them in, and you can pass simple parameters. I'm sure you could expand this to handle chained exceptions, or other more complicated approaches. This was enough to meet our needs.
I simply use 2 lines: ``` sprintf(exBuffer, "NE%4.4X: Caller can %s %s print", marker, "log", "or"); (*env)->ThrowNew(env, (*env)->FindClass(env, "java/lang/Exception"), exBuffer); ``` Produces: ``` Exception in thread "main" java.lang.Exception: NE0042: Caller can log or print. ```
Best way to throw exceptions in JNI code?
[ "", "java", "exception", "java-native-interface", "" ]
I'd like to use the newer `<button>` tag in an ASP.NET website which, among other things, allows CSS-styled text and embedding a graphic inside the button. The asp:Button control renders as `<input type="button">`, is there any way to make a preexisting control render to `<button>`? From what I've read there is an incompatibility with IE posting the button's markup instead of the value attribute when the button is located within a `<form>`, but in ASP.NET it will be using the onclick event to fire \_\_doPostBack anyway, so I don't think that this would be a problem. Are there any reasons why I shouldn't use this? If not, how would you go about supporting it with asp:Button, or a new server control based on it? I would prefer to not write my own server control if that can be avoided. --- At first the `<button runat="server">` solution worked, but I immediately ran into a situation where it needs to have a CommandName property, which the HtmlButton control doesn't have. It looks like I'm going to need to create a control inherited from Button after all. What do I need to do in order to override the render method and make it render what I want? --- **UPDATE** DanHerbert's reply has made me interested in finding a solution to this again, so I've spent some more time working on it. First, there's a far easier way of overloading the TagName: ``` public ModernButton() : base(HtmlTextWriterTag.Button) { } ``` The problem with Dan's solution as it stands is the innerhtml of the tag is placed into the value property, which causes a validation error on postback. A related problem is, even if you render the value property correctly, IE's braindead implementation of the `<button>` tag posts the innerhtml instead of the value anyway. So, any implementation of this needs to override the AddAttributesToRender method in order to correctly render the value property, and also provide some sort of workaround for IE so it doesn't completely screw up the postback. The IE problem may be insurmountable if you want to take advantage of the CommandName/CommandArgument properties for a databound control. Hopefully someone can suggest a workaround for this. I have made progress on the rendering: [ModernButton.cs](http://gist.github.com/69841) This renders as a proper html `<button>` with the correct value, but it doesn't work with the ASP.Net PostBack system. I've written some of what I need to provide the `Command` event, but it doesn't fire. When inspecting this button side-by-side with a regular asp:Button, they look the same other than the differences I need. So I'm not sure how ASP.Net is wiring up the `Command` event in this case. An additional problem is, nested server controls aren't rendered (as you can see with the ParseChildren(false) attribute). It's pretty easy to inject literal html text into the control during render, but how do you allow support for nested server controls?
This is an old question, but for those of us unlucky enough still having to maintain ASP.NET Web Forms applications, I went through this myself while trying to include Bootstrap glyphs inside of built-in button controls. As per Bootstrap documentation, the desired markup is as follows: ``` <button class="btn btn-default"> <span class="glyphicon glyphicon-search" aria-hidden="true"></span> Search </button> ``` I needed this markup to be rendered by a server control, so I set out to find options. # Button This would be the first logical step, but β€”as this question explainsβ€” Button renders an `<input>` element instead of `<button>`, so adding inner HTML is not possible. # LinkButton (credit to [Tsvetomir Tsonev's answer](https://stackoverflow.com/a/187527)) **Source** ``` <asp:LinkButton runat="server" ID="uxSearch" CssClass="btn btn-default"> <span class="glyphicon glyphicon-search" aria-hidden="true"></span> Search </asp:LinkButton> ``` **Output** ``` <a id="uxSearch" class="btn btn-default" href="javascript:__doPostBack(&#39;uxSearch&#39;,&#39;&#39;)"> <span class="glyphicon glyphicon-search" aria-hidden="true"></span> Search </a> ``` **Pros** * Looks OK * `Command` event; `CommandName` and `CommandArgument` properties **Cons** * Renders `<a>` instead of `<button>` * Renders and relies on obtrusive JavaScript # HtmlButton (credit to [Philippe's answer](https://stackoverflow.com/a/1171539)) **Source** ``` <button runat="server" id="uxSearch" class="btn btn-default"> <span class="glyphicon glyphicon-search" aria-hidden="true"></span> Search </button> ``` **Result** ``` <button onclick="__doPostBack('uxSearch','')" id="uxSearch" class="btn btn-default"> <span class="glyphicon glyphicon-search" aria-hidden="true"></span> Search </button> ``` **Pros** * Looks OK * Renders proper `<button>` element **Cons** * No `Command` event; no `CommandName` or `CommandArgument` properties * Renders and relies on obtrusive JavaScript to handle its `ServerClick` event --- At this point it is clear that none of the built-in controls seem suitable, so the next logical step is try and modify them to achieve the desired functionality. # Custom control (credit to [Dan Herbert's answer](https://stackoverflow.com/a/573990)) **NOTE: This is based on Dan's code, so all credit goes to him.** ``` using System.Web.UI; using System.Web.UI.WebControls; namespace ModernControls { [ParseChildren] public class ModernButton : Button { public new string Text { get { return (string)ViewState["NewText"] ?? ""; } set { ViewState["NewText"] = value; } } public string Value { get { return base.Text; } set { base.Text = value; } } protected override HtmlTextWriterTag TagKey { get { return HtmlTextWriterTag.Button; } } protected override void AddParsedSubObject(object obj) { var literal = obj as LiteralControl; if (literal == null) return; Text = literal.Text; } protected override void RenderContents(HtmlTextWriter writer) { writer.Write(Text); } } } ``` I have stripped the class down to the bare minimum, and refactored it to achieve the same functionality with as little code as possible. I also added a couple of improvements. Namely: * Remove `PersistChildren` attribute (seems unnecessary) * Remove `TagName` override (seems unnecessary) * Remove HTML decoding from `Text` (base class already handles this) * Leave `OnPreRender` intact; override `AddParsedSubObject` instead (simpler) * Simplify `RenderContents` override * Add a `Value` property (see below) * Add a namespace (to include a sample of **@ Register** directive) * Add necessary `using` directives The `Value` property simply accesses the old `Text` property. This is because the native Button control renders a `value` attribute anyway (with `Text` as its value). Since `value` is a valid attribute of the `<button>` element, I decided to include a property for it. **Source** ``` <%@ Register TagPrefix="mc" Namespace="ModernControls" %> <mc:ModernButton runat="server" ID="uxSearch" Value="Foo" CssClass="btn btn-default" > <span class="glyphicon glyphicon-search" aria-hidden="true"></span> Search </mc:ModernButton> ``` **Output** ``` <button type="submit" name="uxSearch" value="Foo" id="uxSearch" class="btn btn-default"> <span class="glyphicon glyphicon-search" aria-hidden="true"></span> Search </button> ``` **Pros** * Looks OK * Renders a proper `<button>` element * `Command` event; `CommandName` and `CommandArgument` properties * Does not render or rely on obtrusive JavaScript **Cons** * None (other than not being a built-in control)
Although you say that using the [button runat="server"] is not a good enough solution it is important to mention it - a lot of .NET programmers are afraid of using the "native" HTML tags... Use: ``` <button id="btnSubmit" runat="server" class="myButton" onserverclick="btnSubmit_Click">Hello</button> ``` This usually works perfectly fine and everybody is happy in my team.
How can I use the button tag with ASP.NET?
[ "", "asp.net", "c#", "html", "" ]
I have few different applications among which I'd like to share a C# enum. I can't quite figure out how to share an enum declaration between a regular application and a WCF service. Here's the situation. I have 2 lightweight C# destop apps and a WCF webservice that all need to share enum values. Client 1 has ``` Method1( MyEnum e, string sUserId ); ``` Client 2 has ``` Method2( MyEnum e, string sUserId ); ``` Webservice has ``` ServiceMethod1( MyEnum e, string sUserId, string sSomeData); ``` My initial though was to create a library called Common.dll to encapsulate the enum and then just reference that library in all of the projects where the enum is needed. However, WCF makes things difficult because you need to markup the enum for it to be an integral part of the service. Like this: ``` [ServiceContract] [ServiceKnownType(typeof(MyEnum))] public interface IMyService { [OperationContract] ServiceMethod1( MyEnum e, string sUserId, string sSomeData); } [DataContract] public enum MyEnum{ [EnumMember] red, [EnumMember] green, [EnumMember] blue }; ``` So .... Is there a way to share an enum among a WCF service and other applictions?
Using the Common library should be fine. Enumerations are serializable and the DataContract attributes are not needed. See: <http://msdn.microsoft.com/en-us/library/ms731923.aspx> > Enumeration types. Enumerations, including flag enumerations, are > serializable. Optionally, enumeration types can be marked with the > DataContractAttribute attribute, in which case every member that > participates in serialization must be marked with the > EnumMemberAttribute attribute EDIT: Even so, there should be no issue with having the enum marked as a DataContract and having client libraries using it.
I must have had some issues with an outdated service reference or something. I went back and created a common library containing the enum, and everything works fine. I simply added a using reference to the service interface's file. ``` using Common; [ServiceContract] [ServiceKnownType(typeof(MyEnum))] public interface IMyService { [OperationContract] ServiceMethod1( MyEnum e, string sUserId, string sSomeData); } ``` and I dropped the following: ``` [DataContract] public enum MyEnum{ [EnumMember] red, [EnumMember] green, [EnumMember] blue }; ``` I guess since the enum is referenced via ServiceKnownType, it didn't need to be marked up in the external library with [DataContract] or [Enumerator]
Sharing Enum with WCF Service
[ "", "c#", "wcf", "enums", "" ]
What is the best way to make trailing slashes not matter in the latest version of Routes (1.10)? I currently am using the clearly non-DRY: ``` map.connect('/logs/', controller='logs', action='logs') map.connect('/logs', controller='logs', action='logs') ``` I think that turning minimization on would do the trick, but am under the impression that it was disabled in the newer versions of Routes for a reason. Unfortunately documentation doesn't seem to have caught up with Routes development, so I can't find any good resources to go to. Any ideas?
There are two possible ways to solve this: 1. [Do it entirely in pylons](http://wiki.pylonshq.com/display/pylonscookbook/Adding+trailing+slash+to+pages+automatically). 2. [Add an htaccess rule to rewrite the trailing slash](http://enarion.net/web/apache/htaccess/trailing-slash/). Personally I don't like the trailing slash, because if you have a uri like: <http://example.com/people> You should be able to get the same data in xml format by going to: <http://example.com/people.xml>
The following snippet added as the very last route worked for me: ``` map.redirect('/*(url)/', '/{url}', _redirect_code='301 Moved Permanently') ```
Trailing slashes in Pylons Routes
[ "", "python", "routes", "pylons", "" ]
I have a requirement of reading subject, sender address and message body of new message in my Outlook inbox from a C# program. But I am getting security alert 'A Program is trying to access e-mail addresses you have stored in Outlook. Do you want to allow this'. By some googling I found few third party COM libraries to avoid this. But I am looking for a solution which don't require any third party COM library.
Sorry, I have had that annoying issue in both Outlook 2003 and Outlook 2007 add-ins, and the only solution that worked was to purchase a [Redemption](http://www.dimastr.com/redemption/) license. In Outlook 2007 that pesky popup should only show up if your firewall is down or your anti-virus software is outdated as far as I recall.
I ran into same issue while accessing sender email address for outlook mail item. To avoid 'security alert' do not create new Application object, instead use **Globals.ThisAddIn.Application** to create new mailitem. ``` string GetSenderEmail(Outlook.MailItem item) { string emailAddress = ""; if (item.SenderEmailType == "EX") { Outlook.MailItem tempItem = (Outlook.MailItem)Globals.ThisAddIn.Application.CreateItem(Outlook.OlItemType.olMailItem); tempItem.To = item.SenderEmailAddress; emailAddress = tempItem.Recipients[1].AddressEntry.GetExchangeUser().PrimarySmtpAddress.Trim(); } else { emailAddress = item.SenderEmailAddress.Trim(); } return emailAddress; } ```
How to avoid Outlook security alert when reading outlook message from C# program
[ "", "c#", "outlook", "" ]
Recently, [I made a post about the developers I'm working with not using try catch blocks properly](https://stackoverflow.com/questions/204814/is-there-any-valid-reason-to-ever-ignore-a-caught-exception), and unfortuantely using try... catch blocks in critical situations and ignoring the exception error all together. causing me major heart ache. Here is an example of one of the several thousand sections of code that they did this (some code left out that doesn't particuarly matter: ``` public void AddLocations(BOLocation objBllLocations) { try { dbManager.Open(); if (objBllLocations.StateID != 0) { // about 20 Paramters added to dbManager here } else { // about 19 Paramters added here } dbManager.ExecuteNonQuery(CommandType.StoredProcedure, "ULOCATIONS.AddLocations"); } catch (Exception ex) { } finally { dbManager.Dispose(); } } ``` This is absolutely discusting, in my eyes, and does not notify the user in case some potential problem occurred. I know many people say that OOP is evil, and that adding multiple layers adds to the number of lines of code and to the complexity of the program, leading to possible issues with code maintainence. Much of my programming background, I personally, have taken almost the same approach in this area. Below I have listed out a basic structure of the way I normally code in such a situation, and I've been doing this accross many languages in my career, but this particular code is in C#. But the code below is a good basic idea of how I use the Objects, it seems to work for me, but since this is a good source of some fairly inteligent programming mines, I'd like to know If I should re-evaluate this technique that I've used for so many years. Mainly, because, in the next few weeks, i'm going to be plunging into the not so good code from the outsourced developers and modifying huge sections of code. i'd like to do it as well as possible. sorry for the long code reference. ``` // ******************************************************************************************* /// <summary> /// Summary description for BaseBusinessObject /// </summary> /// <remarks> /// Base Class allowing me to do basic function on a Busines Object /// </remarks> public class BaseBusinessObject : Object, System.Runtime.Serialization.ISerializable { public enum DBCode { DBUnknownError, DBNotSaved, DBOK } // private fields, public properties public int m_id = -1; public int ID { get { return m_id; } set { m_id = value; } } private int m_errorCode = 0; public int ErrorCode { get { return m_errorCode; } set { m_errorCode = value; } } private string m_errorMsg = ""; public string ErrorMessage { get { return m_errorMsg; } set { m_errorMsg = value; } } private Exception m_LastException = null; public Exception LastException { get { return m_LastException; } set { m_LastException = value;} } //Constructors public BaseBusinessObject() { Initialize(); } public BaseBusinessObject(int iID) { Initialize(); FillByID(iID); } // methods protected void Initialize() { Clear(); Object_OnInit(); // Other Initializable code here } public void ClearErrors() { m_errorCode = 0; m_errorMsg = ""; m_LastException = null; } void System.Runtime.Serialization.ISerializable.GetObjectData( System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { //Serialization code for Object must be implemented here } // overrideable methods protected virtual void Object_OnInit() { // User can override to add additional initialization stuff. } public virtual BaseBusinessObject FillByID(int iID) { throw new NotImplementedException("method FillByID Must be implemented"); } public virtual void Clear() { throw new NotImplementedException("method Clear Must be implemented"); } public virtual DBCode Save() { throw new NotImplementedException("method Save Must be implemented"); } } // ******************************************************************************************* /// <summary> /// Example Class that might be based off of a Base Business Object /// </summary> /// <remarks> /// Class for holding all the information about a Customer /// </remarks> public class BLLCustomer : BaseBusinessObject { // *************************************** // put field members here other than the ID private string m_name = ""; public string Name { get { return m_name; } set { m_name = value; } } public override void Clear() { m_id = -1; m_name = ""; } public override BaseBusinessObject FillByID(int iID) { Clear(); try { // usually accessing a DataLayerObject, //to select a database record } catch (Exception Ex) { Clear(); LastException = Ex; // I can have many different exception, this is usually an enum ErrorCode = 3; ErrorMessage = "Customer couldn't be loaded"; } return this; } public override DBCode Save() { DBCode ret = DBCode.DBUnknownError; try { // usually accessing a DataLayerObject, //to save a database record ret = DBCode.DBOK; } catch (Exception Ex) { LastException = Ex; // I can have many different exception, this is usually an enum // i do not usually use just a General Exeption ErrorCode = 3; ErrorMessage = "some really weird error happened, customer not saved"; ret = DBCode.DBNotSaved; } return ret; } } // ******************************************************************************************* // Example of how it's used on an asp page.. protected void Page_Load(object sender, EventArgs e) { // Simplifying this a bit, normally, I'd use something like, // using some sort of static "factory" method // BaseObject.NewBusinessObject(typeof(BLLCustomer)).FillByID(34); BLLCustomer cust = ((BLLCustomer)new BLLCustomer()).FillByID(34); if (cust.ErrorCode != 0) { // There was an error.. Error message is in //cust.ErrorMessage // some sort of internal error code is in //cust.ErrorCode // Give the users some sort of message through and asp:Label.. // probably based off of cust.ErrorMessage //log can be handled in the data, business layer... or whatever lab.ErrorText = cust.ErrorMessage; } else { // continue using the object, to fill in text boxes, // literals or whatever. this.labID = cust.ID.toString(); this.labCompName = cust.Name; } } ``` Bottom line, my question is, Am I over complicating things with the muliple layers, and the inherited classes or is my old concept illustrated still working good and stable? Is there a better way now a days to accomplish these things? Should I go to just making straight SQL calls from the asp.net page code behind pages as fellow work associate developer suggested (though that last solution makes me feel icky), instead of going through a business object, and data layer (data layer not shown, but basically holds all the stored proc calls). Yeah, another developer did ask me why i go through the effort of layering things, when you can just type what you need straight in a \*.aspx.cs code behind page, and then I can have the joys of over 1k lines of code behind. What is some advice here?
Have you considered using an ORM like NHibernate? There's no point in re-inventing the wheel. To me this is a code smell: ``` BLLCustomer cust = ((BLLCustomer)new BLLCustomer()).FillByID(34); ``` Too many brackets! I've found that using the active record pattern in a language like C# always ends in tears because it's hard(er) to unit test.
The jump from the first bit of code to the next is huge. Whether a complicated business object layer is necessary will depend on the size of the app in question. At the very least though our policy is that exceptions are logged where they are handled. How you present to the user is up to you but having logs is essential so that developers can get more information if necessary.
General Business Object Practices (and exception errors - redux)
[ "", "c#", "error-handling", "object", "" ]
I've worked in shops where I've implemented Exception Handling into the event log, and into a table in the database. Each have their merits, of which I can highlight a few based on my experience: Event Log * Industry standard location for exceptions (+) * Ease of logging (+) * Can log database connection problems here (+) * Can build report and viewing apps on top of the event log (+) * Needs to be flushed every so often, if alot is reported there (-) * Not as extensible as SQL logging [add custom fields like method name in SQL] (-) SQL/Database * Can handle large volumes of data (+) * Can handle rapid volume inserts of exceptions (+) * Single storage location for exception in load balanced environment (+) * Very customizable (+) * A little easier to build reporting/notification off of SQL storage (+) * Different from where typical exceptions are stored (-) Am I missing any major considerations? I'm sure that a few of these points are debatable, but I'm curious what has worked best for other teams, and why you feel strongly about the choice.
You need to differentiate between logging and tracing. While the lines are a bit fuzzy, I tend to think of logging as "non developer stuff". Things like unhandled exceptions, corrupt files, etc. These are definitely not normal, and should be a very infrequent problem. Tracing is what a developer is interested in. The stack traces, method parameters, that the web server returned an HTTP Status of 401.3, etc. These are really noisy, and can produce a lot of data in a short amount of time. Normally we have different levels of tracing, to cut back the noise. For logging in a client app, I think that Event Logs are the way to go (I'd have to double check, but I think ASP.NET Health Monitoring can write to the Event Log as well). Normal users have permissions to write to the event log, as long as you have the Setup (which is installed by an admin anyway) create the event source. Most of your advantages for Sql logging, while true, aren't applicable to event logging: * Can handle large volumes of data: *Do you really have large volumes of unhandled exceptions or other high level failures?* * Can handle rapid volume inserts of exceptions: *A single unhandled exception should bring your app down - it's inherently rate limited. Other interesting events to non developers should be similarly aggregated.* * Very customizable: *The message in an Event Log is pretty much free text. If you need more info, just point to a text or structured XML or binary file log* * A little easier to build reporting/notification off of SQL storage: *Reporting is built in with the Event Log Viewer, and notification systems are, either inherent - due to an application crash - or mixed in with other really critical notifications - there's little excuse for missing an Event Log message. For corporate or other networked apps, there's a thousand and 1 different apps that already cull from Event Logs for errors...chances are your sysadmin is already using one.* For *tracing*, of which the specific details of an exception or errors is a part of, I like flat files - they're easy to maintain, easy to grep, and can be imported into Sql for analysis if I like. 90% of the time, you don't need them and they're set to WARN or ERROR. But, when you do set them to INFO or DEBUG, you'll generate a *ton* of data. An RDBMS has a lot of overhead - for performance (ACID, concurrency, etc.), storage (transaction logs, SCSI RAID-5 drives, etc.), and administration (backups, server maintenance, etc.) - all of which are unnecessary for trace logs.
I wouldn't log *straight* to the database. As you say, database issues become tricky to log :) I would log to the filesystem, and then have a job which bulk-inserts from files to the database. Personally I like having the logs in the database in the log run primarily for the scaling situation - I pretty much assume I'll have more than one machine running, and it's handy to be able to effectively have a combined log. (Each entry should state the machine it comes from, of course.) Report and viewing apps can be done very easily from a database - there may be fewer log-specialized reporting tools out there at the moment, but pretty much all databases have generalised reporting functionality. For ease of logging, I'd use a framework like [log4net](http://logging.apache.org/log4net/index.html) which takes a lot of the effort out of it, and is a tried and tested solution. Aside from anything else, that means you can change your output strategy with no code changes. You could even log to both the event log and the database if necessary, or send some logs to one place and some to the other. (I've assumed .NET here, but there are similar logging frameworks for many platforms.)
(Windows) Exception Handling: to Event Log or to Database?
[ "", "sql", "exception", "event-log", "" ]
I know VS2008 has the remove and sort function for cleaning up using directives, as does Resharper. Apart from your code being "clean" and removing the problem of referencing namespaces which might not exist in the future, what are the benefits of maintaining a "clean" list of using directives? Less code? Faster compilation times?
For me it's basically all about less noise (plus making Resharper happy!). I would believe any improvement in compilation time would be minimal.
If you always only have the using directives that you need, and always have them appropriately sorted, then when you come to diff two versions of the code, you'll never see irrelevant changes. Furthermore, if you have a neat set of using directives then anyone looking at the code to start with can get a *rough* idea of what's going to be used just by look at the using directives.
What are the benefits of maintaining a "clean" list of using directives in C#?
[ "", "c#", "visual-studio", "resharper", "using", "" ]
Can a `JApplet` use a `JFileChooser` so that the user can select a file on his hard-drive? Or would this violate Java applet security? (I'm assuming that the default security settings are being used. I don't want to ask my users to grant me extra permissions.)
[This thread](http://forums.sun.com/thread.jspa?threadID=5322793&tstart=91) indicates that you need to digitally sign your applet before a `JFileChooser` is permitted.
As mentioned, you need to sign your applet, which result in a "vague security warning" when the user is presented the applet. When the user accept to run this applet, the applet is given full access and functions like an ordinary application with it's obvious security implications. I'm in the same dilemma regarding a web application I'm working on and is not yet sure if it'll get deployed. You could alternatively use the built-in filebrowser in the webbrowser and bounce back the file-content from your server if you're working with smaller files. Also, some security measures you can make regarding a signed applet are: * Validating the origin of the applet code. ``` URL appletUrl = MyApplet.class.getProtectionDomain().getCodeSource().getLocation(); if(appletUrl.toString().equalsIgnoreCase(safeAppletUrl) == false) return false; ``` * Verifying the base URL from which the applet was run. ``` URL documentUrl = this.getDocumentBase(); if(documentUrl.toString().equalsIgnoreCase(safeDocumentUrl) == false) return false; ```
JFileChooser use within JApplet
[ "", "java", "applet", "jfilechooser", "" ]
To make click-able divs, I do: ``` <div class="clickable" url="http://google.com"> blah blah </div> ``` and then ``` $("div.clickable").click( function() { window.location = $(this).attr("url"); }); ``` I don't know if this is the best way, but it works perfectly with me, except for one issue: If the div contains a click-able element, such as <a href="...">, and the user clicks on the hyperlink, both the hyperlink and div's-clickable are called This is especially a problem when the anchor tag is referring to a javascript AJAX function, which executes the AJAX function *AND* follows the link in the 'url' attribute of the div. Anyway around this?
If you return "false" from your function it'll stop the event bubbling, so only your first event handler will get triggered (ie. your anchor will not see the click). ``` $("div.clickable").click( function() { window.location = $(this).attr("url"); return false; }); ``` See [event.preventDefault() vs. return false](https://stackoverflow.com/questions/1357118/javascript-event-preventdefault-vs-return-false) for details on return false vs. preventDefault.
`$("div.clickable").click( function(event) { window.location = $(this).attr("url"); event.preventDefault(); });`
jQuery DIV click, with anchors
[ "", "javascript", "jquery", "" ]
I am using java language,I have a method that is supposed to return an object if it is found. If it is not found, should I: 1. return null 2. throw an exception 3. other Which is the best practise or idiom?
If you are always expecting to find a value then throw the exception if it is missing. The exception would mean that there was a problem. If the value can be missing or present and both are valid for the application logic then return a null. More important: What do you do other places in the code? Consistency is important.
Only throw an exception if it is truly an error. If it is expected behavior for the object to not exist, return the null. Otherwise it is a matter of preference.
Should a retrieval method return 'null' or throw an exception when it can't produce the return value?
[ "", "java", "exception", "error-handling", "null", "" ]
I am trying to connect to 2 databases on the same instance of MySQL from 1 PHP script. At the moment the only way I've figured out is to connect to both databases with a different user for each. I am using this in a migration script where I am grabbing data from the original database and inserting it into the new one, so I am looping through large lists of results. Connecting to 1 database and then trying to initiate a second connection with the same user just changes the current database to the new one. Any other ideas?
You'll need to pass a boolean true as the optional fourth argument to mysql\_connect(). See [PHP's mysql\_connect() documentation](http://php.net/mysql_connect) for more info.
If your database user has access to both databases and they are on the same server, you can use one connection and just specify the database you want to work with before the table name. Example: ``` SELECT column FROM database.table ``` Depending on what you need to do, you might be able to do an [`INSERT INTO`](http://dev.mysql.com/doc/refman/5.0/en/insert-select.html) and save a bunch of processing time. ``` INSERT INTO database1.table (column) SELECT database2.table.column FROM database2.table ```
How to connect to 2 databases at the same time in PHP
[ "", "php", "mysql", "database", "" ]
What's the best way to trim a DateTime object to a specific precision? For instance, if I have a DateTime with a value of '2008-09-29 09:41:43', but I only want it's precision to be to the minute, is there any better way to do it than this? ``` private static DateTime TrimDateToMinute(DateTime date) { return new DateTime( date.Year, date.Month, date.Day, date.Hour, date.Minute, 0); } ``` What I would really want is to make it variable so that I could set its precision to the second, minute, hour, or day.
``` static class Program { //using extension method: static DateTime Trim(this DateTime date, long roundTicks) { return new DateTime(date.Ticks - date.Ticks % roundTicks, date.Kind); } //sample usage: static void Main(string[] args) { Console.WriteLine(DateTime.Now); Console.WriteLine(DateTime.Now.Trim(TimeSpan.TicksPerDay)); Console.WriteLine(DateTime.Now.Trim(TimeSpan.TicksPerHour)); Console.WriteLine(DateTime.Now.Trim(TimeSpan.TicksPerMillisecond)); Console.WriteLine(DateTime.Now.Trim(TimeSpan.TicksPerMinute)); Console.WriteLine(DateTime.Now.Trim(TimeSpan.TicksPerSecond)); Console.ReadLine(); } } ```
You could use an enumeration ``` public enum DateTimePrecision { Hour, Minute, Second } public static DateTime TrimDate(DateTime date, DateTimePrecision precision) { switch (precision) { case DateTimePrecision.Hour: return new DateTime(date.Year, date.Month, date.Day, date.Hour, 0, 0); case DateTimePrecision.Minute: return new DateTime(date.Year, date.Month, date.Day, date.Hour, date.Minute, 0); case DateTimePrecision.Second: return new DateTime(date.Year, date.Month, date.Day, date.Hour, date.Minute, date.Second); default: break; } } ``` and expand as required.
Is there a better way to trim a DateTime to a specific precision?
[ "", "c#", ".net", "datetime", "" ]
for working with MS word files in python, there is python win32 extensions, which can be used in windows. How do I do the same in linux? Is there any library?
You could make a subprocess call to [antiword](http://en.wikipedia.org/wiki/Antiword). Antiword is a linux commandline utility for dumping text out of a word doc. Works pretty well for simple documents (obviously it loses formatting). It's available through apt, and probably as RPM, or you could compile it yourself.
Use the **native Python docx module**. Here's how to extract all the text from a doc: ``` document = docx.Document(filename) docText = '\n\n'.join( paragraph.text for paragraph in document.paragraphs ) print(docText) ``` See [Python DocX site](https://python-docx.readthedocs.org/en/latest/) Also check out [Textract](http://textract.readthedocs.org/en/latest/) which pulls out tables etc. Parsing XML with regexs invokes cthulu. Don't do it!
extracting text from MS word files in python
[ "", "python", "linux", "ms-word", "" ]
Is there an easy way to convert between color models in Java (RGB, HSV and Lab). Assuming RGB color model: * How do I calculate black body spectrum color palette? I want to use it for a heatmap chart. * How about single-wavelength spectrum? **Edit:** I found that the [ColorSpace](http://java.sun.com/javase/6/docs/api/java/awt/color/ColorSpace.html) class can be used for conversions between RGB/CIE and many other color models.
You can build such a palette using the HSV color-model. That's easy once you have the HSV to RGB code in place and play around with the numbers for some minutes. However, I think it's not worth it to add the code to your project just to generate a little palette. It's much easier and less work to extract the palettes you need from a file and add them as a static array. Photoshop let's you edit palettes and comes with a very nice black body palette as a preset. You can simply save these as a .act file. The file itself is just a simple 256 color Γ‘ 3 byte file (order is read, green, blue. 8 bits per channel).
Java has built-in RGB to HSB conversion. Whenever I need a quick pallet of colors in Java I just do this: ``` public Color[] generateColors(int n) { Color[] cols = new Color[n]; for(int i = 0; i < n; i++) { cols[i] = Color.getHSBColor((float) i / (float) n, 0.85f, 1.0f); } return cols; } ``` It is a quick and dirty hack (I would tweak the 'magic' numbers for your app), but for my simple uses it generates a nice bright pleasant pallet.
Generating spectrum color palettes
[ "", "java", "colors", "" ]
I'm using C# & .NEt 3.5. What is the difference between the OptionA and OptionB ? ``` class MyClass { private object m_Locker = new object(); private Dicionary<string, object> m_Hash = new Dictionary<string, object>(); public void OptionA() { lock(m_Locker){ // Do something with the dictionary } } public void OptionB() { lock(m_Hash){ // Do something with the dictionary } } } ``` I'm starting to dabble in threading (primarly for creating a cache for a multi-threaded app, NOT using the HttpCache class, since it's not attached to a web site), and I see the OptionA syntax in a lot of the examples I see online, but I don't understand what, if any, reason that is done over OptionB.
Option B uses the object to be protected to create a critical section. In some cases, this more clearly communicates the intent. If used consistently, it guarantees only one critical section for the protected object will be active at a time: ``` lock (m_Hash) { // Across all threads, I can be in one and only one of these two blocks // Do something with the dictionary } lock (m_Hash) { // Across all threads, I can be in one and only one of these two blocks // Do something with the dictionary } ``` Option A is less restrictive. It uses a secondary object to create a critical section for the object to be protected. If multiple secondary objects are used, it's possible to have more than one critical section for the protected object active at a time. ``` private object m_LockerA = new object(); private object m_LockerB = new object(); lock (m_LockerA) { // It's possible this block is active in one thread // while the block below is active in another // Do something with the dictionary } lock (m_LockerB) { // It's possible this block is active in one thread // while the block above is active in another // Do something with the dictionary } ``` Option A is equivalent to Option B if you use only one secondary object. As far as reading code, Option B's intent is clearer. If you're protecting more than one object, Option B isn't really an option.
It's important to understand that lock(m\_Hash) does *NOT* prevent other code from using the hash. It only prevents other code from running that is also using m\_Hash as its locking object. One reason to use option A is because classes are likely to have private variables that you will use inside the lock statement. It is much easier to just use one object which you use to lock access to all of them instead of trying to use finer grain locks to lock access to just the members you will need. If you try to go with the finer grained method you will probably have to take multiple locks in some situations and then you need to make sure you are always taking them in the same order to avoid deadlocks. Another reason to use option A is because it is possible that the reference to m\_Hash will be accessible outside your class. Perhaps you have a public property which supplies access to it, or maybe you declare it as protected and derived classes can use it. In either case once external code has a reference to it, it is possible that the external code will use it for a lock. This also opens up the possibility of deadlocks since you have no way to control or know what order the lock will be taken in.
Difference between lock(locker) and lock(variable_which_I_am_using)
[ "", "c#", ".net", "multithreading", "" ]
I have always wondered WHaT tHE *HecK?!?* is the difference between JScript and JavaScript.
Just different names for what is really ECMAScript. John Resig has a [good explanation](http://ejohn.org/blog/versions-of-javascript/). Here's the full version breakdown: * IE 6-7 support JScript 5 (which is equivalent to ECMAScript 3, JavaScript 1.5) * IE 8 supports JScript 6 (which is equivalent to ECMAScript 3, JavaScript 1.5 - more bug fixes over JScript 5) * Firefox 1.0 supports JavaScript 1.5 (ECMAScript 3 equivalent) * Firefox 1.5 supports JavaScript 1.6 (1.5 + Array Extras + E4X + misc.) * Firefox 2.0 supports JavaScript 1.7 (1.6 + Generator + Iterators + let + misc.) * Firefox 3.0 supports JavaScript 1.8 (1.7 + Generator Expressions + Expression Closures + misc.) * The next version of Firefox will support JavaScript 1.9 (1.8 + To be determined) * Opera supports a language that is equivalent to ECMAScript 3 + Getters and Setters + misc. * Safari supports a language that is equivalent to ECMAScript 3 + Getters and Setters + misc.
As far as I can tell, two things: 1. ActiveXObject constructor 2. The idiom f(x) = y, which is roughly equivalent to f[x] = y.
What's the difference between JavaScript and JScript?
[ "", "javascript", "jscript", "" ]
I need to perform a filtered query from within a django template, to get a set of objects equivalent to python code within a view: ``` queryset = Modelclass.objects.filter(somekey=foo) ``` In my template I would like to do ``` {% for object in data.somekey_set.FILTER %} ``` but I just can't seem to find out how to write FILTER.
You can't do this, which is by design. The Django framework authors intended a strict separation of presentation code from data logic. Filtering models is data logic, and outputting HTML is presentation logic. So you have several options. The easiest is to do the filtering, then pass the result to `render_to_response`. Or you could write a method in your model so that you can say `{% for object in data.filtered_set %}`. Finally, you could write your own template tag, although in this specific case I would advise against that.
I just add an extra template tag like this: ``` @register.filter def in_category(things, category): return things.filter(category=category) ``` Then I can do: ``` {% for category in categories %} {% for thing in things|in_category:category %} {{ thing }} {% endfor %} {% endfor %} ```
How do I perform query filtering in django templates
[ "", "python", "django", "django-templates", "" ]
Because of several iframes, XUL browser elements, and so forth, I have a number of window objects in my XULRunner application. I'm looking for the best way to find the window object that a specified node belongs to using JavaScript. So, to be more specific, given node x, I need to find the specific window object that contains x.
+1 to your question, it was exactly what I was looking for and thanks for the hint given directly by answering yourself. I Googled a bit and according to <http://www.quirksmode.org/dom/w3c_html.html> cross-browsers tables I think the right answer is: ``` function GetOwnerWindow(html_node) { /* ownerDocument is cross-browser, but defaultView works on all browsers except Opera/IE that use parentWinow */ return (html_node.ownerDocument.defaultView) ? html_node.ownerDocument.defaultView : html_node.ownerDocument.parentWindow; } ``` Or maybe even better: ``` return html_node.ownerDocument.defaultView || html_node.ownerDocument.parentWindow; ``` Plz let me know your thoughts.
You may want to use **self**. self is a reference to the current document. **From within the iframe:** ``` <body> <div id="example">Example!</div> <script type="text/javascript"> window.onload = function () { var exampleNode = document.getElementById('example'); exampleNode.bar = function () { // The highest window object: top; // The parent node: self; // The parent node ( except in IE ); this.ownerDocument.defaultView; }; }; </script> </body> ``` **Traversing Multiple Window Objects:** Within the browser object model, the primary window object is referred to as **top**. Other global objects are arranged in a tree structure which stems from top. With a reference to **top**, you can navigate to the other global objects in the tree by using their **names and relationships**, much in the same way as you **traverse the DOM**. When you have multiple window objects, as you do in the case of an iframe (of with old school framesets), the frame has a **name attribute**. Given the objects position relative to the top window object, you can use the name of the child to access the object. `<iframe src ="/default.html" name="advertisement"></iframe>` and then from the context of the top window: `self.advertisement`
How can I get the window object that an HTML node belongs to using JavaScript?
[ "", "javascript", "xul", "xulrunner", "" ]
We are currently designing a website that will be accessed from kiosks in a museum. Users will need to be able to browse through a number of different web pages that will currently contain static HTML content as well as go through various interactive presentations that will be based on flash and run in flash player. Users may need to input some information into a simple registration form from the kiosk as well. One reason that we are currently designing this to run in a browser is because the same site and interactive presentations that are being accessed from the kiosks will also be available on the web. Does anyone have recommendations on whether this design will even work or whether we should simply build two versions of the content, one for web and one for kiosk? What experiences has anyone had with building a website that is available on touchscreen and via the web? This is a first time effort both for myself and for my company so any warnings, suggestions, recommendations at all would be greatly appreciated. *Note:* We are currently working with Flash to build our interactive content and a LAMPP stack for the server-side everything so SilverLight is not really an option.
You can have the same content, but you should have different CSS files. The touchscreen version will need to employ much larger fonts, and in some cases a touchscreen keyboard, whereas the home users won't need that. Further, you may want to promote museum events on the sidebar of the home version to get people to come into the museum, whereas these would be a needless distraction at the kiosks. Further, you may want to link to external websites and resources for the home user, but prevent external web browsing from inside the museum, so the stylesheet may also be used to deactivate links to external resources, without removing the text. Keep them separate using stylesheets and/or JavaScript, but try to keep the content pages the same so you don't have to maintain two sets of content. -Adam
Designing for kiosks is 90% UI optimization. Have a read through this <http://www.voltagecreative.com/blog/2008/05/best-practices-of-touch-screen-interface-design/>
Touchscreen-Oriented Website Development Recommendations for Non-Microsoft Platform
[ "", "php", "flash", "touchscreen", "kiosk", "" ]
I'm using a small site to experiment with the uploading of pictures and displaying them. When someone clicks "add a picture", they get taken to a page with a form on it. They can select a file and click the submit button. But what I want to do now is this: put a second submit button labeled "Cancel" next to the normal confirmation button. If someone then chooses to upload, selects and hits submit, if they press the cancel button before the file is fully uploaded, PHP should stop the uploading of the file and delete it. And then just go back to the overview. No Javascript used whatsoever. I only have localhost, so testing this in kindof impossible, since I just copy a file the millisecond I press the submit button. There's no upload-time with a localhost and I'm not going to buy a server somewhere just for this. Basically what's happening now is that the PHP detects which button was sent. If the submit button was sent, the file is uploaded, if the cancel button is sent, it just goes back to the overview. But PHP does its tasks one in a row. So I don't think this will work. How do I tell PHP to stop doing the upload?
You can't look at the button with php - the whole request will have been sent before PHP gets that information. What you could do is put the cancel button in a different `<form>`, like this: ``` <form> <input type="file> <input type="submit" value="upload"> </form> <form> <input type="submit" value="cancel"> </form> ``` (This is just an example of course - there's bits missing). When they click cancel, the browser should abandon its request and start a new one, cancelling the upload.
Greg has the right idea there. In stead of following the majority, or looking at how things are done, look at smart alternatives, like Greg's explanation above. Any upload cannot function without a valid link between the client and the server; hence if you close your browser window, or re-direct it to some place else, the upload is killed. use an iframe and name it eg.: "myframe". you can easily hide it in a div. have a form with your action="somefile.php" and target="myframe". add a lil Javascript to your form's "file" field: onFocus="uploadlistener()". you can name this function anything you like, but use it to check if the person "opened" anything. the browser will automatically swap focus, whether, the user clicked "browse", or if he then opened a file. difference is, after a file has been "selected", the input field receives the focus again, but remember you have a listener on the "onFocus()" event. so: if the field is not empty, call: document.uploadform.submit() Using this method, you don't even need a submit button. if you want to skin your "browse" button, just make it transparent using CSS, eg: input name="myfile" type="file" style="width: 40px; -moz-opacity: 0; filter: alpha(opacity=0)" onFocus="somefunction()" Well to cancel upload just redirect the iframe to some other place, eg: input type="button" value="cancel" onClick="document.uploadform.action='blank.php'; document.uploadform.submit()" Pardon if the html above spans across multiple lines, it's the first time I'm posting here. To track progress, you need to add a server side listener, either with PHP-5.2, or some Perl script to check how many bytes have been loaded thus far of the total file size checked before upload was started. this check interval can be achived with some AJAX, or if you don't know the term, look up: HTTP-REQUEST. this runs server side code in the background and outputs a response like you would see in the browser, but here you can capture it in a variable, and do your stuff. I hope this was helpful to anyone.
Cancel a webform submit with PHP
[ "", "php", "html", "web-services", "" ]
I'd like to install Java on a Psion 5MX with GNU/Linux 16MB RAM machine, will it be possible? Unfortunatly, ["KVM must be installed by the manufacturer"](http://www.java.com/en/download/faq/5000080100.xml). What I want is to be able to is to write basic Java code, test and sketch simple algorithms. Important notes: I don't need the graphic part since I'll only use the console (no graphic server) but this will be inside a Debian.
Please give us more details about the machine, besides the OS and the memory. Also give us details on what you hope to accomplish with Java on such an underpowered machine (Java has some big overhead in embedded places as compared to writing native code). The answer is maybe. I've seen Java running on a machine with 4MB of RAM, but it was not running Linux (in fact there was no OS at all). Link: [Java on the Nintendo DS](http://www.volny.cz/molej/pstrosnds/)
There is a [List of Java virtual machines](http://en.wikipedia.org/wiki/List_of_Java_virtual_machines "List of Java virtual machines") on Wikipedia, with a number of them open source and targeting embed devices. Like [Mika](http://www.k-embedded-java.com/mika/trac/ "Mika") which seems quite small and portable.
What is the lightest Java Virtual Machine ever? (except KVM)
[ "", "java", "jvm", "" ]
Is it possible for a generic interface's type to be based on a specific parent class? For example: ``` public interface IGenericFace<T : BaseClass> { } ``` Obviously the above code doesn't work but if it did, what I'm trying to tell the compiler is that `T` must be a sub-class of `BaseClass`. Can that be done, are there plans for it, etc.? I think it would be useful in terms of a specific project, making sure a generic interface/class isn't used with unintended type(s) at compile time. Or also to sort of self-document: show what kind of type is intended.
``` public interface IGenericFace<T> where T : SomeBaseClass ```
What your are referring to is called "Generic Constraints". There are numerous constraints that can be put on a generic type. Some basic examples are as follows: * `where T: struct` - The type argument must be a value type. Any value type except `Nullable` - can be specified. See [Using Nullable Types (C# Programming Guide)](http://msdn.microsoft.com/en-us/library/2cf62fcy.aspx) for more information. * `where T : class` - The type argument must be a reference type; this applies also to any class, interface, delegate, or array type. * `where T : new()` - The type argument must have a public parameterless constructor. When used together with other constraints, the `new()` constraint must be specified last. * `where T : <base class name>` - The type argument must be or derive from the specified base class. * `where T : <interface name>` - The type argument must be or implement the specified interface. Multiple interface constraints can be specified. The constraining interface can also be generic. * `where T : U` - The type argument supplied for `T` must be or derive from the argument supplied for `U`. This is called a naked type constraint. These can also be linked together like this: C# ``` public class TestClass<T> where T : MyBaseClass, INotifyPropertyChanged, new() { } public interface IGenericFace<T> where T : SomeBaseClass ``` VB ``` Public Class TestClass(Of T As {MyBaseClass, INotifyPropertyChanged, New}) Public Interface IGenericInterface(Of T As SomeBaseClass) ```
Can C# generics have a specific base type?
[ "", "c#", "generics", "" ]
I'm trying to make a simple C# web server that, at this stage, you can access via your browser and will just do a "Hello World". The problem I'm having is that the server can receive data fine - I get the browser's header information - but the browser doesn't receive anything I send. Furthermore, I can only connect to the server by going to localhost (or 127.0.0.1). I can't get to it by going to my IP and it's not a network setting because Apache works fine if I run that instead. Also, I'm using a port monitoring program and after I attempt a connection from a browser, the process's port gets stuck in a TIME\_WAIT state even though I told the connection to close and it should be back to LISTEN. Here's the relevant code. A couple calls might not make sense but this is a piece of a larger program. ``` class ConnectionHandler { private Server server; private TcpListener tcp; private ArrayList connections; private bool listening; private Thread listeningThread; public Server getServer() { return server; } private void log(String s, bool e) { server.log("Connection Manager: " + s, e); } private void threadedListen() { while (listening) { try { TcpClient t = tcp.AcceptTcpClient(); Connection conn = new Connection(this, t); } catch (NullReferenceException) { log("unable to accept connections!", true); } } log("Stopped listening", false); } public void listen() { log("Listening for new connections", false); tcp.Start(); listening = true; if (listeningThread != null && listeningThread.IsAlive) { listeningThread.Abort(); } listeningThread = new Thread(new ThreadStart( this.threadedListen)); listeningThread.Start(); } public void stop() { listening = false; if (listeningThread != null) { listeningThread.Abort(); log("Forced stop", false); } log("Stopped listening", false); } public ConnectionHandler(Server server) { this.server = server; tcp = new TcpListener(new IPEndPoint( IPAddress.Parse("127.0.0.1"), 80)); connections = new ArrayList(); } } class Connection { private Socket socket; private TcpClient tcp; private ConnectionHandler ch; public Connection(ConnectionHandler ch, TcpClient t) { try { this.ch = ch; this.tcp = t; ch.getServer().log("new tcp connection to " + this.tcp.Client.RemoteEndPoint.ToString(), false); NetworkStream ns = t.GetStream(); String responseString; Byte[] response; Int32 bytes; responseString = String.Empty; response = new Byte[512]; bytes = ns.Read(response, 0, response.Length); responseString = System.Text.Encoding.ASCII.GetString(response, 0, bytes); ch.getServer().log("Received: " + responseString); String msg = "<html>Hello World</html>"; String fullMsg = "HTTP/1.x 200 OK\r\n" + "Server: Test Server\r\n" + "Content-Type: text/html; " + "charset=UTF-8\r\n" + "Content-Length: " + msg.Length + "\r\n" + "Date: Sun, 10 Aug 2008 22:59:59 GMT" + "\r\n"; nsSend(fullMsg, ns); nsSend(msg, ns); ns.Close(); tcp.Close(); } catch (ArgumentNullException e) { ch.getServer().log("connection error: argument null exception: " + e); } catch (SocketException e) { ch.getServer().log("connection error: socket exception: " + e); } } private void nsSend(String s, NetworkStream ns) { Byte[] data = System.Text.Encoding.ASCII.GetBytes(s); ns.Write(data, 0, data.Length); ns.Flush(); ch.getServer().log("Sent: " + s); } } ``` Does anyone have any ideas? It feels like it's gotta be something stupid on my part but I just don't know what. I'd really appreciate any insight
You might like to know that you can use [`HttpListener`](http://msdn.microsoft.com/en-us/library/system.net.httplistener.aspx) to write a basic web-server very easily - this deals with most of the painful bits, letting you concentrate on writing the actual code. The MSDN page gives an example. Note that this uses HTTP.SYS, which is good - but means that non-admins need to be explicitly given access to open ports; on xp you can do this with `httpcfg`; on vista you can use `netsh`. See [here](https://stackoverflow.com/questions/169904/can-i-listen-on-a-port-using-httplistener-or-other-net-code-on-vista-without-re#195256) for more.
One thing which isn't a problem at the moment but might be later on is that your content length is based on the *Unicode* length of the message string, not the *binary* length. There's also rather a lot going on in the Connection constructor - stuff that really doesn't belong in a constructor at all, IMO. It also doesn't close things if exceptions occur. Have you looked at what's going on in a network tracer like WireShark? That would be the easiest way of seeing whether *any* data is getting sent back to the client. Alternatively, post a short but complete version of your code which we can compile and run ourselves.
C# Web Server Connection Problem
[ "", "c#", "connection", "" ]
I want to hold a bunch of const char pointers into an std::set container [1]. std::set template requires a comparator functor, and the standard C++ library offers std::less, but its implementation is based on comparing the two keys directly, which is not standard for pointers. I know I can define my own functor and implement the operator() by casting the pointers to integers and comparing them, but is there a cleaner, 'standard' way of doing it? Please do not suggest creating std::strings - it is a waste of time and space. The strings are static, so they can be compared for (in)equality based on their address. 1: The pointers are to static strings, so there is no problem with their lifetimes - they won't go away.
Just go ahead and use the default ordering which is less<>. The Standard guarantees that less will work even for pointers to different objects: "For templates greater, less, greater\_equal, and less\_equal, the specializations for any pointer type yield a total order, even if the built-in operators <, >, <=, >= do not." The guarantee is there exactly for things like your `set<const char*>`.
If you don't want to wrap them in `std::string`s, you can define a functor class: ``` struct ConstCharStarComparator { bool operator()(const char *s1, const char *s2) const { return strcmp(s1, s2) < 0; } }; typedef std::set<const char *, ConstCharStarComparator> stringset_t; stringset_t myStringSet; ```
Simplest, safest way of holding a bunch of const char* in a set?
[ "", "c++", "stl", "" ]
How do I force Python's `print` function to flush the buffered output to the screen? --- **See also:** [Disable output buffering](https://stackoverflow.com/questions/107705) if the goal is to change the buffering behaviour generally. This question is about explicitly flushing output after a specific `print` call, even though output is still being buffered. **For duplicate closers:** if a beginner is asking a question about trying to make output appear immediately while not using a newline at the end, **please instead use** [Why doesn't print output show up immediately in the terminal when there is no newline at the end?](https://stackoverflow.com/questions/25897335) to close the question. The current question isn't good enough because the person asking will likely **not have a concept** of buffering or flushing; the other question is intended to explain those concepts first, whereas this question is about the technical details.
In Python 3, [`print`](https://docs.python.org/library/functions.html#print) can take an optional `flush` argument: ``` print("Hello, World!", flush=True) ``` In Python 2, after calling `print`, do: ``` import sys sys.stdout.flush() ``` By default, [`print`](https://docs.python.org/2/reference/simple_stmts.html#the-print-statement) prints to [`sys.stdout`](https://docs.python.org/2/library/sys.html#sys.stdout) (see the documentation for more about [file objects](https://docs.python.org/2/library/stdtypes.html#file-objects)).
You can change the flushing behavior using the `-u` command line flag, e.g. `python -u script.py`. > -u : unbuffered binary stdout and stderr; also PYTHONUNBUFFERED=x > see man page for details on internal buffering relating to '-u' Here is the [relevant documentation](http://docs.python.org/using/cmdline.html#cmdoption-u).
How can I flush the output of the print function?
[ "", "python", "printing", "flush", "output-buffering", "" ]
I'm in the process of trying to move our company from SalesForce to SugarCRM, but I've run in to a nasty bug (the moment I add a custom field to Accounts, all accounts stop showing up). We've paid for support from the SugarCRM people, but they only have take-forever-then-get-a-worthless-response-level tech support for the open-source version (and we avoid proprietary software like the plague). Oh, and did I mention our Salesforce contract expires at the end of the week? So, long story short, I'm stuck debugging the SugarCRM app myself. I'm an decently experienced programmer, and I have baseline PHP competency, but I don't even know where to being trying to solve this issue. Can any Sugar developers out there recommend any kind of process for debugging Sugar? Are there any resources out there that would help me to understand what the different PHP files do, or how the Sugar system works overall? Just as an example of the sort of thing I'm talking about: I figured out how to get sugar to print stack traces, and by following several I noticed a pattern with all the problem lines involving ``` $this->_tpl_vars ``` I'd love to try and figure out why that method call isn't working, but I don't know: A) what `_tpl_vars` is supposed to do B) where `_tpl_vars` is defined C) what `$this` is supposed to be D) where in the framework `$this` gets set etc. So if anyone can help explain how/where I would start finding answers to these questions, I'd be incredibly grateful.
Although it's not a perfect answer to my question, this article: <http://developers.sugarcrm.com/wordpress/2008/09/26/where-is-the-code-for-x/> did help a bit. Also when I looked further through the official Sugar docs I found that the Developer Guide does contain some explanation of how Sugar works (although obviously it's not as focused on how Sugar works so much as it's focused on how to make Sugar do new things). Hope that helps any other burgeoning Sugar devs out there.
I worked with SugarCRM a couple years ago, and although I loved what I saw on the surface, I ended up rejecting it for our project because of what you are experiencing now. The internals of the product are woefully underdocumented. I had envisioned writing a bunch of slick modules for the product, but the resources just don't exist. You'll spend all your time digging through code, pouring over forum posts, and trying to find examples of what you're trying to accomplish. Doesn't sound like things have gotten much better. Given that your PHP experience is less-than-guru level, and you're undoubtedly busy with a lot of other tasks and deadlines, I think you should maybe reconsider this transition if it's not too late, at least until you get a better comfort level with Sugar. If you're forced to move to Sugar because of an expiring contract with Salesforce, I think you might be in for some serious heartburn!
How do you debug SugarCRM problems/learn how SugarCRM works?
[ "", "php", "sugarcrm", "" ]
Today I had a discussion with a colleague about nested functions in Javascript: ``` function a() { function b() { alert('boo') } var c = 'Bound to local call object.' d = 'Bound to global object.' } ``` In this example, trials point out that b is not reachable outside the body of a, much like c is. However, d is - after executing a(). Looking for the exact definition of this behaviour in the [ECMAScript v.3 standard](http://www.ecma-international.org/publications/files/ECMA-ST/Ecma-262.pdf) , I didn't find the exact wording I was looking for; what Sec.13 p.71 does not say, is which object the function object created by the function declaration statement is to be bound to. Am I missing something?
This is static scoping. Statements within a function are scoped within that function. Javascript has a quirky behavior, however, which is that without the **var** keyword, you've implied a **global variable**. That's what you're seeing in your test. Your "d" variable is available because it is an implied global, despite being written within the body of a function. Also, to answer the second part of your question: A function exists in whatever scope it is declared, just like a variable. **Sidenote:** You probably don't want global variables, especially not implied ones. It's recommended that you always use the var keyword, to prevent confusion and to keep everything clean. **Sidenote:** The ECMA Standard isn't probably the most helpful place to find answers about Javascript, although it certainly isn't a bad resource. Remember that javascript in your browser is just an implementation of that standard, so the standards document will be giving you the rules that were (mostly) followed by the implementors when the javascript engine was being built. It can't offer specific information about the implementations you care about, namely the major browsers. There are a couple of books in particular which will give you very direct information about how the javascript implementations in the major browsers behave. To illustrate the difference, I'll include excerpts below from both the ECMAScript specification, and a book on Javascript. I think you'll agree that the book gives a more direct answer. Here's from the **ECMAScript Language Specification**: > 10.2 *Entering An Execution Context* > > Every function and constructor call > enters a new execution context, even > if a function is calling itself > recursively. Every return exits an > execution context. A thrown exception, > if not caught, may also exit one or > more execution contexts. > > When control > enters an execution context, the scope > chain is created and initialised, > variable instantiation is performed, > and the this value is determined. > > The > initialisation of the scope chain, > variable instantiation, and the > determination of the this value depend > on the type of code being entered. Here's from **O'Reilly's [Javascript: The Definitive Guide (5th Edition)](http://oreilly.com/catalog/9780596101992/index.html)**: > 8.8.1 Lexical Scoping > > Functions in JavaScript are lexically > rather than dynamically scoped. This > means that they run in the scope in > which they are defined, not the scope > from which they are executed. When a > function is defined, the current scope > chain is saved and becomes part of > the internal state of the function. > ... Highly recommended for covering these kinds of questions is Douglas Crockford's book: [JavaScript, The Good Parts http://oreilly.com/catalog/covers/9780596517748\_cat.gif](http://oreilly.com/catalog/covers/9780596517748_cat.gif) [**Javascript, The Good Parts**](http://oreilly.com/catalog/9780596517748/index.html), also from O'Reilly.
As I understand it, these are equivalent as far as scoping is concerned: ``` function a() { ... } ``` and ``` var a = function() { ... } ```
What is the scope of a function in Javascript/ECMAScript?
[ "", "javascript", "functional-programming", "scope", "ecma262", "" ]
Is there any way to add a field to a class at runtime ( a field that didn't exist before ) ? Something like this snippet : ``` Myobject *ob; // create an object ob->addField("newField",44); // we add the field to the class and we assign an initial value to it printf("%d",ob->newField); // now we can access that field ``` I don't really care how it would be done , I don't care if it's an ugly hack or not , I would like to know if it could be done , and a small example , if possible . **Another Example:** say I have an XML file describing this class : ``` <class name="MyClass"> <member name="field1" /> <member name="field2" /> </class> ``` and I want to "add" the fields "field1" and "field2" to the class (assuming the class already exists) . Let's say this is the code for the class : ``` class MyClass { }; ``` I don't want to create a class at runtime , I just want to add members/fields to an existing one . Thank you !
## Use a map and a variant. For example, using boost::variant. See <http://www.boost.org/doc/libs/1_36_0/doc/html/variant.html> (But of course, you can create your own, to suit the types of your XML attributes.) ``` #include <map> #include <boost/variant.hpp> typedef boost::variant< int, std::string > MyValue ; typedef std::map<std::string, MyValue> MyValueMap ; ``` By adding MyValueMap as a member of your class, you can add properties according to their names. Which means the code: ``` oMyValueMap.insert(std::make_pair("newField", 44)) ; oMyValueMap.insert(std::make_pair("newField2", "Hello World")) ; std::cout << oMyValueMap["newField"] ; std::cout << oMyValueMap["newField2"] ; ``` By encapsulating it in a MyObject class, and adding the right overloaded accessors in this MyObject class, the code above becomes somewhat clearer: ``` oMyObject.addField("newField", 44) ; oMyObject.addField("newField2", "Hello World") ; std::cout << oMyObject["newField"] ; std::cout << oMyObject["newField2"] ; ``` But you lose somewhat the type safety of C++ doing so. But for XML, this is unavoidable, I guess.
There's no way to do it in the way you've described, since the compiler needs to resolve the reference at compile time - it will generate an error. But see [The Universal Design Pattern](http://steve-yegge.blogspot.com/2008/10/universal-design-pattern.html).
C++ dynamic class ( dynamic hack )
[ "", "c++", "dynamic", "" ]
What's the best way to use NaNs in C++? I found `std::numeric_limits<double>::quiet_NaN()` and `std::numeric_limits<double>::signaling_NaN()`. I'd like to use `signaling_NaN` to represent an uninitialized variable as follows: ``` double diameter = std::numeric_limits<double>::signaling_NaN(); ``` This, however, signals (raises an exception) on assignment. I want it to raise an exception on use, not on assignment. Is there any way to use `signaling_NaN` without raising an exception on assignment? Is there a good, portable alternative to `signaling_NaN` that will raise a floating point exception when used?
After looking into this some more, it looks like `signaling_NaN` is useless as provided. If floating point exceptions are enabled, then calling it counts as processing a signaling NaN, so it immediately raises an exception. If floating point exceptions are disabled, then processing a signaling NaN automatically demotes it to a quiet NaN, so `signaling_NaN` doesn't work either way. [Menkboy's code](https://stackoverflow.com/questions/235386/using-nan-in-c#235490) works, but trying to use signaling NaNs runs into other problems: there's no portable way to enable or disable floating point exceptions (as alluded to [here](https://stackoverflow.com/questions/85726/converting-floating-point-exceptions-into-c-exceptions#88829) and [here](https://stackoverflow.com/questions/235664/how-to-use-stdsignalingnan#236025)), and if you're relying on exceptions being enabled, third party code may disable them (as described [here](https://stackoverflow.com/questions/235664/how-to-use-stdsignalingnan#237391)). So it seems like [Motti's solution](https://stackoverflow.com/questions/235386/using-nan-in-c#236952) is really the best choice.
What signaling NAN means is that when the CPU encounters it a signal is fired, (hence the name). If you want to detect uninitialized variables then raising the warning level on your compiler usually detects all paths that use uninitalized values. Failing that you can use a wrapper class that stores a boolean saying if the value is initialized: ``` template <class T> class initialized { T t; bool is_initialized; public: initialized() : t(T()), is_initialized(false) { } initialized(const T& tt) : t(tt), is_initialized(true) { } T& operator=(const T& tt) { t = tt; is_initialized = true; return t; } operator T&() { if (!is_initialized) throw std::exception("uninitialized"); return t; } }; ```
Using NaN in C++?
[ "", "c++", "floating-point", "nan", "" ]
Is it safe to assume that two itterations over the same collection will return the objects in the same order? Obviously, it is assumed that the collection has not otherwise been changed.
Short answer - yes. Obviously, though, the order of the items in the collection may not be exactly as they were inserted, depending on the type of collection (a dictionary, for example). But you will get the same results each time you iterate over a single, unmodified collection using a foreach loop.
It depends on the collection type. For most collections, the answer is "Yes". However, this is not guaranteed. The docs of a collection type should specify whether or not it does, but as most do, that detail is generally over looked. However, if it is not stable, it would be a tremendous oversight if the docs didn't mention that.
Is the order of objects returned by FOREACH stable?
[ "", "c#", ".net", "collections", "foreach", "ienumerable", "" ]
If you throw an exception from inside an MFC dialog, the app hangs, even if you have a catch block in your code. It refuses to respond to the mouse or keyboard, and the only way to shut it down is to use Task Manager. ### Why I'm posting this question To my shame, there is a popular shrink-wrapped application that hangs every time it encounters an exceptional error in a modal dialog. When we made a massive shift from integer error codes to exceptions, I was responsible for choosing std::exception as the base class for the thrown exceptions. It wasn't until a huge amount of work went into the conversion that our testing uncovered this problem, and by then it was too late to change. Hopefully this question/answer will keep someone from making the same mistake.
The code for CDialog::DoModal makes the dialog modal by disabling the parent window. When the dialog code returns, the window is reenabled. There is an explicit catch for CException\* errors, but not for any other kind of thrown exception; thus the parent window never gets reenabled. Change your code to throw a pointer to any exception derived from CException, and you'll fix the problem.
If you are interested in learning about how Windows detects apphangs we have added some posts to this on the Windows Error Reporting blog: [Let there be hangs part 1 of 4](http://blogs.msdn.com/wer/archive/2009/03/19/let-there-be-hangs-part-1-not-responding.aspx) [Let there be hangs part 2 of 4](http://blogs.msdn.com/wer/archive/2009/03/19/let-there-be-hangs-part-2-wer-history-101.aspx) [Let there be hangs part 3 of 4](http://blogs.msdn.com/wer/archive/2009/03/19/let-there-be-hangs-part-3-the-hungapp-module.aspx) [Let there be hangs part 4 of 4](http://blogs.msdn.com/wer/archive/2009/03/19/let-there-be-hangs-part-4-better-bucketing-in-windows-vista.aspx) Important to note is that this information when sent through Microsoft's Windows Error Reporting gets communicated to the software developers to try and fix these issues. If you are sending in your error reports you WILL help fix issues that are occuring on your PC! I am a Program Manager at Microsoft on the Windows Error Reporting team.
Why does my MFC app hang when I throw an exception?
[ "", "c++", "windows", "mfc", "" ]
Finding out what's selected in real browsers is as simple as: ``` var range = { start: textbox.selectionStart, end: textbox.selectionEnd } ``` But IE, as usual, doesn't understand. What's the best cross-browser way to do this?
I'll post this function for another time, seeing as this question got linked to from another one. The following will do the job in all browsers and deals with all new line problems without seriously compromising performance. I've arrived at this after [some toing and froing](https://stackoverflow.com/questions/3622818/ies-document-selection-createrange-doesnt-include-leading-or-trailing-blank-lin) and now I'm pretty convinced it's the best such function around. **UPDATE** This function does assume the textarea/input has focus, so you may need to call the textarea's `focus()` method before calling it. ``` function getInputSelection(el) { var start = 0, end = 0, normalizedValue, range, textInputRange, len, endRange; if (typeof el.selectionStart == "number" && typeof el.selectionEnd == "number") { start = el.selectionStart; end = el.selectionEnd; } else { range = document.selection.createRange(); if (range && range.parentElement() == el) { len = el.value.length; normalizedValue = el.value.replace(/\r\n/g, "\n"); // Create a working TextRange that lives only in the input textInputRange = el.createTextRange(); textInputRange.moveToBookmark(range.getBookmark()); // Check if the start and end of the selection are at the very end // of the input, since moveStart/moveEnd doesn't return what we want // in those cases endRange = el.createTextRange(); endRange.collapse(false); if (textInputRange.compareEndPoints("StartToEnd", endRange) > -1) { start = end = len; } else { start = -textInputRange.moveStart("character", -len); start += normalizedValue.slice(0, start).split("\n").length - 1; if (textInputRange.compareEndPoints("EndToEnd", endRange) > -1) { end = len; } else { end = -textInputRange.moveEnd("character", -len); end += normalizedValue.slice(0, end).split("\n").length - 1; } } } } return { start: start, end: end }; } var el = document.getElementById("your_input"); el.focus(); var sel = getInputSelection(el); alert(sel.start + ", " + sel.end); ```
IE's Range implementation is a slithy horror. It really wants you to use the execrable execCommand interface instead of anything involving indexing into the text. There are two approaches I know of for getting the indices and they both have problems. The first uses range.text as in your example code. Unfortunately range.text has a habit of stripping off leading and trailing newlines, which means if the caret/selection is at the start of a line other than the first one, beforeLength will be off by (number of newlines\*2) characters and you'll get the wrong selected text. The second approach is to use range.moveStart/End (on a duplicated range), as outlined in the answer to this question: [Character offset in an Internet Explorer TextRange](https://stackoverflow.com/questions/164147/character-offset-in-an-internet-explorer-textrange) (however as you are using a known textarea parent you can ignore the stuff about node-finding). This doesn't have the same problem, but it does report all indices as if newlines were simple LF characters, even though textarea.value and range.text will return them as CRLF sequences! So you can't use them directly to index into the textarea, but you can either fix them up with a bunch of newline counting or just string-replace away all the CRs from the value before you use it.
Is there an Internet Explorer approved substitute for selectionStart and selectionEnd?
[ "", "javascript", "internet-explorer", "selection-api", "" ]