Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
I have a web page where i have 2 forms when i click the enter key, I am calling a javascript function to force the page to load another page.My code is ``` function SearchUser() { var text = document.getElementById("searchItem").value; text = text == "" ? -1 : text; var by = document.getElementById("listBy").value; var on=""; if(by==1) { on="USERNAME"; } else if(by==2) { on="FIRSTNAME"; } else if(by==3) { on="EMAIL_ID"; } gotoUrl="userlist.php?searchItem="+text+"&onSearch="+on; alert(gotoUrl); window.navigate=gotoUrl; ``` } and ``` $(document).ready(function() { $("#frmUserListSearch").keyup(function(event) { if(event.keyCode == 13) { SearchUser(); } }); ``` }); But the page is doing a form submit when the SearchUSer function being called.I am getting the correct url in the alert.But The page is not loading in the brower Any Ideas ??? Thanks in advance
``` if (document.addEventListener) { document.getElementById('strip').addEventListener('keypress',HandleKeyPress,false); } else { document.getElementById('strip').onkeypress = HandleKeyPress; } function HandleKeyPress(e) { switch (e.keyCode) { case e.DOM_VK_ENTER: if (e.preventDefault) e.preventDefault(); else e.returnValue = false; } } ``` EDIT due to original Question edit: all you need is: ``` $(document).ready(function() { $("#frmUserListSearch").keyup(function(event) { if(event.keyCode == 13) { SearchUser(); if (e.preventDefault) e.preventDefault(); else e.returnValue = false; } }); }); ``` edited to reflect comment
Returning false often does the trick. <http://javascript.about.com/library/bldisdef.htm>
Javascript:Block form submit on Enter Key press
[ "", "javascript", "forms", "submit", "" ]
What results when you pass an empty `String` (or some other unrecognized value, or a `null`) to a Java enum `.valueOf` call? For example: ``` public enum Status { STARTED, PROGRESS, MESSAGE, DONE; } ``` and then ``` String empty = ""; switch(Status.valueOf(empty)) { case STARTED: case PROGRESS: case MESSAGE: case DONE: { System.out.println("is valid status"); break; } default: { System.out.println("is not valid"); } } ``` --- Basically, I want to know if I'm using a switch statement with the enum, will the default case be called or will I get an exception of some sort?
You should get an `IllegalArgumentException` if the name is not that of an enum (which it won't be for the empty string). This is generated in the API docs for all enum `valueOf` methods. You should get a `NullPointerException` for `null`. It's probably not a good idea to give a dummy value to your `String` variable (nor to allow the last `case`/`default` to fall through).
I just tried your code. It throws an `IllegalArgumentException`. Just like the documentation says.
What results when you pass an invalid String to a Java enum .valueOf call?
[ "", "java", "enums", "" ]
I'm very new to C#. My boss asked me to wrote some code using listview as a file browser. I tried it and it seems it works. This code is to open the files from your drives and display it on the listView. It's very simple. I also made an additional function where one can clear the displayed items in the listView. I would like to add additional feature, where I can also open the directory and not only the files. By the way, here is the sample of my code: ``` private void btnOpen_Click(object sender, EventArgs e) { string strSelectedPath; folderBrowserDialog1.ShowDialog(); strSelectedPath = folderBrowserDialog1.SelectedPath; label1.Text = strSelectedPath; DirectoryInfo di = new DirectoryInfo(strSelectedPath); FileInfo[] files = di.GetFiles(); foreach (FileInfo file in files) { listView1.Items.Add(file.Name); } } private void btnClear_Click(object sender, EventArgs e) { listView1.Items.Clear(); label1.Text=""; } ``` Could you please show me how?
If I understand your question correctly (you want to list not only the files in the selected directory, but also the sub-directories), you will want to look into the [GetDirectories](http://msdn.microsoft.com/en-us/library/s7xk2b58.aspx) method of the DirectoryInfo class. You could do something like this, perhaps: ``` DirectoryInfo di = new DirectoryInfo(strSelectedPath); // first list sub-directories DirectoryInfo[] dirs = di.GetDirectories(); foreach (DirectoryInfo dir in dirs) { listView1.Items.Add(dir.Name); } // then list the files FileInfo[] files = di.GetFiles(); foreach (FileInfo file in files) { listView1.Items.Add(file.Name); } ``` Update: I would suggest that you move the above code into a separate method that takes a string parameter for the path (something like `ListDirectoryContents(string path)`). In this method you can start with clearing the items from the list view, setting the label text and then adding new content as above. This method can be called from your `btnOpen_Click` method, passing `folderBrowserDialog1.SelectedPath` in the path parameter. I usually try to keep my event handlers as small as possible, preferably not performing any real work but rather just call some other method that does the work. This opens up a bit more for triggering the same functionality from other places. Say for instance that your application can take a path as a command line parameter, then it will be cleaner code just calling `ListDirectoryContents` with the path from the command line than perhaps duplicating the same behaviour in your form. Full code example of that approach: ``` private void btnOpen_Click(object sender, EventArgs e) { string path = BrowseForFolder(); if (path != string.Empty) { ListDirectoryContent(path); } } private string BrowseForFolder() { FolderBrowserDialog fbd = new FolderBrowserDialog(); if (fbd.ShowDialog() == DialogResult.OK) { return fbd.SelectedPath; } return string.Empty; } private void ListDirectoryContent(string path) { label1.Text = path; listView1.Items.Clear(); DirectoryInfo di = new DirectoryInfo(path); // first list sub-directories DirectoryInfo[] dirs = di.GetDirectories(); foreach (DirectoryInfo dir in dirs) { listView1.Items.Add(dir.Name); } // then list the files FileInfo[] files = di.GetFiles(); foreach (FileInfo file in files) { listView1.Items.Add(file.Name); } } ``` The upsides of this code is that you can reuse the method BrowseForFolder whenever you need to browse for a folder, since it simply returns the selected path and is not connected to what the path will be used for. Similarly, the ListDirectoryContent method is completely unaware of from where the path parameter comes; it may come from the folder browser, it may come from the command line or anywhere else. If you focus on having your methods performing only their "core task", relying on input parameters for any additional information that they need you will get code that is easier to reuse and maintain. When it comes to event handlers (such as btnOpen\_Click), I like to see them as triggers; they trigger things to happen, but the don't really do a lot themselves.
The DirectoryInfo class contains a GetDirectories method, as well as a GetFiles method. See your original code sample below, modified to add directories: ``` private void btnOpen_Click(object sender, EventArgs e) { string strSelectedPath; folderBrowserDialog1.ShowDialog(); strSelectedPath = folderBrowserDialog1.SelectedPath; label1.Text = strSelectedPath; DirectoryInfo di = new DirectoryInfo(strSelectedPath); FileInfo[] files = di.GetFiles(); DirectoryInfo[] directories = di.GetDirectories(); foreach (DirectoryInfo directory in directories) { listView1.Items.Add("Directory " + directory.Name); } foreach (FileInfo file in files) { listView1.Items.Add(file.Name); } } ```
listview opening directories
[ "", "c#", "" ]
The below MSSQL2005 query is very slow. I feel like their ought to be a way to speed it up, but am unsure how. Note that I editted the inner join to use select statements to make it more obvious (to people reading this question) what is going on, though this has no impact on speed (probably the Execution plan is the same either way). Interestingly, I never actually use keywordvaluegroups for anything more than a count, but I'm not sure if there is a way to capitalize on this. ``` select top 1 cde.processPath as 'keywordValue', count(*) as 'total' from dbo.ClientDefinitionEntry AS cde INNER JOIN dbo.KeywordValueGroups AS kvg ON cde.keywordGroupId = kvg.keywordValueGrpId where kvg.[name] = @definitionName group by cde.processPath order by total desc ``` Edit: Apparently, people keep complaining about my use of subqueries. In fact, it makes no difference. I added them right before posting this question to make it easier to see what is going on. But they only made things more confusing, so I changed it not to use them. Edit: Indexes in use: ``` ClientDefinitionEntry: IX_ClientDefinitionEntry |nonclustered located on PRIMARY|clientId, keywordGroupId KeyWordValueGroups IX_KeywordValueGroups |nonclustered located on PRIMARY|keywordValueGrpId IX_KeywordValueGroups_2 |nonclustered located on PRIMARY|version IX_KeywordValueGroups_Name |nonclustered located on PRIMARY|name ```
I'd make sure you had the following indexes. The ID on KeywordValueGroups. The Name on KeywordValueGroups. The ID on ClientDefinitionEntry with an INCLUDE for the processPath. ``` CREATE INDEX [IX_ClientDefinitionEntry_Id_ProcessPath] ON [dbo].[ClientDefinitionEntry] ( [keywordGroupId] ASC ) INCLUDE ( [processPath]) ON [PRIMARY] CREATE INDEX [IX_KeywordValueGroups_Id] ON [dbo].[KeywordValueGroups] ( [keywordValueGrpId] ASC ) CREATE INDEX [IX_KeywordValueGroups_Name] ON [dbo].[KeywordValueGroups] ( [name] ASC ) ``` I'd also change the query to the following. ``` select top 1 cde.processPath as 'keywordValue', count(*) as 'total' from dbo.ClientDefinitionEntry AS cde INNER JOIN dbo.KeywordValueGroups AS kvg ON cde.keywordGroupId = kvg.keywordValueGrpId where kvg.[name] = @definitionName group by processPath order by total desc ```
How does the execution plan looks like ? By having a look at it, you'll learn which part of the query takes the most time / resources. Have you indexes on the columns where you filter on ? Have you indexes on the columns that you use for joining ? Have you indexes on the columns that you use for sorting ? once you've taken a look at this, and the query is still slow, you can take a look at how your database / table is fragmented (dbcc showcontig), and see if it is necessary to rebuild the indexes. It might be helpfull to have a maintenance plan which rebuilds your indexes on a regular basis.
SQL Optimization Query
[ "", "sql", "sql-server", "performance", "" ]
Does someone know how well the following 3 compare in terms of speed: * shared memory * tmpfs (/dev/shm) * mmap (/dev/shm) Thanks!
Read about `tmpfs` [here](http://lwn.net/2001/1206/a/tmpfs.php3). The following is copied from that article, explaining the relation between shared memory and `tmpfs` in particular. ``` 1) There is always a kernel internal mount which you will not see at all. This is used for shared anonymous mappings and SYSV shared memory. This mount does not depend on CONFIG_TMPFS. If CONFIG_TMPFS is not set the user visible part of tmpfs is not build, but the internal mechanisms are always present. 2) glibc 2.2 and above expects tmpfs to be mounted at /dev/shm for POSIX shared memory (shm_open, shm_unlink). Adding the following line to /etc/fstab should take care of this: tmpfs /dev/shm tmpfs defaults 0 0 Remember to create the directory that you intend to mount tmpfs on if necessary (/dev/shm is automagically created if you use devfs). This mount is _not_ needed for SYSV shared memory. The internal mount is used for that. (In the 2.3 kernel versions it was necessary to mount the predecessor of tmpfs (shm fs) to use SYSV shared memory) ``` So, when you actually use POSIX shared memory (which i used before, too), then `glibc` will create a file at `/dev/shm`, which is used to share data between the applications. The file-descriptor it returns will refer to that file, which you can pass to `mmap` to tell it to map that file into memory, like it can do with any "real" file either. The techniques you listed are thus complementary. They are not competing. `Tmpfs` is just the file-system that provides in-memory files as an implementation technique for `glibc`. As an example, there is a process running on my box currently having registered such a shared memory object: ``` # pwd /dev/shm # ls -lh insgesamt 76K -r-------- 1 js js 65M 24. Mai 16:37 pulse-shm-1802989683 # ```
"It depends." In general, they're all in-memory and dependent upon system implementation so the performance will be negligible and platform-specific for most uses. If you really care about performance, you should profile and determine your requirements. It's pretty trivial to replace any one of those methods with another. That said, shared memory is the least intensive as there are no file operations involved (but again, very implementation-dependent). If you need to open and close (map/unmap) repeatedly, *lots* of times, then it could be significant overhead. Cheers! Sean
Shmem vs tmpfs vs mmap
[ "", "c++", "linux", "mmap", "" ]
I have something like this: ``` Map<String, String> myMap = ...; for(String key : myMap.keySet()) { System.out.println(key); System.out.println(myMap.get(key)); } ``` So is `myMap.keySet()` called once in the **foreach loop**? I think it is, but want your opinion. I would like to know if using foreach in this way (`myMap.keySet()`) has a performance impact or it is equivalent to this: ``` Set<String> keySet = myMap.keySet(); for (String key : keySet) { ... } ```
If you want to be absolutely certain, then compile it both ways and decompile it and compare. I did this with the following source: ``` public void test() { Map<String, String> myMap = new HashMap<String, String>(); for (String key : myMap.keySet()) { System.out.println(key); System.out.println(myMap.get(key)); } Set<String> keySet = myMap.keySet(); for (String key : keySet) { System.out.println(key); System.out.println(myMap.get(key)); } } ``` and when I decompiled the class file with [Jad](http://www.varaneckas.com/jad), I get: ``` public void test() { Map myMap = new HashMap(); String key; for(Iterator iterator = myMap.keySet().iterator(); iterator.hasNext(); System.out.println((String)myMap.get(key))) { key = (String)iterator.next(); System.out.println(key); } Set keySet = myMap.keySet(); String key; for(Iterator iterator1 = keySet.iterator(); iterator1.hasNext(); System.out.println((String)myMap.get(key))) { key = (String)iterator1.next(); System.out.println(key); } } ``` So there's your answer. It is called once with either for-loop form.
It's only called once. In fact it uses an iterator to do the trick. Furthermore, in your case, I think you should use ``` for (Map.Entry<String, String> entry : myMap.entrySet()) { System.out.println(entry.getKey()); System.out.println(entry.getValue()); } ``` to avoid searching in the map each time.
Java foreach efficiency
[ "", "java", "performance", "loops", "foreach", "premature-optimization", "" ]
I need to clear all APC cache entries when I deploy a new version of the site. APC.php has a button for clearing all opcode caches, but I don't see buttons for clearing all User Entries, or all System Entries, or all Per-Directory Entries. Is it possible to clear all cache entries via the command-line, or some other way?
You can use the PHP function `apc_clear_cache`. Calling `apc_clear_cache()` will clear the system cache and calling `apc_clear_cache('user')` will clear the user cache.
I don't believe any of these answers actually work for clearing the APC cache from the command line. As [Frank Farmer](https://stackoverflow.com/questions/911158/how-to-clear-apc-cache-entries/911219#911219) commented above, the CLI runs in a process separate from Apache. My solution for clearing from the command line was to write a script that copies an APC clearing script to the `web` directory and accesses it and then deletes it. The script is restricted to being accessed from the localhost. 1. **apc\_clear.php** This is the file that the script copies to the web directory, accesses, and deletes. ``` <?php if (in_array(@$_SERVER['REMOTE_ADDR'], array('127.0.0.1', '::1'))) { apc_clear_cache(); apc_clear_cache('user'); apc_clear_cache('opcode'); echo json_encode(array('success' => true)); } else { die('SUPER TOP SECRET'); } ``` 2. **Cache clearing script** This script copies apc\_clear.php to the web directory, accesses it, then deletes it. This is based off of a Symfony task. In the Symfony version, calls are made to the Symfony form of copy and unlink, which handle errors. You may want to add checks that they succeed. ``` copy($apcPaths['data'], $apcPaths['web']); //'data' is a non web accessable directory $url = 'http://localhost/apc_clear.php'; //use domain name as necessary $result = json_decode(file_get_contents($url)); if (isset($result['success']) && $result['success']) { //handle success } else { //handle failure } unlink($apcPaths['web']); ```
How to clear APC cache entries?
[ "", "php", "performance", "caching", "apc", "" ]
I am trying a simple Extension Method example and am unable to increment or decrement an int. Here is the code ``` static class ExtensionMethodsExp { public static void Print(this object o) { Console.WriteLine("This is print: {0}", o.ToString()); } public static int Double(this int i) { return i * 2; } public static int Decrement(this int i) { return i--; } public static int Increment(this int i) { return i++; } } ``` } Program Code is ``` class Program { static void Main(string[] args) { int myNumber = 10; myNumber.Print(); myNumber = myNumber.Double(); myNumber.Print(); myNumber = myNumber.Decrement(); myNumber.Print(); myNumber = myNumber.Increment(); myNumber.Print(); myNumber.Increment().Double().Print(); Console.ReadKey(); } } ``` I am getting following as output This is print: 10 This is print: 20 This is print: 20 This is print: 20 This is print: 40 Any idea why Decrement or Increment should not work here. Is there something I am missing? thanks
Try this: ``` public static int Decrement(this int i) { return --i; } public static int Increment(this int i) { return ++i; } ```
The reason your code is not working is because of the way you are using the Increment and Decrement operators. When you write: ``` return i++; ``` The value of i is returned BEFORE the increment occurs. Try this: ``` return ++i; ``` or better yet, this: ``` return i + 1; ```
C# Extension Method not working for increment and decrement scenarios, is it by design?
[ "", "c#", "extension-methods", "" ]
How do you get a list of all the tables and use that list to enumerate the columns? I've found posts that describe one or the other, but not both. My net-result is I want to generate a static class which contains names of all the columns in each tables so I could, for example, do: ``` comboBoxFoo.DisplayMember = SomeNamespace.SomeTable.SomeDisplayColumnName; comboBoxFoo.ValueMember = SomeNamespace.SomeTable.SomeIDColumnName; comboBoxFoo.DataSource = dingo; ``` I'm currently using [this](https://stackoverflow.com/questions/360990/how-would-i-get-the-column-names-from-a-model-linq/363746#363746) method which while it works, it means I have to manually create my tables in a list. I have a seperate command line project which generates the SomeNameSpace.SomeTable class manually and I add the generated class file in to the project. Ideally, if I could loop through via a foreach of tables and do something like this: ``` foreach(var table in someTableNumerationMethodForAGivenContext()) { var columnList = databaseContext.ColumnNames<someTable>(); foreach(var columnData in columnList) { DoJazz(columnData.Name); } } ``` Is there a better way to do this other than manually have to do the databaseContext.ColumnNames() ? Edit 1: We're using LinqToSQL. Moving to ADO.NET also an option on the table, but at the moment we have no pressing need to. Edit 2: I know L2S does databinding but what I'm after is getting a list of column names as strings from a table. L2S doesn't offer this or it's not apparent on my side. I'd like to do something like: SomeTable.SomeColumn.ToString() or something. SubSonic has this. Final: Thanks everyone. all are very good answers and lead me to the answer. You guys rock!
Nazadus, Is this what you are looking for? LINQ to SQL Trick: Get all Table [and Column] Names: <http://blogs.msdn.com/jomo_fisher/archive/2007/07/30/linq-to-sql-trick-get-all-table-names.aspx>
What you are describing is essentially an [ORM](http://en.wikipedia.org/wiki/Object-relational_mapping) Linq to SQL is an ORM that will create prototype c# classes for you that contain the information you are describing. It has excellent support for the kind of data binding that you have illustrated.
LINQ table enumeration with column enumeration
[ "", "c#", "linq", "" ]
I'm looking for something (preferably a Firefox extension) which will allow me to see all AJAX subrequests. Basically, anytime an XMLHTTPRequest() is made, I want to know what URL was being requested and what (if any) GET and POST vars were passed along with it. Unless I'm missing it, I don't see anything quite like this in Firebug or Web Developer Toolbar. *(In case you're curious, the main reason for wanting this is that I want to scrape a local copy of a site that is using JS to load all its contents, and I don't want to spend hours digging through their JS code when I could just see the subrequests being made.)*
[Firebug](http://getfirebug.com/) should show it in the Net panel. **EDIT**: Also, if Firebug slows down your Firefox in a way that makes it unusable, like it does for me sometimes, [WireShark](http://www.wireshark.org/) (formerly Ethereal) will analyze all network traffic on your system, including HTTP and AJAX requests.
[Fiddler 2](http://www.fiddler2.com/fiddler2/) is a great tool for watching HTTP traffic. **\* 2014 Update \*** Since my original post, both Internet Explorer and Chrome have added built-in developer tools that are quite useful. While I still support and use Fiddler for non-web related http monitoring or when I need to really dig in deep and modify requests in transit, these days I find myself pretty much using IE or Chrome's built in tools as they are sufficient for 99% of my needs. They both have a networking tab, where you can monitor http requests, plus other nifty features for debugging webpages. * [Internet Explorer F12 Tools Introduction](http://msdn.microsoft.com/en-us/library/ie/gg589512(v=vs.85).aspx) * [Documentation for Chrome's F12 Tools](https://developer.chrome.com/devtools) * [FireBug, which is mentioned above](https://stackoverflow.com/a/911214/86860) is also a good tool if you're using FireFox.
What's an easy way to see what AJAX calls are being made?
[ "", "javascript", "ajax", "debugging", "xmlhttprequest", "" ]
My kiddo had a homework assignment to write Blackjack in Java. I helped him a little but for the most part he did it all himself and it actually plays pretty well. He even caught an error I didn't see in how it was calculating hand values. However, there is a snag that he hasn't dealt with and every solution I can think of is really complicated and way beyond what he's going to be able to easily code up with his still rudimentary Java skills. The Ace. In fact, not just one Ace, there's four of them and you could possibly get all four of them in a single hand. How do you elegantly deal with calculating the value of a hand of cards when there's one or more Aces, each of which might be valued at one or eleven. I feel like there should be a graceful algorithm for it, but I'm not seeing it. Of course, part of it could just be that I'm tired, but maybe you can help.
Just treat each ace as 11. Then while the value is over 21, subtract 10 from your total for each ace in your hand.
You will only ever use 1 ace for the 11 points. So calculate all but the last ace as 1 and if have 10 or less points, the last ace counts as 10.
Is there an elegant way to deal with the Ace in Blackjack?
[ "", "java", "blackjack", "" ]
In "THE Java™ Programming Language, Fourth Edition" By Ken Arnold, James Gosling, David Holmes, its mentioned that: **paragraph: (4.3.2)** *"Similarly, if an interface inherits more than one method with the same signature, or if a class implements different interfaces containing a method with the same signature, there is only one such method. The implementation of this method is ultimately defined by the class implementing the interfaces, and there is no ambiguity there. If the methods have the same signature but different return types, then one of the return types must be a subtype of all the others, otherwise a compile-time error occurs. The implementation must define a method that returns that common subtype."* **Can anybody give me some example code that justifies the points of above paragraph ?** I tried to write the code and test what is mentioned but I am getting compile-time error the sub-interface hides the base interface method so can only implement sub-interface method. Thanks in advance. -Arun
In the following two interfaces `methodA()` is identically defined in terms of parameters (none) and return type (int). The implementation class at the bottom defines a single method with this exact signature. As it complies to both interfaces, you get no problem there - any calls made via a reference of type InterfaceA or InterfaceB will be dispatched to this implementation. The second `methodB()` is defined as returning any subtype of `Number` (or `Number` itself) in `InterfaceA`. `InterfaceB` defines `methodB()` as returning an `Integer` which is a subtype of `Number`. The implementation class actually implements the method with `Integer`, thus complying to the contract of both `InterfaceA` and `InterfaceB`. No problem here either. The commented out case of `methodB()` being implemented as returning a `Double` however would not work: While it would satisfy the contract of `InterfaceA`, it would conflict with `InterfaceB` (which demands an `Integer`). If `InterfaceA` and `InterfaceB` were also specifying (different) contracts for a `methodC()` (commented out in the example) this would be contradictory and create a compiler error. Implementing both signatures (differing only in return type) is not allowed in Java. The above rules would also hold true if were to add any parameters to the methods. For simplicity I kept this out of the example. ``` public interface InterfaceA { public int methodA(); public Number methodB(); // public int methodC(); // conflicting return type } public interface InterfaceB { public int methodA(); public Integer methodB(); // public String methodC(); // conflicting return type } public class ImplementationOfAandB implements InterfaceA, InterfaceB { public int methodA() { return 0; } public Integer methodB() { return null; } // This would NOT work: // public Double methodB() { // return null; // } } ```
``` interface A { void method(); Object returnMethod(); } interface B { void method(); B returnMethod(); } class Impl implements A,B { void method() { } B returnMethod() { } } ``` As you can see, `Impl.method()` implements both `A.method()` and `B.method()`, while `Impl.returnMethod()` returns a `B`, which is a child of `Object`, thus fulfilling `A.returnMethod()`'s contract too. Would the latter require a return type that is not a parent of `B.returnMethod()`'s return type that would be a comile error, since no such implementation could exist in `Impl`.
Java Interface: Inheriting, Overriding, and Overloading Methods
[ "", "java", "interface", "overriding", "overloading", "" ]
Is there a way to get session management or security programatically in Jersey, e.g. web-application session management? Or are transactions, sessions, and security all handled by the container in which the Jersey application is deployed?
Session management is the purview of the container in which Jersey is deployed. In most production cases, it will be deployed within a container that performs session management. The code below is a simple example of a jersey resource that gets the session object and stores values in the session and retrieves them on subsequent calls. ``` @Path("/helloworld") public class HelloWorld { @GET @Produces("text/plain") public String hello(@Context HttpServletRequest req) { HttpSession session= req.getSession(true); Object foo = session.getAttribute("foo"); if (foo!=null) { System.out.println(foo.toString()); } else { foo = "bar"; session.setAttribute("foo", "bar"); } return foo.toString(); } } ```
> I thought that sessions is something we should **never** use in > RESTful applications... Yegor is right. We shouldn't never maintain state in the server side *a la* conventional web application. If you want to build a decoupled SOA-oriented application you don't need to use any API/framework for REST web services. If you need, or want, to maintain the global client-server state in the server side you are implicitly building what we could describe as a SOA-oriented [web]app, but using Jersey like a [web] development framework of sorts. Inadvertently you are twisting the nature of a web service (REST or otherwise). You **can** do it in the way it's been suggested in the first answer, but you **mustn't**. The final result is not a web service, just a regular app constructed with web services' tools. -\_o
jersey security and session management
[ "", "java", "jersey", "" ]
I am very new to C++ programming and you will see why. I want to make a character array consisting of a few words that I want to search with a linear search function. Does this array have to be a two-dimensional array? For example: ``` char Colors[3][6] = {"red", "green", "blue"}; ``` I tried it like this: ``` char Colors[] = {"red", "green", "blue"}; ``` This gave me a "too many initializers" error. I assume the 1st method is correct because it states the amount of elements in the array and the maximum length of an element, correct? Now how would I implement a linear search function to find a word inside that array? Can I do something like the following: (Assuming the linearSearch function has already been declared) ``` char searchKey; char element; char Colors[3][6] = {"red", "green", "blue"}; printf("Enter the color to look for: \n"); scanf("%s", searchKey); element = linearSearch(Colors, searchKey, ??); //?? is where I don't know what to enter if (element != -1) { printf("Found the word.\n"); } else { printf("Didn't find the word.\n"); } ``` Is this possible? If so, what would the declaration look for the linearSearch function? I hope I provided enough information for this to be somewhat usable. edit: Thanks all for the help, got the program working as intended.
You could make your linearSearch function to return the index of the search term in the array. Here is a sample program: ``` #include <stdio.h> #include <string.h> int linearSearch (const char **Array, const char *searchKey, int arraySize) { for (int i = 0; i < arraySize; ++i) { if (strcmp(Array[i], searchKey) == 0) return i; } // We didn't find the searchKey in the Array return -1; } int main () { char *colors[] = { "red", "green", "blue" }; int index = linearSearch (colors, "green", 3); if (index < 0) { // search string was not found printf("Search string not found!\n"); } else { printf("String %s found at index %d\n", colors[index], index); } return 0; } ``` We use the strcmp() function to compare the strings. It returns zero if strings match and nonzero if they don't. To use it, you need to include the `string.h` header. But, as others have suggested, you should use STL if you can.
I would recommend to learn about the C++ standard library, which would help you very much. For example, ``` #include <vector> #include <string> #include <algorithm> #include <iostream> using namespace std; vector<string> words; words.push_back("red"); words.push_back("blue"); words.push_back("green"); if (find(words.begin(), words.end(), "green") != words.end()) cout << "found green!" else cout << "didn't find it"; ``` Why implement `linearSearch` yourself? c++ already has `std::find` which does it for you! Moreover, if you use a `set` instead of a `vector`, you can now use `std::binary_search` which is O(log n) instead of O(n), since a set is sorted.
Linear Search in a Char Array -- C++ (Visual Studio 2005)
[ "", "c++", "arrays", "search", "visual-c++-2005", "" ]
I want to avoid placing an EditorAttribute on every instance of a certain type that I've written a custom UITypeEditor for. I can't place an EditorAttribute on the type because I can't modify the source. I have a reference to the only PropertyGrid instance that will be used. Can I tell a PropertyGrid instance (or all instances) to use a custom UITypeEditor whenever it encounters a specific type? [Here](http://msdn.microsoft.com/en-us/magazine/cc163804.aspx) is an MSDN article that provides are starting point on how to do this in .NET 2.0 or greater.
You can usually associate editors etc at runtime via `TypeDescriptor.AddAttributes`. For example (the `Bar` property should show with a "..." that displays "Editing!"): ``` using System; using System.ComponentModel; using System.Drawing.Design; using System.Windows.Forms; class Foo { public Foo() { Bar = new Bar(); } public Bar Bar { get; set; } } class Bar { public string Value { get; set; } } class BarEditor : UITypeEditor { public override UITypeEditorEditStyle GetEditStyle(ITypeDescriptorContext context) { return UITypeEditorEditStyle.Modal; } public override object EditValue(ITypeDescriptorContext context, IServiceProvider provider, object value) { MessageBox.Show("Editing!"); return base.EditValue(context, provider, value); } } static class Program { [STAThread] static void Main() { TypeDescriptor.AddAttributes(typeof(Bar), new EditorAttribute(typeof(BarEditor), typeof(UITypeEditor))); Application.EnableVisualStyles(); Application.Run(new Form { Controls = { new PropertyGrid { SelectedObject = new Foo() } } }); } } ```
Marc's solution bluntly applies the EditorAttribute to the Bar type globally. If you have a delicate disposition, you might rather annotate properties of a specific instances. Alas, that isn't possible with `TypeDescriptor.AddAttributes` My solution was to write a wrapper `ViewModel<T>`, which copies properties from T, annotating some with extra attributes. Suppose we have a variable `datum` of type Report, we'd use it like this ``` var pretty = ViewModel<Report>.DressUp(datum); pretty.PropertyAttributeReplacements[typeof(Smiley)] = new List<Attribute>() { new EditorAttribute(typeof(SmileyEditor),typeof(UITypeEditor))}; propertyGrid1.SelectedObject = pretty; ``` Where `ViewModel<T>` is defined: ``` public class ViewModel<T> : CustomTypeDescriptor { private T _instance; private ICustomTypeDescriptor _originalDescriptor; public ViewModel(T instance, ICustomTypeDescriptor originalDescriptor) : base(originalDescriptor) { _instance = instance; _originalDescriptor = originalDescriptor; PropertyAttributeReplacements = new Dictionary<Type,IList<Attribute>>(); } public static ViewModel<T> DressUp(T instance) { return new ViewModel<T>(instance, TypeDescriptor.GetProvider(instance).GetTypeDescriptor(instance)); } /// <summary> /// Most useful for changing EditorAttribute and TypeConvertorAttribute /// </summary> public IDictionary<Type,IList<Attribute>> PropertyAttributeReplacements {get; set; } public override PropertyDescriptorCollection GetProperties (Attribute[] attributes) { var properties = base.GetProperties(attributes).Cast<PropertyDescriptor>(); var bettered = properties.Select(pd => { if (PropertyAttributeReplacements.ContainsKey(pd.PropertyType)) { return TypeDescriptor.CreateProperty(typeof(T), pd, PropertyAttributeReplacements[pd.PropertyType].ToArray()); } else { return pd; } }); return new PropertyDescriptorCollection(bettered.ToArray()); } public override PropertyDescriptorCollection GetProperties() { return GetProperties(null); } } ``` As defined above, this substitutes properties of a specific type, but you can substitute properties by name if you need the greater resolution.
How do I inject a custom UITypeEditor for all properties of a closed-source type?
[ "", "c#", ".net", "propertygrid", "uitypeeditor", "" ]
My boss has a windows application that he wrote. It is not a Windows console application, but a Windows GUI application. We, of course, have the source code, but he does not want it to be a console app. He wants it to remain a regular GUI application. The thing is, he wants to be able to call it from PHP, passing it parameters, and have the application return information to the calling PHP script. I can easily call Windows console applications and read the output. I can even call VBS scripts and get the output from them as well. But, we are stumped on how to get a regular Windows application to output data to a calling php script without resorting to writing the output to a text file and reading it from within php. Has anybody been able to do this? If so, how? Thanks in advance. Amy --- Editing to add: Apparently, the boss put this code in his application: ``` BOOL bConsole = AllocConsole(); HANDLE hOutput = GetStdHandle(STD_OUTPUT_HANDLE); DWORD dwCharsWritten = 0; string sS3Path = sCommandLine.substr(sCommandLine.find("S3://") + 5); string sMessage = "S3 Path: " + sS3Path; BOOL bWritten = WriteConsole(hOutput, sMessage.c_str(), sMessage.size(), &dwCharsWritten, NULL); ``` But, php is not seeing the information that he is writing to this console. We've tried exec and shell\_exec to no avail.
Our final solution was for my boss to modify his Windows application. He was able to write to the console from within the app, and we could then read the output to that console. Amy
The best approch here would be to add a command line switch which would make your application behave like a console application when specified, GUI otherwise. Retriving information from a GUI application is impossible unless it is sending output through Standard Output or a file.
Getting Output from a Windows App Using PHP
[ "", "php", "windows", "" ]
I have a `ListView` like: ``` Col1 Col2 Col3 1 A I 2 B II 3 C III ``` I use 2 buttons. When I click on the first button the Col3 should collapse and it should be visible when a click in the second button. Any idea on how to do such a `ListView` in WPF?
Use of Thumb will solve the problem. Just as ``` <ListView x:Name="MyListView"IsSynchronizedWithCurrentItem="True" ItemsSource="{Binding Path=Items}", Mode=Default, Source={StaticResource DataProvider}}" Thumb.DragDelta="Thumb_DragDelta"> ``` ``` public Window1() { InitializeComponent(); MyListView.AddHandler(Thumb.DragDeltaEvent, new DragDeltaEventHandler(Thumb_DragDelta), true ); } void Thumb_DragDelta(object sender, DragDeltaEventArgs e) { Thumb senderAsThumb = e.OriginalSource as Thumb; GridViewColumnHeader header = senderAsThumb.TemplatedParent as GridViewColumnHeader; if (header.Column.ActualWidth < MIN_WIDTH) { header.Column.Width = MIN_WIDTH; } if (header.Column.ActualWidth > MAX_WIDTH) { header.Column.Width = MAX_WIDTH; } } ```
Could you provide some xaml-code of what your listview looks like? You could bind a RelayCommand to your button and pass the ListView as a parameter. Then you could set Visibility = False. ``` <Button Command="{Binding MyButtonCommand} CommandParameter="{Binding ElementName=Col3}" /> ``` This would be your cs: ``` ICommand _myButtonCommand; public ICommand MyButtonCommand { get { if (_myButtonCommand== null) _myButtonCommand= new RelayCommand(param => HideList(param )); return _myButtonCommand; } } void HideList(object param){ (param as ListView).Visibility = False; } ``` I'm talking about RelayCommand as in Josh Smith's example: <http://msdn.microsoft.com/en-us/magazine/dd419663.aspx> you can dl the code there. I guess you could achieve a similar result in xaml only with triggers, however I'm not as experienced with that subject.
Hide listview header programmatically
[ "", "c#", "wpf", "listview", "" ]
I am creating a user input at one of the events: ``` var throwConnectBox = function() { chat_box = document.getElementById('box'); div = window.parent.document.createElement('div'); input = window.parent.document.createElement('input'); input.type = "submit"; input.value = "Join chat"; input.onclick = "conn.send('$connect\r\n');"; div.appendChild(input); chat_box.appendChild(div); } ``` ... but the resulting input does not have onclick property. I tried to use ``` input.onclick = conn.send('$connect\r\n'); ``` ... instead, but didn' work either. What am I doing wrong?
Try this: ``` input.onclick = function() { conn.send('$connect\r\n'); }; ``` Steve
There is a problem with one of your lines here; I've corrected it for you: ``` var throwConnectBox = function() { chat_box = document.getElementById('box'); div = window.parent.document.createElement('div'); input = window.parent.document.createElement('input'); input.type = "submit"; input.value = "Join chat"; /* this line is incorrect, surely you don't want to create a string? */ // input.onclick = "conn.send('$connect\r\n');";? input.onclick = function() { conn.send('$connect\r\n'); }; div.appendChild(input); chat_box.appendChild(div); } ``` Does that make more sense?
Add onclick property to input with JavaScript
[ "", "javascript", "input", "onclick", "" ]
I'm wondering if it's possible to make a method which behaves differently when called as a class method than when called as an instance method. For example, as a skills-improvement project, I'm writing a `Matrix` class (yes, I know there are perfectly good matrix classes already out there). I've created a class method for it called `identity` which returns an identity matrix of a specified size. Now, when called on an *instance* of `Matrix`, it seems logical that the size shouldn't need to be specified; it should return an identity matrix of the same size as the `Matrix` it's called on. In other words, I'd like to define a method which can determine whether it was called via an instance and, if so, access that instance's attributes. Unfortunately, even after digging through the documentation and a few Google searches, I haven't found anything which suggests this is possible. Does anyone know differently? **Edit:** Wow! Clearly, I'm still not quite used to first-class functions. Here's what I ended up with — thanks to Unknown for providing the key! ``` class Foo(object): def __init__(self, bar): self.baz = bar self.bar = MethodType(lambda self: self.__class__.bar(self.baz), self, self.__class__) @classmethod def bar(cls, baz): return 5 * baz Foo.bar(3) # returns 15 foo = Foo(7) foo.bar() # returns 35 ``` **Edit 2:** Just a quick note — this technique (and most of those presented below) won't work on classes which define `__slots__`, as you cannot reassign the method.
Questionably useful Python hacks are my forte. ``` from types import * class Foo(object): def __init__(self): self.bar = methodize(bar, self) self.baz = 999 @classmethod def bar(cls, baz): return 2 * baz def methodize(func, instance): return MethodType(func, instance, instance.__class__) def bar(self): return 4*self.baz >>> Foo.bar(5) 10 >>> a=Foo() >>> a.bar() 3996 ```
**[edited: use attribute to be a more direct answer; see the helpful comment by John Fouhy]** You can use a descriptor to do what you want: ``` class cls_or_inst_method(object): def __init__(self, class_method, instance_method): self.class_method = class_method self.instance_method = instance_method def __get__(self, obj, objtype): if obj is None: return self.class_method else: return lambda: self.instance_method(obj) def my_class_method(baz): return baz + 1 def my_instance_method(self): return self.baz * 2 class Foo(object): baz = 10 bar = cls_or_inst_method(my_class_method, my_instance_method) ``` Using the above: ``` >>> print Foo.bar(5) 6 >>> my_foo = Foo() >>> print my_foo.bar() 20 ```
A class method which behaves differently when called as an instance method?
[ "", "python", "class", "methods", "" ]
I'm trying (and failing) to write a simple template file: ``` <#@ template language="C#" hostspecific="True" debug="True" #> <#@ output extension="cs" #> <#@ include file="T4Toolbox.tt" #> <#@ property name="ClassName" processor="PropertyProcessor" type="System.String" #> public class <#= ClassName #> { } ``` When I click on the template in visual studio, the property 'ClassName' is there in the properties window. That's what I want! When I enter text in there and build, I get the following error: ``` Error 1 Running transformation: System.ArgumentNullException: Value cannot be null. Parameter name: objectToConvert at Microsoft.VisualStudio.TextTemplating.ToStringHelper.ToStringWithCulture(Object objectToConvert) at Microsoft.VisualStudio.TextTemplating32ED7F6BD49D2C3984C2CB7194792D4B.GeneratedTextTransformation.TransformText() in c:\Users\neilt.PAV12\Documents\Visual Studio 2008\Projects\ConsoleApplication2\ConsoleApplication2\ClassMaker.tt:line 6 C:\Users\neilt.PAV12\Documents\Visual Studio 2008\Projects\ConsoleApplication2\ConsoleApplication2\ClassMaker.tt 1 1 ``` Hopefully, you can see what I want to do: I'd like my template to spit out a .cs file with a class named with the string I set in the property window in visual studio. Sadly, I am failing at a very early step!!
[Last time I tried](http://www.olegsych.com/2008/04/t4-property-directive/), this scenario didn't work because there is no standard processor for the property directive and no support it in Visual Studio. You may be using the limited support provided for this directive by the Clarius T4 editor; I remember getting a similar error.
You shoud invoke `Initialize()` mehod first, like this: ``` ClassTemplate t = new ClassTemplate(); t.Session = new Dictionary<string, object>(); t.Session["ClassName"] = "Person"; t.Initialize();//This is important. string output = t.TransformText(); Console.WriteLine(output); ```
Error when attempting to pass a parameter to a t4 template
[ "", "c#", "visual-studio", "properties", "t4", "" ]
I'm working on a fairly large web site built in PHP that will potentially have a lot of users. I'm looking into a way to protect the login screen from automated attempts. I have already included a CAPTCHA check on the registration form, yet want to harden the site more. There have been similar questions on StackOverflow that I know of, and I know I'm capable of implementing this myself from scratch (storing login attempts and their time in the db), yet I dislike that path: * Conceptually, I think this kind of logic belongs at the web server/infrastructure level, not the application level. I dislike having this logic and complexity in my application * I worry about performance, particularly at the database level. * I'm lazy, in a good way, by not wanting to build a common utility like this from scratch Any advise is appreciated, I think that I'm particularly looking for some kind of Apache module that can do this. My platform is PHP5 (using CodeIgniter), Apache2, MySQL 5.
**update: do not use sleep() for rate limiting!** this doesn't make sense at all. i don't have a better solution on hand. --- a good start would be to just `sleep(1);` after a failed login attempt - easy to implement, almost bug-free. 1 second isn't much for a human (especially because login attempts by humans don't fail to often), but 1sec/try brute-force ... sloooow! dictionary attacks may be another problem, but it's in the same domain. if the attacker starts too may connections to circumvent this, you deal with a kind of DOS-attack. problem solved (but now you've got another problem). some stuff you should consider: * if you lock accounts soley on a per IP basis, there may be problems with private networks. * if you lock accounts soley on a username basis, denial-of-service attacks agains known usernames would be possible * locking on a IP/username basis (where username is the one attacked) could work better **my suggestion:** complete locking is not desireable (DOS), so a better alternative would be: count the login attempts for a certain username from a unique IP. you could do this with a simple table `failed_logins: IP/username/failed_attempts` if the login fails, `wait(failed_attempts);` seconds. every xx minutes, run a cron script that decreases `failed_logins:failed_attempts` by one. sorry, i can't provide a premade solution, but this should be trivial to implement. okay, okay. here's the pseudocode: ``` <?php $login_success = tryToLogIn($username, $password); if (!$login_success) { // some kind of unique hash $ipusr = getUserIP() . $username; DB:update('INSERT INTO failed_logins (ip_usr, failed_attempts) VALUES (:ipusr, 1) ON DUPLICATE KEY UPDATE failed_logins SET failed_attempts = failed_attempts+1 WHERE ip_usr=:ipusr', array((':ipusr' => $ipusr)); $failed_attempts = DB:selectCell('SELECT failed_attempts WHERE ip_usr=:ipusr', array(':ipusr' => $ipusr)); sleep($failed_attempts); redirect('/login', array('errorMessage' => 'login-fail! ur doin it rong!')); } ?> ``` **disclaimer:** this may not work in certain regions. last thing i heard was that in asia there's a whole country NATed (also, they all know kung-fu).
A very dummy untested example, but I think, you will find here the main idea ). ``` if ($unlockTime && (time() > $unlockTime)) { query("UPDATE users SET login_attempts = 0, unlocktime = 0 ... "); } else { die ('Your account is temporary locked. Reason: too much wrong login attempts.'); } if (!$logged_in) { $loginAttempts++; $unlocktime = 0; if ($loginAttempts > MAX_LOGIN_ATTEMPTS) { $unlockTime = time() + LOCK_TIMEOUT; } query("UPDATE users SET login_attempts = $loginAttempts, unlocktime = $unlocktime ... "); } ``` Sorry for the mistakes - I wrote it in some seconds ad didn't test... The same you can do by IP, by nickname, by session\_id etc...
How to delay login attempts after too many tries (PHP)
[ "", "php", "login-attempts", "" ]
We've already gotten our code base running under Python 2.6. In order to prepare for Python 3.0, we've started adding: ``` from __future__ import unicode_literals ``` into our `.py` files (as we modify them). I'm wondering if anyone else has been doing this and has run into any non-obvious gotchas (perhaps after spending a lot of time debugging).
The main source of problems I've had working with unicode strings is when you mix utf-8 encoded strings with unicode ones. For example, consider the following scripts. two.py ``` # encoding: utf-8 name = 'helló wörld from two' ``` one.py ``` # encoding: utf-8 from __future__ import unicode_literals import two name = 'helló wörld from one' print name + two.name ``` The output of running `python one.py` is: ``` Traceback (most recent call last): File "one.py", line 5, in <module> print name + two.name UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 4: ordinal not in range(128) ``` In this example, `two.name` is an utf-8 encoded string (not unicode) since it did not import `unicode_literals`, and `one.name` is an unicode string. When you mix both, python tries to decode the encoded string (assuming it's ascii) and convert it to unicode and fails. It would work if you did `print name + two.name.decode('utf-8')`. The same thing can happen if you encode a string and try to mix them later. For example, this works: ``` # encoding: utf-8 html = '<html><body>helló wörld</body></html>' if isinstance(html, unicode): html = html.encode('utf-8') print 'DEBUG: %s' % html ``` Output: ``` DEBUG: <html><body>helló wörld</body></html> ``` But after adding the `import unicode_literals` it does NOT: ``` # encoding: utf-8 from __future__ import unicode_literals html = '<html><body>helló wörld</body></html>' if isinstance(html, unicode): html = html.encode('utf-8') print 'DEBUG: %s' % html ``` Output: ``` Traceback (most recent call last): File "test.py", line 6, in <module> print 'DEBUG: %s' % html UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 16: ordinal not in range(128) ``` It fails because `'DEBUG: %s'` is an unicode string and therefore python tries to decode `html`. A couple of ways to fix the print are either doing `print str('DEBUG: %s') % html` or `print 'DEBUG: %s' % html.decode('utf-8')`. I hope this helps you understand the potential gotchas when using unicode strings.
Also in 2.6 (before python 2.6.5 RC1+) unicode literals doesn't play nice with keyword arguments ([issue4978](http://bugs.python.org/issue4978)): The following code for example works without unicode\_literals, but fails with TypeError: `keywords must be string` if unicode\_literals is used. ``` >>> def foo(a=None): pass ... >>> foo(**{'a':1}) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: foo() keywords must be strings ```
Any gotchas using unicode_literals in Python 2.6?
[ "", "python", "unicode", "python-2.6", "unicode-literals", "" ]
How can I redirect www.mysite.com/picture/12345 to www.mysite.com/picture/some-picture-title/12345? Right now, "/picture/12345" is rewritten on picture.aspx?picid=12345 and same for second form of url (picture/picture-title/12323 to picture.aspx?picid12323) I can't just rewrite first form of url to second because i have to fetch picture title from database. On the first hand, problem looks very easy but having in mind time to parse every request, what would be the right thing to do with it?
Not knowing what is the ASP.NET technology (Webforms or MVC) I will assume it's WebForms. You can have a look at URL Redirecting and build you own rules. And you do this one time only to apply to all of the links that look like you want. [Scott Guthrie](http://weblogs.asp.net/scottgu/) has a [very nice post](http://weblogs.asp.net/scottgu/archive/2007/02/26/tip-trick-url-rewriting-with-asp-net.aspx) about it. If what you want is to when it comes to that address redirect to a new one, it's quite easy as well. First of all let's **reuse the code**, so you will redirect first to a commum page called, for example, **redirectme.aspx** in that page you get the **REFERER** address using the ServerVariables or passing the Url in a QueryString, it's your chooise and then you can attach the title name, like: ``` private void Redirect() { // get url: www.mysite.com/picture/12345 string refererUrl = Request.ServerVariables["HTTP_REFERER"]; // using the ServerVariables or Request.UrlReferrer.AbsolutePath; //string refererUrl = Request.QueryString["url"]; // if you are redirecting as Response.Redirect("redirectme.aspx?" + Request.Url.Query); // split the URL by '/' string[] url = refererUrl.Split('/'); // get the postID string topicID = url[url.Length-1]; // get the title from the post string postTitle = GetPostTitle(topicID); // redirect to: www.mysite.com/picture/some-picture-title/12345 Response.Redirect( String.Format("{0}/{1}/{2}", refererUrl.Substring(0, refererUrl.Length - topicID.Length), postTitle, topicID)); } ``` to save time on the server do this on the first Page event ``` protected void Page_PreInit(object sender, EventArgs e) { Redirect(); } ```
If you're running IIS7 then (for both webforms and MVC) the URL rewriting module (<http://learn.iis.net/page.aspx/460/using-url-rewrite-module/>) is worth looking at. Supports pattern matching and regular expressions for redirects, state whether they're temporary or permanent, plus they're all managable through the console. Why code when you don't have to?
Redirecting URL's
[ "", "c#", "asp.net", "redirect", "" ]
Why do many professional web developers always insist on developing sites that accommodate for browsers that have Javascript disabled? Besides tech heads and developers, most 'normal' users don't even know what it is.
> Who uses browsers older than Firefox 2 or IE6? Wrong question. It's not the age of the browser that's the problem. There are plenty of *new* browsers out there that don't support javascript or don't support it well, and they can be just as important as the latest safari or firefox. Others have mentioned smartphones or lynx, but the main one in my book is **Googlebot**. That's a browser just like any other, and it won't run most of your javascript. Also, even if you have firefox you might use a plugin like NoScript. That's not the same thing as running with javascript disabled, but if you do things wrong you can really mess up for those users (ie, detect javascript state once at the start of a session or creation of an account, and then no longer serve javascript pages at al, even if they wanted to enable it for you). Finally, if you do any work for the US Goverment you are required by law to support certain accessibility standards that include working with javascript disabled.
A few months ago I tested the user population on a mainstream million-member site I was working on, and around 10% of unique users did not have Javascript running. Consider reversing the question: is it worth developing a site that only works for Ajax-capable users? Would you really ignore search bots, most mobiles, and a heap of other users? Back to basics. First, create your site using **bare-bones (X)HTML**, on REST-like principles (at least to the extent of requiring POST requests for state changes). Simple semantic markup, and forget about CSS and Javascript. Step one is to get that right, and have your entire site (or as much of it as makes sense) working nicely this way for search bots and Lynx-like user agents. Then add a **visual** layer: CSS/graphics/media for visual polish, but don't significantly change your original (X)HTML markup; allow the original text-only site to stay intact and functioning. Keep your markup clean! Third is to add a **behavioural** layer: Javascript (Ajax). Offer things that make the experience faster, smoother, nicer for users/browsers with Ajax-capable JS... but only those users. Users without Javascript are still welcome; and so are search bots, the visually impaired, many mobiles, etc. This is called **progressive enhancement** in web design circles. Do it this way and your site works, in some reasonable form, for everyone.
Do web sites really need to cater for browsers that don't have Javascript enabled?
[ "", "javascript", "" ]
Why do people use enums in C++ as constants when they can use `const`?
An enumeration implies a set of *related* constants, so the added information about the relationship must be useful in their model of the problem at hand.
Bruce Eckel gives a reason in [Thinking in C++](http://bruce-eckel.developpez.com/livres/cpp/ticpp/v1/?page=page_8#L8.4.2): > In older versions of C++, `static const` was not supported inside classes. This meant that `const` was useless for constant expressions inside classes. However, people still wanted to do this so a typical solution (usually referred to as the “enum hack”) was to use an untagged `enum` with no instances. An enumeration must have all its values established at compile time, it’s local to the class, and its values are available for constant expressions. Thus, you will commonly see: > ``` > #include <iostream> > using namespace std; > > class Bunch { > enum { size = 1000 }; > int i[size]; > }; > > int main() { > cout << "sizeof(Bunch) = " << sizeof(Bunch) > << ", sizeof(i[1000]) = " > << sizeof(int[1000]) << endl; > } > ```
Why do people use enums in C++ as constants while they can use const?
[ "", "c++", "enums", "enumeration", "" ]
when we add a param to the URL $redirectURL = $printPageURL . "?mode=1"; it works if $printPageURL is "<http://www.somesite.com/print.php>", but if $printPageURL is changed in the global file to "<http://www.somesite.com/print.php?newUser=1>", then the URL becomes badly formed. If the project has 300 files and there are 30 files that append param this way, we need to change all 30 files. the same if we append using "&mode=1" and $printPageURL changes from "<http://www.somesite.com/print.php?new=1>" to "<http://www.somesite.com/print.php>", then the URL is also badly formed. is there a library in PHP that will automatically handle the "?" and "&", and even checks that existing param exists already and removed that one because it will be replaced by the later one and it is not good if the URL keeps on growing longer? **Update:** of the several helpful answers, there seems to be no pre-existing function addParam($url, $newParam) so that we don't need to write it?
Use a combination of [`parse_url()`](https://www.php.net/manual/en/function.parse-url.php) to explode the URL, [`parse_str()`](https://www.php.net/parse_str) to explode the query string and [`http_build_query()`](https://www.php.net/manual/en/function.http-build-query.php) to rebuild the querystring. After that you can rebuild the whole url from its original fragments you get from `parse_url()` and the new query string you built with `http_build_query()`. As the querystring gets exploded into an associative array (key-value-pairs) modifying the query is as easy as modifying an array in PHP. **EDIT** ``` $query = parse_url('http://www.somesite.com/print.php?mode=1&newUser=1', PHP_URL_QUERY); // $query = "mode=1&newUser=1" $params = array(); parse_str($query, $params); /* * $params = array( * 'mode' => '1' * 'newUser' => '1' * ) */ unset($params['newUser']); $params['mode'] = 2; $params['done'] = 1; $query = http_build_query($params); // $query = "mode=2&done=1" ```
Use this: <http://hu.php.net/manual/en/function.http-build-query.php>
is there a PHP library that handles URL parameters adding, removing, or replacing?
[ "", "php", "url-rewriting", "" ]
I have program that has a variable that should never change. However, somehow, it is being changed. Is there a way to have the debugger stop when that particular member variable is modified?
Set a data breakpoint to stop execution whenever some variable changes. Break on the initialization of your variable, or someplace where your variable is visible - you need to be able get its address in memory. Then, from the menus choose Debug -> New Breakpoint -> New Data Breakpoint. Enter "`&var`" (with `var` replaced by the name of your variable.) This will break into the debugger on the exact line of code that is modifying your variable. More documentation here: [<http://msdn.microsoft.com/en-us/library/350dyxd0.aspx>](http://msdn.microsoft.com/en-us/library/350dyxd0.aspx)
You can set conditional breakpooint at places where the variable is used. In Visual Studio set breakpoint by pressing F9 when your cursor at the line where you want to set breakpoint. Next, right click on the breakpoint and select Condition. Type your condition like ``` n != 5 ``` Good luck. Here's [a link from MSDN](http://msdn.microsoft.com/en-us/library/aa290718(VS.71).aspx).
Visual Studio: how do I have the debugger stop when a member variable is modified?
[ "", "c++", "windows", "visual-studio", "" ]
So I have some PHP code that looks like: ``` $message = 'Here is the result: %s'; ``` I just used %s as an example. It's basically a placeholder for whatever will go there. Then I pass the string to a function and I want that function to replace the %s with the value. What do I need to do to achieve this? Do I need to do some regex, and use preg\_replace(), or something? or is there a simpler way to do it?
You can actually use the [sprintf](http://php.net/sprintf) function which will return a formatted string and will put your variables on the place of the placeholders. It also gives you great powers over how you want your string to be formatted and displayed. ``` $output = sprintf("Here is the result: %s for this date %s", $result, $date); ```
``` $find = array( '#name#', '#date#' ); $search = array( 'someone\'s name', date("m-d-Y") ); $text_result = str_replace($find, $search, $text); ``` I'm usually using this for my code, fetching the $text from some text/html files then make the $text\_result as the output
How to replace a variable within a string with PHP?
[ "", "php", "regex", "preg-replace", "replace", "" ]
I am trying to see from an SQL console what is inside an Oracle BLOB. I know it contains a somewhat large body of text and I want to just see the text, but the following query only indicates that there is a BLOB in that field: ``` select BLOB_FIELD from TABLE_WITH_BLOB where ID = '<row id>'; ``` the result I'm getting is not quite what I expected: ``` BLOB_FIELD ----------------------- oracle.sql.BLOB@1c4ada9 ``` So what kind of magic incantations can I do to turn the BLOB into it's textual representation? PS: I am just trying to look at the content of the BLOB from an SQL console (Eclipse Data Tools), not use it in code.
First of all, you may want to store text in CLOB/NCLOB columns instead of BLOB, which is designed for binary data (your query would work with a CLOB, by the way). The following query will let you see the first 32767 characters (at most) of the text inside the blob, provided all the character sets are compatible (original CS of the text stored in the BLOB, CS of the database used for VARCHAR2) : ``` select utl_raw.cast_to_varchar2(dbms_lob.substr(BLOB_FIELD)) from TABLE_WITH_BLOB where ID = '<row id>'; ```
SQL Developer provides this functionality too : Double click the results grid cell, and click edit : [![enter image description here](https://i.stack.imgur.com/KQkq8.png)](https://i.stack.imgur.com/KQkq8.png) Then on top-right part of the pop up , "View As Text" (You can even see images..) [![enter image description here](https://i.stack.imgur.com/aiLCL.png)](https://i.stack.imgur.com/aiLCL.png) And that's it! [![enter image description here](https://i.stack.imgur.com/g7Q0F.png)](https://i.stack.imgur.com/g7Q0F.png)
How do I get textual contents from BLOB in Oracle SQL
[ "", "sql", "oracle", "blob", "" ]
Given the J5+ memory model (JSR-133) is the following code thread-safe and permissible? And if it's safe, is it acceptable in some situations? ``` public final class BackgroundProcessor extends Object implements Runnable { public BackgroundProcessor(...) { super(); ... new Thread(this).start(); } public void run() { ... } } ``` As I read the new JMM spec, initiating a thread creates a happens-before relationship with anything the initiated thread does. Assume that the object has private member variables set in the constructor and used in run(). And the class is marked final to prevent sub-classing surprises. Note: There is a similar question here, but this has a different angle: [calling thread.start() within its own constructor](https://stackoverflow.com/questions/84285/calling-thread-start-within-its-own-constructor)
Well, unless you particularly want to disagree with Brian Goetz on a Java concurrency issue, I'd assume it's wrong. Although his exact words are "is best not to...", I'd still heed his advice. From **JCIP, p. 42:** > "A **common mistake** that can let the > 'this' reference escape during > construction is to **start a thread > from a constructor** [...] There's > nothing wrong with *creating* a thread > in a constructor, but it is best not > to *start* the thread immediately. > Instead, expose a start or initialize > method..." **Update:** just to elaborate on why this is a problem. Although there's guaranteed to be a memory barrier between the call to Thread.start() and that thread's run() method actually beginning to execute, there's no such barrier between what happens during the constructor *after* the call to Thread.start(). So if some other variables are still to be set, or if the JVM carries out some "have-just-constructed-object" housekeeping, neither of these are guaranteed to be seen by the other thread: i.e. the object could be seen by the other thread in an incomplete state. Incidentally, aside from whether or not it actually breaks the JMM, it also just feels a bit like an "odd thing to do" in a constructor.
[JLS: Threads and Locks](http://docs.oracle.com/javase/specs/jls/se5.0/html/memory.html) says > Two actions can be ordered by a happens-before relationship. If one action happens-before another, then the first is visible to and ordered before the second. > > If we have two actions x and y, we write hb(x, y) to indicate that x happens-before y. > > * If x and y are actions of the same thread and x comes before y in program order, then hb(x, y). and > A call to start() on a thread happens-before any actions in the started thread. so we can conclude that all actions in the constructor before the call to Thread.start() happen before all actions in the thread that was started. If Thread.start() is after all writes to the object's fields, then the started thread will see all writes to the object's fields. If there are no other writes to the fields (that another thread will read), then the code is thread-safe.
Can I launch a thread from a constructor?
[ "", "java", "multithreading", "" ]
I'm rewriting an old VBSCript WSC component into a nicer C# COM Component. For a horrid reason the old component in one place is passed the Server Context, IServer by using ``` Set objCurr = CreateObject("MTxAS.AppServer.1") Set objCurrObjCont = objCurr.GetObjectContext() Set component.servercontext = objCurrObjCont("Server") ``` this is then used to do a standard `Server.MapPath("/somelocation")` However I'm stumped upon what to do in the .Net COM Component, `System.Web.HttpContext.Current.MapPath()` doesn't work as expected as there is no Web Context. I tried passing the context from Classic ASP into the COM Component but I'm not sure which reference to include so I can invoke the correct member, Microsoft.Active X Data Objects 2.7 seems a common one, but this only includes Recordsets etc, nothing for the C++ IServer interface so it comes our just as a `COM OBJECT`. Does anyone know of a way to do this / a work around? At this rate I'm thinking I may have to change the behaviour of the component
Add to your C# project an interop for ASP.dll (you will find it in the \system32\inetsrv folder. Add a public method to the class that gets instantiated by ASP:- ``` ASPTypeLibrary.ScriptingContext context; public void OnStartPage(ASPTypeLibrary.ScriptingContext sc) { context = sc; } ``` Now when you need a MapPath use:- ``` context.Server.MapPath("..."); ``` Note context gives you access to the Request, Response and Session in addition to Server. The OnStartPage is a pre-COM+ hack that ASP used and still works even in the latest versions. ASP performs the COM equivalent of reflection (examining the COM classes type library info) to determine if a public OnStartPage method is available, if so it calls it passing the ScriptingContext object. There is no .NET HttpContext available, the request would have had to have been handled by .NET in the first place for that to exist. A HttpContext cannot be created on a thread "after the fact" as it were. Hence if your component needs to interact with the Http conversation it will have to do so via the ASP context object since ASP is the host that is actually handling the request.
I think indeed changing the behaviour is the best option here... wel... not exactly the behaviour, but the interface of the COM object... Instead of passing in the server context, just pass in the relevant information needed for the method.
Server.MapPath in a COM Component
[ "", "c#", "com", "asp-classic", "vbscript", "" ]
I have some PHP code that generates dynamic tables of data on the fly. By clicking various links you "refine" the tables of data. What I'd like is each of these links to retain the current GET information and add to it. IE: ``` $allPreviousVars = ???; // Could be 20+ vars echo "<a href='".$allPreviousVars."&newVar=2'>Link</a>"; ``` I can think of ways to do it by iterating through $\_GET with a loop, but surely there is a quicker way to do this?
How about $\_SERVER["QUERY\_STRING"]? **EDIT:** Since you were kind enough to give me credit for this answer, I should add one thing. You should wrap the above variable in htmlspecialchars() before you output it. Otherwise someone could type a URL with `">` in it, and it would break your link.
I do this as follows: ``` <?php echo http_build_query(array_merge($_GET, array('foo'=>'bar', 'foo2'=>'bar2')); ?> ``` Note that any existing 'foo' or 'foo2' keys would be replaced.
PHP How do I retain all GET vars in links?
[ "", "php", "variables", "get", "hyperlink", "" ]
In my Java application, I am archiving TIBCO RV messages to a file as bytes. I am writing a small utility app that will play the messages back. This way I can just create a TibrvMsg object from the bytes without having to parse the file and construct the object manually. The problem I am having is that I am reading a file that was created on a Linux box, and attempting to run my app on a Windows machine. I get an error due to the different charset the file was written in. So now, what I want to do is log each message in a specific charset (UTF-8), so that I don't care what platform I run my playback app in. The app should just read in the file knowing before-hand the charset the file is written in. I am planning on using java.nio packages for this, to transform the bytes from one charset to another. Do I need to know what charset the TIBRV message bytes are encoded in to do the transformation? If so, how can I find this out?
You are taking opaque data and, it would appear, attempting to write it to a file as textual data without escaping the non textual portions of it (alternatively you are writing it as raw bytes and then trying to read it as if it were character based which is much the same problem). This is flawed from the very start. Opaque data should be treated as meaningless and simply stored without modification to give back to an API that does know how to deal with it. If the data must be stored in a textual form then you must *losslessly* convert the bytes into text. Appropriate encodings are things like base64. Encoding in the sense of character set encoding is NOT lossless if you apply it to raw binary data. Simply storing the bytes in a file as *bytes* (not characters) along with a fixed length prefix indicating the length of the message and the subject it was sent on is sufficient to replay RV messages through the system. In relation to any text based fields inside the message if the encoding matters (I strongly suggest avoiding this mattering in general when designing the app) then you have the same problem on replay as you would have had at the original receipt time which is to convert from the source encoding to the desired encoding (hopefully using exactly the same code) so this should be a non issue in relation to the replaying.
As this (admittedly rather old) [mailing list message](https://web.archive.org/web/20091030161202/http://www.ethereal.com/lists/ethereal-users/200603/msg00092.html) indicates, little is known about the internal structure of that network protocol. This might make it quite a challenge to do what you're after. That said, if the messages are just binary blocks of data (as captured from the network), they shouldn't even have a charset. Charsets is for textual data, where it matters since a single character can be encoded in many different ways. Binary data is not composed out of characters, so there cannot be an encoding in that sense.
How can I find the byte encoding of a TIBCO Rendezvous message?
[ "", "java", "character-encoding", "nio", "tibco", "" ]
I have a database table which gives me the following result: ``` array(8) { ["link_id"]=> string(2) "20" ["link_url"]=> string(56) "http://url.of/website" ["link_name"]=> string(34) "Website title" ["link_target"]=> string(0) "" ["link_description"]=> string(0) "" ["link_updated"]=> string(19) "2009-05-24 16:51:04" ["taxonomy_id"]=> string(2) "36" ["term_id"]=> string(2) "34" ["category_name"]=> string(15) "Link category" } ``` I want to sort many of these arrays in to one multidimensional array, based on the *category\_name* key, and then sorted by the *link\_updated* key. So I eventually want it to look like this: ``` array(2) { ["First category"]=> array(2) { ["link_name"]=> string(11) "Newest link" ["link_updated"]=> string(19) "2009-05-24 16:51:24" } ["Second category"]=> array(2) { ["link_name"]=> string(10) "Older link" ["link_updated"]=> string(19) "2009-05-20 05:32:56" } } ``` I have no idea how to do this, but I think I have to make my own sorting method (usort())? EDIT: I want to show 5 links in each category.
I solved it myself, by using the following code: ``` foreach ($bookmarks as $b) { $category[$b["category_name"]][] = array( "link_id" => $b["link_id"], "link_url" => $b["link_url"], "link_name" => $b["link_name"], "link_target" => $b["link_target"], "link_description" => $b["link_description"], "link_updated" => $b["link_updated"], "taxonomy_id" => $b["taxonomy_id"], "term_id" => $b["term_id"], "category_name" => $b["category_name"] ); } ``` This creates an array of the category name, and puts all subarrays in the right parent array (based on category). The sorting after time the link is updated is being made in the SQL query.
Using [usort()](https://www.php.net/manual/en/function.usort.php) you can sort your arrays in any way you want: ``` function sort_crazy_way($a, $b){ // do your business. } usort($array, 'sort_crazy_way'); ``` After you get it sorted, you can create the last array in another for loop. From the PHP manual: > The comparison function must return an > integer less than, equal to, or > greater than zero if the first > argument is considered to be > respectively less than, equal to, or > greater than the second. So, your comparison function should be something like: ``` function sort_crazy_way($a, $b){ $sorted_by_category = strcmp($a['category_name'], $b['category_name']); if($sorted_by_category){ return $sorted_by_category; } // If we're here, category_name is the same. Compare link_updated. $time_diff = strtotime($a['link_updated']) - strtotime($b['link_updated']); return $time_diff; } ```
Sort arrays into multidimensional array by key
[ "", "php", "arrays", "multidimensional-array", "" ]
I am playing of a sound-file in Java, and is looking for a simple way to determine when the sound-file has finished playing so I can kill the thread. Is there a simple way to accomplish this?
## Comments You play sound either synchronously or asynchronously. In case you play it synchronously (blocking the calling thread), you know when the sound ends playing — your code gain control then. In case you play it asynchronously (allowing a different thread to be created), the helper thread will terminate itself right after finishing playing. ## P.S. Please share your observations on memory leaking and reasons underneath the question.
Sorry this is a little late, but I just ran into an issue today that sounds suspiciously familiar to this one. In some game code, Im using javax.sound.sampled.Clip to play various sounds, I found that if I didn't explicitly call line.close() once it was finished, the count of native threads in the profiler would just sky-rocket until I got an OutOfMemory error. ``` // this just opens a line to play the sample Clip clip = AudioSystem.getClip(); clip.open( audioFormat, sounddata, 0, sounddata.length); clip.start(); // at this point, there is a native thread created 'behind the scenes' // unless I added this, it never goes away: clip.addLineListener( new LineListener() { public void update(LineEvent evt) { if (evt.getType() == LineEvent.Type.STOP) { evt.getLine().close(); } } }); ``` My presumption is that the clip creates a thread to meter out the sample bytes into the line, but the thread hangs around after that in case you want to re-use the clip again. My second presumption is that somewhere something in my code must have a reference to the clip, or vice-versa, but at any rate, the snippet above duct-taped the problem. Hope this is useful to someone.
Determine when to close a sound-playing thread in Java
[ "", "java", "multithreading", "audio", "" ]
I just started playing around with [Mozilla Jetpack](https://jetpack.mozillalabs.com/), and I love it so far. I wrote a little code that displays an icon in the statusbar that, when clicked, brings up a notification: ``` var myTitle = 'Hello World!'; var line1 = 'I am the very model of a modern Major-General,'; var line2 = 'I\'ve information vegetable, animal, and mineral,'; var line3 = 'I know the kings of England, and I quote the fights historical,'; var line4 = 'From Marathon to Waterloo, in order categorical.'; var myBody = line1 + ' ' + line2 + ' ' + line3 + ' ' + line4; var myIcon = 'http://www.stackoverflow.com/favicon.ico'; jetpack.statusBar.append({ html: '<img src="' + myIcon + '">', width: 16, onReady: function(doc) { $(doc).find("img").click(function() { jetpack.notifications.show({title: myTitle, body: myBody, icon: myIcon}); }); } }); ``` Because the text is very long in this example, the notification looks like this: [Jetpack Notification http://img33.imageshack.us/img33/7113/jetpack.png](http://img33.imageshack.us/img33/7113/jetpack.png) I want to split the text of the notification onto four different lines when they are displayed so the notification box is taller and narrower. How do I go about doing this? **Edit 1 (Thanks to [Rudd Zwolinski](https://stackoverflow.com/users/219/rudd-zwolinski)):** I tried, but this does not help: ``` var myBody = line1 + '\n' + line2 + '\n' + line3 + '\n' + line4; ``` **Edit 2 (Thanks to [Ólafur Waage](https://stackoverflow.com/users/22459/olafur-waage)):** This does not help either: ``` var myBody = line1 + '<br />' + line2 + '<br />' + line3 + '<br />' + line4; ``` **Edit 3 (Thanks to [Matt](https://stackoverflow.com/users/85803/matt)):** Even this does not help: ``` var myBody = line1 + "\n" + line2 + "\n" + line3 + "\n" + line4; ```
Unfortunately, the alert created doesn't allow new lines for the toast popup in Windows. According to the Jetpack API: > Eventually, this object will be the > end-all be-all of easy communication > with your users. Notification bars, > transparent messages, Growls, doorknob > messages, and so forth will all go > through here. **For now, it just has > simple notifications.** As shown in [the source code](http://hg.mozilla.org/labs/jetpack/file/696629c0ba99/extension/content/js/notifications.js), the `jetpack.notifications.show` method makes a call to the Mozilla [`nsIAlertsService`](https://developer.mozilla.org/En/NsIAlertsService), which doesn't allow multiple lines for the Windows toast popups. The upside is that the API indicates that you'll have much more control over alerts in the future, but for the pre-release version you'll have to keep your notification text down to a minimum.
I can't test this because I'm on a mac and getting Growl notifications from `jetpack.notifications.show`, and Growl constrains the width, but try changing `myBody` to this: ``` var myBody = line1 + '\n' + line2 + '\n' + line3 + '\n' + line4; ``` The line breaks do show up for me, so this might be what you're looking for. **EDIT**: This does not work for the Windows toast notifications, so it doesn't answer the question. However, **it will show newlines in Growl notifications for Mac OS X**, so I'm leaving this answer up.
Displaying multiline notifications
[ "", "javascript", "jquery", "firefox-addon", "firefox-addon-sdk", "" ]
I am having trouble efficiently selecting the information I need to display. Hopefully someone else has a better idea of how to solve this. Given the following data structures, ``` public class Department { public int ID { get; set; } public string Name { get; set; } public IList<Product> Products{ get; set; } } public class Product { public int ID { get; set; } public string Name { get; set; } } ``` And given the following data ``` Department1 = { Id=1, Name="D1", Products = {new Product{Id=1, Name="Item1"}, new Product{Id=2, Name="Item2"} } Department2 = { Id=2, Name="D2", Products = {new Product{Id=2, Name="Item2"}, new Product{Id=3, Name="Item3"} } ``` **How do I select out that "Item2" is common to both "D1" and "D2"?** I have tried using an intersection query, but it appears to want two deferred query execution plans to intersect rather than two IEnumerable lists or ILists. Any help with this is greatly appreciated. Edit: It appears I wasn't very precise by trying to keep things simple. I have a list of departments, each contain a list of products. Given these lists, how do I select another list of products based on a particular criteria. My criteria in this instance is that I want to select only products that exist in all of my departments. I want only the data that intersects all elements.
My [Intersect](http://msdn.microsoft.com/en-us/library/system.linq.enumerable.intersect.aspx) function works fine: ``` Department department1 = new Department { Id = 1, Name = "D1", Products = new List<Product> () { new Product { Id = 1, Name = "Item1" }, new Product { Id = 2, Name = "Item2" } } }; Department department2 = new Department { Id = 2, Name = "D2", Products = new List<Product>() { new Product { Id = 2, Name = "Item2" }, new Product { Id = 3, Name = "Item3" } } }; IEnumerable<Product> products = department1.Products.Intersect(department2.Products, new ProductComparer()); foreach (var p in products) { Console.WriteLine(p.Name); } ``` **(edit)** ``` public class ProductComparer : IEqualityComparer<Product> { public bool Equals(Product x, Product y) { return x.Name == y.Name && x.Id == y.Id; } public int GetHashCode(Product obj) { return obj.Id.GetHashCode() ^ obj.Name.GetHashCode(); } } ```
If you want to use Linq, then you could flatten the Products collection and associate each one with the parent Department object (so you have a collection of (Product, Department) pairs) and then re-group on Product. ``` var sharedItems = new[] { department1, department2 } .SelectMany(d => d.Products, (dep, prod) => new { Department = dep, Product = prod }) .GroupBy(v => v.Product) .Where(group => group.Count() > 1); ``` The result of this query is an enumeration of IGroupings where the key is the product and contains the Departments with that product.
Linq Dilemma
[ "", "c#", "linq", "" ]
I have a C# application that should only be used when the network is down, but am afraid users will just unplug the network cable in order to use it. Is there a way to detect if the network cable has been unplugged? Thanks
You could use IsNetworkAlive(). Although technically it doesn't check link state, it's probably better since it can detect wireless and dialup connectivity as well. Here's an example: ``` using System.Runtime.InteropServices; class Program { [DllImport("sensapi.dll")] static extern bool IsNetworkAlive(out int flags); static void Main(string[] args) { int flags; bool connected = IsNetworkAlive(out flags); } } ``` The flags param returns whether the connection is to the internet or just a LAN. I'm not 100% sure how it knows, but I'd bet it just looks to see if there is a default gateway set.
In my humble opinion, there is no certain way to distinguish between a network down and an unplugged cable. And even if there is a way, there is also a way to work around it. Let's assume that you have a solution and let's look at some situations: * There is no network traffic, the cable is not unplugged from the computer: it may be unplugged at the other end. * There is no network traffic, the cable is unplugged: but this has always been the case, the laptop is connected via Wi-Fi, which is down at the moment. * There are several network interfaces, only the one connected to WAN is down: should your app work? * The network is actually down, in the sense you mean: someone has managed to reboot the router continuously for using your app.
How can I tell if a network cable has been unplugged?
[ "", "c#", "networking", "" ]
I was told that the optimal way to program in C++ is to use STL and string rather than arrays and character arrays. i.e., ``` vector<int> myInt; ``` rather than ``` int myInt[20] ``` However, I don't understand the rational behind why it would result in security problems.
I suggest you read up on [buffer overruns](http://en.wikipedia.org/wiki/Buffer_overrun), then. It's much more likely that a programmer creates or risks buffer overruns when using raw arrays, since they give you less protection and don't offer an API. Sure, it's possible to shoot yourself in the foot using STL too, but at least it's harder.
There appears to be some confusion here about what security vectors can and cannot provide. Ignoring the use of iterators, there are three main ways of accessing elements ina vector. * the operator[] function of vector - this provides no bounds checking and will result in undefined behaviour on a bounds error, in the same way as an array would if you use an invalid index. * the at() vector member function - this provides bounds checking and will raise an exception if an invalid index is used, at a small performance cost * the C++ operator [] for the vector's underlying array - this provides no bounds checking, but gives the highest possible access speed.
How does using arrays in C++ result in security problems
[ "", "c++", "security", "" ]
I have a string. How do I remove all text after a certain character? (*In this case `...`*) The text after will **`...`** change so I that's why I want to remove all characters after a certain one.
Split on your separator at most once, and take the first piece: ``` sep = '...' stripped = text.split(sep, 1)[0] ``` You didn't say what should happen if the separator isn't present. Both this and [Alex's solution](https://stackoverflow.com/a/904753/4518341) will return the entire string in that case.
Assuming your separator is '...', but it can be any string. ``` text = 'some string... this part will be removed.' head, sep, tail = text.partition('...') >>> print head some string ``` If the separator is not found, `head` will contain all of the original string. The [partition](https://docs.python.org/3/library/stdtypes.html#str.partition) function was added in Python 2.5. > `S.partition(sep)` -> `(head, sep, tail)` > > Searches for the separator *sep* in *S*, and returns the part before it, > the separator itself, and the part after it. If the separator is not > found, returns *S* and two empty strings.
How to remove all characters after a specific character in python?
[ "", "python", "replace", "" ]
I am trying to create an extension method for the generic delegate `Action<T>` to be able to make simple asynchronous calls on `Action<T>` methods. It basically just implements the pattern for when you want to execute the method and don't care about it's progress: ``` public static class ActionExtensions { public static void AsyncInvoke<T>(this Action<T> action, T param) { action.BeginInvoke(param, AsyncActionCallback, action); } private static void AsyncActionCallback<T>(IAsyncResult asyncResult) { Action<T> action = (Action<T>)asyncResult.AsyncState; action.EndInvoke(asyncResult); } } ``` The problem is that it won't compile because of the extra `<T>` that makes the `AsyncActionCallback` generic and have a different signature than expected. The signature `void AsyncActionCallback(IAsyncResult)` is expected. Does anyone know how to work around this or to accomlish what I am trying to do?
``` public static void AsyncInvoke<T>(this Action<T> action, T param) { action.BeginInvoke(param, asyncResult => { Action<T> a = (Action<T>)asyncResult.AsyncState; a.EndInvoke(asyncResult); }, action); } ```
`AsyncActionCallback<T>` ? Disclaimer: not sure about the above, could be one of those 'limitations'.
How to make this extension method compile?
[ "", "c#", ".net", "generics", "extension-methods", "" ]
HI all, i wish save in a file.txt the chronology of the song played by my music Player . I tried this code snippet but doesn't work : ``` StreamWriter sw = new StreamWriter(@"c:\Media PlayList\List.txt"); private void listBox1_SelectedIndexChanged(object sender, EventArgs e) { wmp.URL = Convert.ToString(listBox1.SelectedItem); foreach (object o in listBox1.SelectedItems) { sw.WriteLine(DateTime.Now + " - " + o.ToString()); } } ``` How i store songs : ``` private List<string> GetFolder(string Folder) { string filena; DirectoryInfo dir = new DirectoryInfo(Folder); FileInfo[] files = dir.GetFiles("*.mp3", SearchOption.AllDirectories); List<string> str = new List<string>(); foreach (FileInfo file in files) { str.Add(file.FullName); } } private void Form2_Load(object sender, EventArgs e) { List<string> uno = GetFolder(@"D:\\Music\\"); listBox1.DataSource = uno; listBox1.DisplayMember = "uno"; } ``` I need each time the Music Player change song the file "List.txt" will be update by listbox.SelectedItem but i cannot update the "List.txt" with my code. Where i wrong? Thanks for your attention. Nice regards EDIT: I updated my code snippet hoping it will be clear .
``` using System; using System.Collections.Generic; using System.IO; using System.Windows.Forms; namespace WindowsApplication1 { public partial class Form1 : Form { public Form1() { InitializeComponent(); listBox1.DataSource = GetFolder("D:\\Music\\"); } private static List<string> GetFolder(string folder) { List<string> FileList = new List<string>(); foreach (FileInfo file in new DirectoryInfo(folder).GetFiles("*.mp3", SearchOption.AllDirectories)) FileList.Add(file.FullName); return FileList; } private void listBox1_SelectedIndexChanged(object sender, EventArgs e) { StreamWriter sw = new StreamWriter("c:\\Media PlayList\\List.txt", true); wmp.URL = Convert.ToString(listBox1.SelectedItem); foreach (object o in listBox1.SelectedItems) sw.WriteLine(DateTime.Now + " - " + o); sw.Close(); } } } ``` The above code will do the work for you. Notes: * If you want to append to the file, you should pass true as the second argument when you create the StreamWriter. * After writing your data to the file, you should explicitly close the StreamWriter, or your file will be empty. * After closing the file you can no longer write to it. If you want you can reopen it.
private void listBox1\_SelectedIndexChanged(object sender, EventArgs e) ``` { wmp.URL = Convert.ToString(listBox1.SelectedItem); foreach (object o in listBox1.SelectedItems) sw.WriteLine(DateTime.Now + " - " + o.ToString()); sw.close(); } ```
Save ListBox_SelectedItem to file.txt
[ "", "c#", ".net", "winforms", "" ]
Is there a known pattern to inherit data in a hierarchical object structure? I have a hierarchical 'Item' structure which needs to inherit its 'Type' from its 'Parent' (have the same data as default). The type of sub item can be modified by its own, and when the type of parent Item changes, all sub items which their type is not changed, should get the new type of parent. Note that I cannot fake it like ``` public string Type { get { if (type == null) return Parent != null ? Parent.Type : null; return type; } } ``` 'cause I have to fill the values in the database, and the structure is too deep to use recursion and not worry about the performance. The only way I can think of it now is ``` public string Type { set { type = value; UpdateUnchangedChildren(value); } } public int AddChild(Item item) { item.Type = Type; return Items.Add(item); } ``` Is there a better way? Thanks.
It's a common problem, usually related to maintenance of various hierarchical settings/configurations. So, I guess a solution to it can be considered "a pattern". Anyways, from the internal architecture perspective you have 2 major options: * normalized structure * denormalized structure "Normazlied" is the one implemented with recursion. A particular piece of data is always stored in one place, all the other places have references to it (e.g., to parent). The structure is easily updated, but readng from it may be a problem. "Denormalized" means that every node will store the whole set of settings for its level and whenever you update a node it takes some time to go down the hierarchy and corect all the children nodes. But the reading operation is instant. And so the "denormalized" version seems to be more widely used, because the common scenario with settings is that you update them rarely, while read them often, hence you need better read performance. For example, [Windows ACL security model](http://www.windowsecurity.com/articles/Understanding-Windows-NTFS-Permissions.html) uses the "denormalized" approach to make security checks fast. You can read how they [resolve conflicts between the "inherited" and explicit permissions (ACEs) by checking them in a specific order](http://alt.pluralsight.com/wiki/default.aspx/Keith.GuideBook/WhatIsACLInheritance.html). That might be an overkill for your particular system though, you can simply have a flag that a particular value was overriden or, on the opposite, reset to "default"... Further details depend on your system needs, you might waht to have a "hybrid" architecture, where some of the fields would be "normalized" and some others won't. But you seem to be on the right way.
I'm not 100% sure what it is you are trying to do... but you could use generics to pass the type of a parent object into a child object... But having a setter there doesn't really make sense... The Parent object's type will be set when it's instantiated, so why would you have a setter there to change it. Assuming you have something like this... ``` public class Child<T> { public string Type { get { return typeof(T).ToString(); } } } ``` So then, when you have a `Parent` Object of any type, you can pass that to your Child Property... ``` public class ParentA { public Child<ParentA> ChildObj { get; set; } } public class ParentB { public Child<ParentB> ChildObj { get; set; } } public class ParentC { public Child<ParentC> ChildObj { get; set; } } ``` Calling any of those ChildObj.Type Properties will return ParentA, ParentB & ParentC respectively. Buit I've a funny feeling you haven't fully explained what it is you're trying to do. Can you post some more code examples showing a Parent Class & Child/Item Class
Data Inheritance in C#
[ "", "c#", "design-patterns", "" ]
I've been playing about with functors in C++. In particular, I've got a vector of pairs I'd like to sort by the first element of the pair. I started off writing a completely specialised functor (i.e. something like "bool MyLessThan(MyPair &lhs, MyPair &rhs)"). Then, just because this sort of stuff is interesting, I wanted to try writing a generic "Apply F to the first elements of this pair" functor. I wrote the below, but g++ doesn't like it. I get: error: type/value mismatch at argument 2 in template parameter list for 'template struct Pair1stFunc2' error: expected a type, got 'less' ``` #include <algorithm> #include <functional> #include <utility> #include <vector> template <class P, class F> struct Pair1stFunc2 { typename F::result_type operator()(P &lhs, P &rhs) const { return F(lhs.first, rhs.first); } typename F::result_type operator()(const P &lhs, const P &rhs) const { return F(lhs.first, rhs.first); } }; typedef std::pair<int,int> MyPair; typedef std::vector<MyPair> MyPairList; MyPairList pairs; void foo(void) { std::sort(pairs.begin(), pairs.end(), Pair1stFunc2<MyPair, std::less>()); } ``` Can anyone shed any light on what I'm doing wrong here? I know this is as slightly artificial example, but I'd like to know what's going on, if only to improve my STL-fu.
You need to specialize std::less with the comparison type you're using. ``` Pair1stFunc2<MyPair, std::less<int> >() ``` will do the trick. Within your own operator() you'll also need to instantiate an object of the comparison type, since you can't just call the class directly. E.g. change ``` return F(lhs.first, rhs.first); ``` to ``` F func; return func(lhs.first, rhs.first); ``` You could also move the specialization into the functor, as another answer suggests.
To expand on dirkgently's answer, here's an example of what might work as you intend: ``` template <typename T, template <typename> class F> struct Pair1stFunc2 { template <typename P> typename F<T>::result_type operator()(P &lhs, P &rhs) const { F<T> f; return f(lhs.first, rhs.first); } template <typename P> typename F<T>::result_type operator()(const P &lhs, const P &rhs) const { F<T> f; return f(lhs.first, rhs.first); } }; void foo(void) { std::sort(pairs.begin(), pairs.end(), Pair1stFunc2<int, std::less>()); } ``` Note that it works, but it might not be exactly what you had in mind.
g++ rejects my simple functor with "expected a type, got 'xyz'"
[ "", "c++", "templates", "g++", "functor", "" ]
I was wondering what would make a programmer to choose either Pimpl idiom or pure virtual class and inheritance. I understand that pimpl idiom comes with one explicit extra indirection for each public method and the object creation overhead. The Pure virtual class in the other hand comes with implicit indirection(vtable) for the inheriting implementation and I understand that no object creation overhead. **EDIT**: But you'd need a factory if you create the object from the outside What makes the pure virtual class less desirable than the pimpl idiom?
When writing a C++ class, it's appropriate to think about whether it's going to be 1. A Value Type Copy by value, identity is never important. It's appropriate for it to be a key in a std::map. Example, a "string" class, or a "date" class, or a "complex number" class. To "copy" instances of such a class makes sense. 2. An Entity type Identity is important. Always passed by reference, never by "value". Often, doesn't make sense to "copy" instances of the class at all. When it does make sense, a polymorphic "Clone" method is usually more appropriate. Examples: A Socket class, a Database class, a "policy" class, anything that would be a "closure" in a functional language. Both pImpl and pure abstract base class are techniques to reduce compile time dependencies. However, I only ever use pImpl to implement Value types (type 1), and only sometimes when I really want to minimize coupling and compile-time dependencies. Often, it's not worth the bother. As you rightly point out, there's more syntactic overhead because you have to write forwarding methods for all of the public methods. For type 2 classes, I always use a pure abstract base class with associated factory method(s).
`Pointer to implementation` is usually about hiding structural implementation details. `Interfaces` are about instancing different implementations. They really serve two different purposes.
Pimpl idiom vs Pure virtual class interface
[ "", "c++", "abstract-class", "pimpl-idiom", "" ]
I'm looking for something to turn my C# XML comments into documentation. I don't like CHM's, nor MSDN's look and feel. I love using the javadocs. They're easy to navigate, and everything is accessible. I am looking for a tool I can use to convert the comments in my code to a javadoc like look and feel. Is there something that does this? I've tried Sandcastle and its various GUI's but they don't do what I want.
Probably you can use [Doxygen](http://www.doxygen.nl/) ?
Please see this question <https://stackoverflow.com/questions/546053/anyone-using-ndoc-or-a-similar-tool-to-help-with-system-documentation/> You will find there a brief overview of different commercial and opensource tools My vote is for [SandCastle](http://www.codeplex.com/Sandcastle)
Javadoc like documentation for C#'s XML comments
[ "", "c#", "xslt", "documentation", "comments", "javadoc", "" ]
What is the upper bound of the range() function and how can I extend it, or alternately what's the best way to do this: ``` for i in range(1,600851475143): ```
`range(1, 600851475143)` wants to generate a very large list in memory, and you'll get an out of memory error. To save memory, use `xrange` instead of `range`. Unfortunately, `xrange` doesn't work with large numbers (it's an implementation restriction) Example (raises OverflowError): ``` for i in xrange(1, 600851475143): print i ``` You can have large minimum or maximum values in your interval with `range`, if their difference is small. Example: ``` x = 1 << 200 print list(xrange(x, x + 3)) ``` Output: ``` [1606938044258990275541962092341162602522202993782792835301376L, 1606938044258990275541962092341162602522202993782792835301377L, 1606938044258990275541962092341162602522202993782792835301378L] ``` A fancy solution to your original *for* loop problem: ``` def bigrange(a, b = None): if b is None: b = a a = 0 while a < b: yield a a += 1 for i in bigrange(1, 600851475143): print i ``` A less fancy solution, which works even if you have `continue` in the loop body: ``` i = 1 - 1 while i < 600851475143 - 1: i += 1 print i ```
Have you considered just doing this? Or is there some reason you specifically need `range()`? ``` x = 1 while x < 600851475143: // some code x += 1 ```
python: can I extend the upper bound of the range() method?
[ "", "python", "python-2.x", "" ]
For debugging php code I use MacGDBp but it has its quirks: it shows only the top frame variables of the stack, it sometimes refuses to display any variable at all and last version has decorates the source text with non ascii characters. Is there any alternative that is native OS X? (ie. *not* Eclipse, I can't stand it).
I have also used MacGDBp and became frustrated with the limitations you mentioned. While it is not a native app per say, NetBeans 6.5 and higher is free and includes a decent PHP debugger that works with XDebug. <http://netbeans.org/kb/docs/php/debugging.html> It is not without it's own set of issues, but it does seem to be more reliable than MacGDBp. If you are not opposed to paying, the Komodo IDE (My IDE of choice) also has a PHP debugger. <http://www.activestate.com/komodo-ide?src=AScom&type=bn&X=HP&campaign=KMD> Also, though slightly off topic, you may find the easy Xdebug FireFox extension useful: <https://addons.mozilla.org/en-US/firefox/addon/58688/> Lastly, the XDebug website has a list of additional clients, browser plugins and instructions on how to use them: <http://www.xdebug.org/docs/remote#browser_session>
For Linux users - <http://protoeditor.sourceforge.net/> has a nice lightweight client for Xdebug which is also available as a plugin for Kate (this is not mentioned on the Xdebug site) Xdebug also runs happily with XAMPP - if you figure out where to put the compiled .so file ;) There also is an article describing on how to install Xdebug on Linux w/ XAMPP on the SaniSoft blog: <http://www.sanisoft.com/blog/2007/06/23/how-to-install-xdebug-php-extension-for-xampp-on-linux/>
MacGDBp, but better?
[ "", "php", "macos", "gdb", "" ]
I was very surprised when I found out my code wasn't working so I created a console application to see where the problem lies and I've got even more surprised when I saw the code below returns 0 ``` static void Main(string[] args) { float test = 140 / 1058; Console.WriteLine(test); Console.ReadLine(); } ``` I'm trying to get the result in % and put it in a progress(meaning (140 / 1058) \* 100) bar on my application,the second value(1058) is actually ulong type in my application,but that doesn't seem to be the problem. The question is - where the problem is?
This will work the way you expect ... ``` float test = (float)140 / (float)1058; ``` By the way, your code works fine for me (prints a 0.1323251 to the console).
You are using integer arithmetic and then converting the result to a float. Use floating-point arithmetic instead: ``` float test = 140f / 1058f; ```
Divide returns 0 instead of float
[ "", "c#", "" ]
I'm trying to use Brandon Walkin's BWSplitView from BWToolkit in a Cocoa PyObjc project. When I run the project I get the following error message: ``` NSInvalidUnarchiveOperationException - *** -[NSKeyedUnarchiver decodeObjectForKey:]: cannot decode object of class (BWSplitView) ``` Does this mean his toolkit is incompatible with a PyObc project, so I should just use the default interface builder views? BWToolkit seems pretty much perfect for my program, and I plan to use it elsewhere in my interface.
I suspect that you got that error because you had a BWSplitView in a nib/xib file that you were attempting to load. In order to unarchive the objects in a nib file, the runtime needs to be able to create instances of the archived classes (e.g. BWSplitView). The exception that's being thrown is because BWSplitView isn't available to the runtime. In an Objective-C app you would link to the BWToolkit framework and the dynamic linker would do the work of making BWSplitView available to the runtime. In a PyObjC app, you have to explicitly import classes that you want available to the runtime (that aren't linked behind the scenes for you, such as the Cocoa classes). Fortunately, BWToolkit has a bridge support file so you can import it directly (assuming it's in a standard framework location such as /Library/Frameworks). If you need to load a framework that does not have a bridge support file, you can use `objc.loadBundle` and then use `NSClassFromString` to get a class object. On a side note, /System/Library/Frameworks is reserved for Apple-supplied system frameworks. You should not put third-party frameworks in that folder as Apple may wipe that folder at a system update (unlikely but possible). Thrid-party frameworks that are made available to all users on a system should be put in /Library/Frameworks, user-specific frameworks similarly in ~/Library/Frameworks and application specific frameworks in Contents/Frameworks, where within the application's app bundle.
I've fixed this using the following steps: 1. Download and install <http://github.com/jrydberg/pyobjc-bwtoolkitframework/tree/master> 2. Ensure you have BWToolkit.framework installed in /System/Library/Frameworks (this can be done by redownloading BWToolkit and copying the folder across) 3. Use import BWToolkitFramework in main.py
BWSplitView and PyObjc
[ "", "python", "cocoa", "pyobjc", "bwtoolkit", "" ]
I am new to makefiles. I learned makefile creation and other related concepts from "Managing projects with GNU make" book. The makefile is ready now and I need to make sure the one which I created is OK. Here is the makefile ``` #Main makefile which does the build #makedepend flags DFLAGS = #Compiler flags #if mode variable is empty, setting debug build mode ifeq ($(mode),release) CFLAGS = -Wall else mode = debug CFLAGS = -g -Wall endif CC = g++ PROG = fooexe #each module will append the source files to here SRC := main.cpp #including the description include bar/module.mk include foo/module.mk OBJ := $(patsubst %.cpp, %.o, $(filter %.cpp,$(SRC))) .PHONY:all all: information fooexe information: ifneq ($(mode),release) ifneq ($(mode),debug) @echo "Invalid build mode." @echo "Please use 'make mode=release' or 'make mode=debug'" @exit 1 endif endif @echo "Building on "$(mode)" mode" @echo ".........................." #linking the program fooexe: $(OBJ) $(CC) -o $(PROG) $(OBJ) %.o:%.cpp $(CC) $(CFLAGS) -c $< -o $@ depend: makedepend -- $(DFLAGS) -- $(SRC) .PHONY:clean clean: find . -name "*.o" | xargs rm -vf rm -vf fooexe ``` **Questions** 1. The above given makefile works well with release and debug builds. But is it in the correct format? Or do you see any flaws in that? 2. Above makefile does debug build by default when invoked using *make*. For release builds, *make mode=release* is required. Is this the correct approach? 3. Is the debug and release compiler flags supplied to g++ is correct? For debug, I use *-g -Wall* and for release, just *-Wall*. Is this right? Any help would be great.
1. It is one reasonable format. It is tied specifically to GNU Make, but that's a relatively minor problem if you have chosen to use GNU Make on every platform. * If there is a flaw, it is that you could end up linking object files built in debug mode to create the final build. * Some might argue that a 'mode=release' option is non-standard; they'd be right, but there isn't a standard alternative that I'm aware of. You just need to be aware that your convention might not suit everyone (but it doesn't have to - it just has to suit you and your users). 2. Building a debug build by default is probably sensible - and more sensible than building the release build by default. 3. Dropping the `-g` flag for the release build is not automatically bad, but if your code ever produces a core dump, it is easier to make head or tail of the core dump if the program file includes debugging information. The primary cost of debugging information is extra sections in the program file that do not need to be loaded into system memory - the runtime cost is small. * You should consider whether to include optimization flags in there. With the GCC tool set, you can use both `-g` and `-O`. It is harder to debug optimized code, but it gives you (often significant) performance benefits.
I would suggest following modes: ``` for debugger: -O0 -g -Wall for development and internal release: -O2 -g -Wall for release outside the company: -O2 -Wall ``` Rationale: * It is very important to develop and test the code in "production mode". You can find that in some cases code that works without optimization crashes in optimized mode because of the bug in your code. (Believe me this happens a lot) -- So use `-O2` * In most of cases you still can debug quite well even with optimized code, so add `-g`. However, if this is too hard to find the bug in such mode you can compile for debugger with `-O0` * Only if you have problems including debug information in code, you should remove `-g`. It is good idea to have `-g` for the code in production environment, because if something crashes you can get much more information.
Simple makefile with release and debug builds - Best practices
[ "", "c++", "makefile", "g++", "" ]
I am currently writing code in C++ to find all possible permutations of 6 integers and store the best permutation (i.e. the one whose total is closest to a given value). I am trying to write this code as efficiently as possible and would apreciate any advice or examples. I was considering storing the integers in an array and performing the permutations using pointers within a loop. Is this a good approach?
They already thought of this one for you: ``` #include <algorithm> int ra[6] = { 1, 2, 3, 4, 5, 6 }; do { // whatever } while (std::next_permutation(ra, ra+6)); ``` Note that the elements have to start in increasing order (by comparison via operator<), or else the loop will terminate before you've seen every permutation. See <http://en.cppreference.com/w/cpp/algorithm/next_permutation> for details. It probably doesn't give the fastest runtime possible, because at each step it has to examine the array to work out what to change. But it's certainly the most efficient in programmer effort, and without knowing the compiler and platform it's not really possible to micro-optimise the nested loop approaches anyway.
Take a look at this excellent post @ [Coding the Wheel](http://www.codingthewheel.com/): [Exhaustively Enumerating Combinations and Permutations in Code](http://www.codingthewheel.com/archives/exhaustively-enumerating-combinations-and-permutations-in-code). It has full code and was written by a fellow [SO'r](https://stackoverflow.com/users/90/coding-the-wheel), it should be enough to get you on the right track.
Efficient coding help
[ "", "c++", "pointers", "" ]
I'm looking for a javascript library (could be based on jQuery) that will implement a client side Form Editor. The perfect example is something like offered by <http://wufoo.com/> You should play with their free version to get the feeling of what I'm trying to find. Also see [this example](http://mikenovember.com/wp-content/uploads/2007/04/form-builder.html) someone made with jQuery. it is very basic, but a step in the right direction. Do you know of any jQuery plugin or library that will give me the full functionality of form editing?
I would recommend the awesome ExtJS framework to build such kind of application. Here's an example of what you can do. [ext/formbuilder](http://tof2k.com/ext/formbuilder/) Add a form panel, then drop a textbox and so on...dead simple. Ext JS 2.2 and 3.0 (not yet ready) are LGPL and GPL licensed, you have also commercial subscriptions available, I think it worth to have a look at it.
Try the [jQuery Form Builder](http://experiments.botsko.net/tests/formbuilder/) plug-in from [Botsko](http://www.botsko.net/blog/2009/04/jquery-form-builder-plugin/)
Looking for a web based, client side form editor
[ "", "javascript", "jquery", "jquery-plugins", "webforms", "client-side", "" ]
I just discovered a bug where the code looked something like this: ``` char *foo = malloc(SOME_NUM * sizeof(char)); if (!processReturnsTrueOrFalse(foo)) { free(foo); char *foo = malloc(SOME_NUM * sizeof(char)); // More stuff, whatever } ``` This compiles, but it's weird that I am allowed to define two variables within the same function, but the compiler appears to scope them differently. If this were the case, how do I differentiate the inner foo with the outer one? How did the compiler know that in the free before my second declaration, I was trying to free the outer foo, but then when I redeclared the inner foo, it didn't give me an error? Thanks for any info. This is probably a pretty obvious, newbie question.
C++ defines a new scope for variables every time you use `{` `}`. Take a look at this example here. ``` const char *foo = "global"; int main(int argc, char* argv[]) { const char *foo = "hello"; { cout << foo << endl; const char *foo = "world"; cout << foo << endl; cout << ::foo << endl; } cout << foo << endl; } ``` When you run this, you get: ``` hello world global hello ``` When you open a new scope and declare a variable with the same name as a variable in an enclosing scope, you hide the variable in the outer scope as long as you remain in the current scope. Once you leave the inner scope, the outer variable becomes visible again. If the outer variable happens to be a globabl variable, you can access with the global namespace `::foo`. If the outer variable is a class variable, you can use `className::foo`. If the outer variable is just a local variable, there is no way to access it until you leave the scope where you declared the variable that hid it. I haven't used C in a while, so C99 will likely be different, but in the older C, there is no way to access a hidden name. ``` const char *foo = "global"; int main(int argc, char* argv[]) { const char *foo = "hello"; { char *foo = "world"; printf("%s\n", foo); } printf("%s\n", foo); return 0; } ``` When you run this, you get: ``` world hello ```
As other posters wrote, you [shadow](http://en.wikipedia.org/wiki/Variable_shadowing) the variable when declare the variable with the same name within inner scope, e.g. function or block. But there is a way to access shadowed **global non-static** variable in C: ``` int foo = 1; // global int bar(void) { printf ("%d", foo); // print global { int foo = 2; // global foo shadowed printf ("%d", foo); // print local { extern int foo; // local foo shadowed printf("%d", foo); // print global } // global foo shadowed printf ("%d", foo); // print local } // end of scope for local foo } ``` I made some dummy blocks because with pre-C99 compilers you cannot declare the variable in the middle of the block.
Interesting Scope Problem, Explanation?
[ "", "c++", "c", "objective-c", "" ]
Simple question... How am I going to reproduce Javascript bugs if I don't have a Mac & Safari? Is it possible to run a legit copy of Mac OS on VMWare, or even better...run Safari in Windows?
Apple had a windows download for safari, but it's long-gone. This is long out-of-date. Can't delete this accepted answer. :-(
> or even better...run Safari in Windows? Sure: <http://www.apple.com/safari/>
How am I going to reproduce Javascript bugs if I don't have a Mac & Safari?
[ "", "javascript", "html", "macos", "testing", "safari", "" ]
I've been reading a lot about Unit tests and Test Driven developemnt. Recently, I also read java unit test code. I however, prefer to develop in Qt. So I googled up "unit testing in c++" and found a host of information about various unit testing frameworks available for C++. However, I could not find a reliable comparison of the the various frameworks. So I look to the SO community to guide me through the selection of what may the "best" unit testing framework for c++. Also, if anybody had specific comments regarding TDD in Qt (especially using Qt-Creator), then they are more than welcome.
Usually use [Boost](http://www.boost.org/doc/libs/1_52_0/libs/test/doc/html/intro.html), but if you are using Qt, their [QtTestLib](http://qt-project.org/doc/qt-5.0/qttestlib/qtest-overview.html) might be the better choice.
I would recommend [doctest](https://github.com/onqtam/doctest) (created by me) - it's the lightest on compile times from all the popular testing frameworks. It is also a direct competitor to [Catch](https://github.com/philsquared/Catch) which is currently the most used framework - checkout the differences in the [FAQ](https://github.com/onqtam/doctest/blob/master/doc/markdown/faq.md#how-is-doctest-different-from-catch)
Unit testing in C++
[ "", "c++", "unit-testing", "qt", "tdd", "qt-creator", "" ]
This query gives me syntax error in when-between line. how can i solve them? ``` alter FUNCTION [dbo].[fn_GetActivityLogsArranger] ( @time AS nvarchar(max) ) RETURNS nvarchar(max) AS BEGIN declare @Return varchar(30) select @Return = case @time when between '15:00' and '15:30' then '15:00-15:30' when between '15:30' and '16:00' then '15:30-16:00' when between '16:00' and '16:30' then '16:00-16:30' when between '16:00' and '16:30' then '16:00-16:30' when between '16:30' and '17:00' then '16:30-17:00' when between '17:00' and '17:30' then '17:00-17:30' when between '17:30' and '18:00' then '17:30-18:00' else 'Unknown' Return @Return end ```
``` alter FUNCTION [dbo].[fn_GetActivityLogsArranger] ( @time AS varchar(30) ) RETURNS varchar(30)AS BEGIN declare @Return varchar(30) select @Return = case when @time between '15:00' and '15:30' then '15:00-15:30' when @time between '15:30' and '16:00' then '15:30-16:00' when @time between '16:00' and '16:30' then '16:00-16:30' when @time between '16:00' and '16:30' then '16:00-16:30' when @time between '16:30' and '17:00' then '16:30-17:00' when @time between '17:00' and '17:30' then '17:00-17:30' when @time between '17:30' and '18:00' then '17:30-18:00' else 'Unknown' end Return @Return end ```
You can't use that format of the case syntax. You will have to do a case which does checks: ``` select @Return = case when @time between '15:00' and '15:30' then '15:00-15:30' when @time between '15:30' and '16:00' then '15:30-16:00' when @time between '16:00' and '16:30' then '16:00-16:30' when @time between '16:00' and '16:30' then '16:00-16:30' when @time between '16:30' and '17:00' then '16:30-17:00' when @time between '17:00' and '17:30' then '17:00-17:30' when @time between '17:30' and '18:00' then '17:30-18:00' else 'Unknown' END Return @Return ``` Also, you were missing an END at the end of your case statement (see END in uppercase above).
How can i use ' when - between ' statement in sql?
[ "", "sql", "sql-server", "sql-server-2005", "" ]
``` select @result=@input.query('*') for xml raw,type ``` Above statement will generate following alert: Msg 6819, Level 16, State 3, Line 2 The FOR XML clause is not allowed in a ASSIGNMENT statement.
For example ``` DECLARE @xml_var XML SET @xml_var = ( SELECT *, ( SELECT * FROM Orders WHERE Orders.CustomerID=Customers.CustomerID FOR XML AUTO, TYPE ) FROM Customers WHERE CustomerID='ALFKI' FOR XML AUTO, TYPE ) ``` refer to : <http://blogs.msdn.com/sqlprogrammability/articles/576095.aspx>
``` DECLARE @RESULTS XML SET @RESULTS = (SELECT * FROM Table_Name FOR XML AUTO) SELECT @RESULTS ```
saving the FOR XML AUTO results to variable in SQL
[ "", "sql", "sql-server", "xml", "t-sql", "" ]
Resolving an xpath that includes namespaces in Java appears to require the use of a `NamespaceContext` object, mapping prefixes to namespace urls and vice versa. However, I can find no mechanism for getting a `NamespaceContext` other than implementing it myself. This seems counter-intuitive. **The question:** Is there any easy way to acquire a `NamespaceContext` from a document, or to create one, or failing that, to forgo prefixes altogether and specify the xpath with fully qualified names?
It is possible to get a *NamespaceContext* instance without writing your own class. Its [class-use](http://java.sun.com/javase/6/docs/api/javax/xml/namespace/class-use/NamespaceContext.html) page shows you can get one using the [javax.xml.stream](http://java.sun.com/javase/6/docs/api/javax/xml/stream/package-summary.html) package. ``` String ctxtTemplate = "<data xmlns=\"http://base\" xmlns:foo=\"http://foo\" />"; NamespaceContext nsContext = null; XMLInputFactory factory = XMLInputFactory.newInstance(); XMLEventReader evtReader = factory .createXMLEventReader(new StringReader(ctxtTemplate)); while (evtReader.hasNext()) { XMLEvent event = evtReader.nextEvent(); if (event.isStartElement()) { nsContext = ((StartElement) event) .getNamespaceContext(); break; } } System.out.println(nsContext.getNamespaceURI("")); System.out.println(nsContext.getNamespaceURI("foo")); System.out.println(nsContext .getNamespaceURI(XMLConstants.XMLNS_ATTRIBUTE)); System.out.println(nsContext .getNamespaceURI(XMLConstants.XML_NS_PREFIX)); ``` Forgoing prefixes altogether is likely to lead to ambiguous expressions - if you want to drop namespace prefixes, you'd need to change the document format. Creating a context from a document doesn't necessarily make sense. The prefixes have to match the ones used in the XPath expression, not the ones in any document, as in this code: ``` String xml = "<data xmlns=\"http://base\" xmlns:foo=\"http://foo\" >" + "<foo:value>" + "hello" + "</foo:value>" + "</data>"; String expression = "/stack:data/overflow:value"; class BaseFooContext implements NamespaceContext { @Override public String getNamespaceURI(String prefix) { if ("stack".equals(prefix)) return "http://base"; if ("overflow".equals(prefix)) return "http://foo"; throw new IllegalArgumentException(prefix); } @Override public String getPrefix(String namespaceURI) { throw new UnsupportedOperationException(); } @Override public Iterator<String> getPrefixes( String namespaceURI) { throw new UnsupportedOperationException(); } } XPathFactory factory = XPathFactory.newInstance(); XPath xpath = factory.newXPath(); xpath.setNamespaceContext(new BaseFooContext()); String value = xpath.evaluate(expression, new InputSource(new StringReader(xml))); System.out.println(value); ``` Neither the implementation returned by the StAX API nor the one above implement the full [class](http://java.sun.com/javase/6/docs/api/javax/xml/namespace/NamespaceContext.html)/[method](http://java.sun.com/javase/6/docs/api/javax/xml/namespace/NamespaceContext.html#getNamespaceURI(java.lang.String)) contracts as defined in the doc. You can get a full, map-based implementation [here](http://illegalargumentexception.blogspot.com/2009/05/java-using-xpath-with-namespaces-and.html).
I've just been working through using xpath and NamespaceContexts myself. I came across a good treatment of the issue [on developerworks](http://www.ibm.com/developerworks/xml/library/x-nmspccontext/index.html?ca=drs-).
NamespaceContext and using namespaces with XPath
[ "", "java", "xml", "xpath", "" ]
Can someone explain to me this odd thing: When in python shell I type the following Cyrillic string: ``` >>> print 'абвгд' абвгд ``` but when I type: ``` >>> print u'абвгд' Traceback (most recent call last): File "<stdin>", line 1, in <module> UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-9: ordinal not in range(128) ``` Since the first tring came out correctly, I reckon my OS X terminal can represent unicode, but it turns out it can't in the second case. Why ?
``` >>> print 'абвгд' абвгд ``` When you type in some characters, your terminal decides how these characters are represented to the application. Your terminal might give the characters to the application encoded as utf-8, ISO-8859-5 or even something that only your terminal understands. Python gets these characters as some sequence of bytes. Then python prints out these bytes as they are, and your terminal interprets them in some way to display characters. Since your terminal usually interprets the bytes the same way as it encoded them before, everything is displayed like you typed it in. ``` >>> u'абвгд' ``` Here you type in some characters that arrive at the python interpreter as a sequence of bytes, maybe encoded in some way by the terminal. With the `u` prefix python tries to convert this data to unicode. To do this correctly python has to known what encoding your terminal uses. In your case it looks like Python guesses your terminals encoding would be ASCII, but the received data doesn't match that, so you get an encoding error. The straight forward way to create unicode strings in an interactive session would therefore be something like this this: ``` >>> us = 'абвгд'.decode('my-terminal-encoding') ``` In files you can also specify the encoding of the file with a special mode line: ``` # -*- encoding: ISO-8859-5 -*- us = u'абвгд' ``` For other ways to set the default input encoding you can look at `sys.setdefaultencoding(...)` or `sys.stdin.encoding`.
As of Python 2.6, you can use the environment variable `PYTHONIOENCODING` to tell Python that your terminal is UTF-8 capable. The easiest way to make this permanent is by adding the following line to your `~/.bash_profile`: ``` export PYTHONIOENCODING=utf-8 ``` ![Terminal.app showing unicode output from Python](https://i.stack.imgur.com/T3sID.png)
Python unicode in Mac os X terminal
[ "", "python", "macos", "unicode", "terminal", "" ]
> **Possible Duplicates:** > [BOO Vs IronPython](https://stackoverflow.com/questions/600539/boo-vs-ironpython) > [Boo vs. IronPython](https://stackoverflow.com/questions/193862/boo-vs-ironpython) Say you want to embed a scripting language into a .NET application. Boo is modelled on Python syntax, but also includes type inference, and just in general seems to be a better, more modern language to embed as a scripting language. Why, then, is there so much fuss about Iron Python? *LATER* As was pointed out, this question is an exact duplicate of: [this](https://stackoverflow.com/questions/193862/) and [this](https://stackoverflow.com/questions/600539)
IronPython is directly developed and supported by Microsoft (under the awesome technical lead of Jim Hugunin!), AND has an insanely great book about it ("IronPython in Action", which I'm biased about but nevertheless evangelize shamelessly). Apart from that, Boo appears to be a great contender, and I'd love to try it out (were I ever to use .NET in earnest rather than as a for-fun endeavor -- as my professional development these days targets Linux and Mac, not Windows, that doesn't seem a likely prospect). If you're using .NET as your main development target, my recommendation is to pick a few small but not toy projects in your area of expertise and develop each of them in both Boo and IronPython (alternating which one goes first) -- after you're through a few, you'll KNOW what's right for you. That's how I ended up switching from Perl 4 to Python as my main language back in the '90s (rather than sticking with Perl 4, of which I was an expert and guru, or switching to then-brand-new Perl 5) -- a few "pilot projects" fully developed in each environment left me with no doubt about what was best for my own productivity.
2 words: User Base. I already know so many languages that I have to keep references handy so I can remember if it's "else if", "elsif" or "elif" in whatever I'm currently working in. Unless there's a compelling reason to use another language (more than just a few small differences) I'm going to stick with one I already know.
Why would one choose Iron Python instead of Boo?
[ "", ".net", "python", "ironpython", "boo", "" ]
I have a need to do RAW POST (PUT a $var) requests to a server, and accept the results from that page as a string. Also need to add custom HTTP header information (like x-example-info: 2342342) I have two ways of doing it * Curl (<http://us.php.net/manual/en/book.curl.php>) * PHP HTTP using the HTTPRequest (<http://us.php.net/manual/en/book.http.php>) What are the differences between the two? what's more lean? faster? Both seem pretty much the same to me...
Curl is bundled with PHP, HTTPRequest is a separate PECL extension. As such, it's much more likely that CURL will be installed on your target platform, which is pretty much the deciding factor for most projects. I'd only consider using HTTPRequest if you plan to only ever install your software on servers you personally have the ability to install PECL extensions on; if your clients will be doing their own installations, installing PECL extensions is usually out of the question. [This page](http://us.php.net/manual/en/intro.http.php) seems to suggest that HTTPRequest uses CURL under the hood anyway. Sounds like it might offer a slightly more elegant interface to curl\_multi\_\*(), though.
HTTPRequest (and the PECL extension) is built on libcurl. <http://us.php.net/manual/en/http.requirements.php> The HTTPRequest is really just an easier/more syntactically friendly way to perform the same task. As Frank Farmer mentioned, you're more likely to have a target platform with curl already installed and could have difficulty getting the PECL library installed by the hosting provider.
PHP Difference between Curl and HttpRequest
[ "", "php", "http", "post", "" ]
I was able to find example code to get the current timestamp in Linux Epoch (Seconds since Midnight Jan 1st 1970), however I am having trouble finding an example as to how to calculate what the Epoch will be in the future, say for example 10 minutes from now, so how can I calculate a future time in Linux Epoch?
This extension method should do the job: ``` private static double GetUnixEpoch(this DateTime dateTime) { var unixTime = dateTime.ToUniversalTime() - new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc); return unixTime.TotalSeconds; } ``` And you can use it as such: ``` var unixTime1 = DateTime.Now.GetUnixEpoch(); // precisely now var unixTime2 = (DateTime.Now + new TimeSpan(0, 10, 0)).GetUnixEpoch(); // 10 minutes in future ``` Note that you need to deal with all date-times in **UTC** (Universal Time), since that's how the start of the Unix Epoch is defined.
There is an interesting twist when you want to know the Unix Epoch time in .Net on a Windows system. For nearly all practical cases and assuming the current time is past the Unix Epoch you could indeed take ``` System.TimeSpan timeDifference = DateTime.UTCNow - new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc); long unixEpochTime = System.Convert.ToInt64(timeDifference.TotalSeconds); ``` But, Unix Epoch Time is defined as "... a system for describing points in time, defined as the number of seconds elapsed since midnight Coordinated Universal Time (UTC) of January 1, 1970, **not counting leap seconds**." (1) Since 1972, UTC has included "leap seconds", and we have had a total of 25 of them so far. (2) The .Net DateTime has no provisions for Leap Seconds, but will simply rely on the OS time. Windows is blissfully unaware of Leap Seconds (3)(4), and so will just have the notion of time as it receives it from its NTP master (I believe the default for a non-domain connected machine is time.windows.com ), which is probably serving up UTC including leap seconds. This means that in order to be pedantically correct about the real number of seconds passed since the Unix epoch, you should probably add the leap seconds to the result obtained above for applications that rely on this. You would have to track the number of seconds to add at each time since leap seconds are not announced far in advance (2). However, as the definition of Unix Epoch Time explicitly excludes leap seconds, you can safely ignore this and simply recalculate seconds from the current UTC time. Sometimes, leap seconds do cause software mayhem (5). The debate over whether to keep or eliminate the practice is ongoing (6)(7)(8). The last leap second at the time of the answer occurred on the 1st of July 2012 (9) and caused problems for various sites and applications (10) (1) <http://en.wikipedia.org/wiki/Unix_time> (2) <http://en.wikipedia.org/wiki/Leap_second> (3) <http://support.microsoft.com/kb/909614> (4) <http://www.meinberg.de/english/info/leap-second.htm> (5) <http://www.networkworld.com/news/2009/010609-leap-second-snafu-affects-oracle.html> (6) <http://www.pcworld.idg.com.au/article/358024/time_waits_no_one_leap_seconds_may_cut/> (7) <http://queue.acm.org/detail.cfm?id=1967009> (8) <http://arxiv.org/abs/1106.3141> (9) <http://hpiers.obspm.fr/iers/bul/bulc/bulletinc.dat> (10) <http://arstechnica.com/business/2012/07/one-day-later-the-leap-second-v-the-internet-scorecard/> (The original answer had a mistake, which was thankfully caught by the commenters Edward Brey and Mormegil below)
Calculating Future Epoch Time in C#
[ "", "c#", "time", "epoch", "" ]
I have several textboxes where users can enter information into them. This can include commas, so I can't use the standard comma delimited strings. What is a good delimiter to denote that strings should be separated based on that character that isn't typically used by users in their writings? I'm going to be combining these fields into a string string and passing them off to my Encryption method I have. After I decrypt them I need to be able to reliably separate them. I'm using C# if it matters.
| would be next on my list and is often used as an alternative to CSV. google "pipe delimited" and you will find many examples. ``` string[] items = new string[] {"Uno","Dos","Tres"}; string toEncrypt = String.Join("|", items); items = toEncrypt.Split(new char[] {'|'}, StringSplitOptions.RemoveEmptyEntries); foreach(string s in items) Console.WriteLine(s); ``` And since everyone likes to be a critic about the encoding and not provide the code, here is one way to encode the text so your | delim won't collide. ``` string[] items = new string[] {"Uno","Dos","Tres"}; for (int i = 0; i < items.Length; i++) items[i] = Convert.ToBase64String(Encoding.UTF8.GetBytes(items[i])); string toEncrypt = String.Join("|", items); items = toEncrypt.Split(new char[] {'|'}, StringSplitOptions.RemoveEmptyEntries); foreach (string s in items) Console.WriteLine(Encoding.UTF8.GetString(Convert.FromBase64String(s))); ```
I have seen unusal characters used as delimiters, even unusal character combinarions like `-|::|-`, but eventhough they are more unlikely to occur, they still can. You have basically two options if you want to make it water tight: 1: Use a character that is impossible to type, like the '\0' character: Join: ``` string combined = string.Join("\0", inputArray); ``` Split: ``` string[] result = combined.Split('\0'); ``` 2: Escape the string and use an escaped character as delimiter, like url encoding the values and use & as delimiter: Join: ``` string combined = string.Join("&", inputArray.Select<string,string>(System.Web.HttpUtility.UrlEncode).ToArray()); ``` Split: ``` string[] result = combined.Split('&').Select<string,string>(System.Web.HttpUtility.UrlDecode).ToArray(); ```
What is a more unique delimiter than comma for separating strings?
[ "", "c#", "csv", "" ]
Is there an event that is fired when the user presses the close button? This is because the Window `Closing` event is fired both when one closes the window manually (with the `Close` method) and also when the user presses the [X] button...but I somehow need to know only when the user presses the [X] button not when the window is closed manually.
I don't believe there is a way to tell those apart in WPF (though I'm not positive). The way I always handled it in WinForms was to create a member variable "\_Closing", set it to false, and a method "ReallyClose()" that would set \_Closing to true, then call Close. My Closing handler would then cancel the close if \_Closing was not set to true. Yeah, it's a bit of a hack, but it worked.
I also don't think there is a way to tell them apart. You can put a handler on the Application.Exit event, but it doesn't distinguish between "red X button close" and "alt-F4 close" (or whatever other types of close you are considering). BTW, if you check for Application.Exit, be sure to check for Application.SessionEnding too - if someone logs off while your app is running, you can't be guaranteed that Application.Exit will be called.
WPF: Is there an event that is fired when the user presses the close button [X]?
[ "", "c#", "wpf", "events", "" ]
I want to *fit* strings into a specific width. Example, "Hello world" -> "...world", "Hello...", "He...rld". Do you know where I can find code for that? It's a neat trick, very useful for representing information, and I'd like to add it in my applications (of course). **Edit**: Sorry, I forgot to mention the **Font** part. Not just for fixed width strings but according to the font face.
It's a pretty simple algorithm to write yourself if you can't find it anywhere - the pseudocode would be something like: ``` if theString.Length > desiredWidth: theString = theString.Left(desiredWidth-3) + "..."; ``` or if you want the ellipsis at the start of the string, that second line would be: ``` theString = "..." + theString.Right(desiredWidth-3); ``` or if you want it in the middle: ``` theString = theString.Left((desiredWidth-3)/2) + "..." + theString.Right((desiredWidth-3)/2 + ((desiredWidth-3) mod 2)) ``` **Edit:** I'll assume you're using MFC. Since you're wanting it with fonts, you could use the [CDC::GetOutputTextExtent](http://msdn.microsoft.com/en-us/library/98e99kxk(VS.80).aspx) function. Try: ``` CString fullString CSize size = pDC->GetOutputTextExtent(fullString); bool isTooWide = size.cx > desiredWidth; ``` If that's too big, then you can then do a search to try and find the longest string you can fit; and it could be as clever a search as you want - for instance, you could just try "Hello Worl..." and then "Hello Wor..." and then "Hello Wo..."; removing one character until you find it fits. Alternatively, you could do a [binary search](http://en.wikipedia.org/wiki/Binary_search) - try "Hello Worl..." - if that doesn't work, then just use half the characters of the original text: "Hello..." - if that fits, try halfway between it and : "Hello Wo..." until you find the longest that does still fit. Or you could try some estimating heuristic (divide the total length by the desired length, proportionately estimate the required number of characters, and search from there. The simple solution is something like: ``` unsigned int numberOfCharsToUse = fullString.GetLength(); bool isTooWide = true; CString ellipsis = "..."; while (isTooWide) { numberOfCharsToUse--; CString string = fullString.Left(numberOfCharsToUse) + ellipsis; CSize size = pDC->GetOutputTextExtent(string); isTooWide = size.cx > desiredWidth; } ```
It's really pretty trivial; I don't think you'll find specific code unless you have something more structured in mind. You basically want: 1. to get the length of the string you have, and the window width. 2. figure out how many charaters you can take from the original string, which will basically be window width-3. Call that *k*. 3. Depending on whether you want to put the ellipsis in the middle or at the right hand end, either take the first floor(k/2) characters from one end, concatenated with "...", then concatenated with the last floor(k/2) characters (with possibly one more character needed because of the division); or take the first k characters, ollowed by "...".
How can I transform a string into an abbreviated form?
[ "", "c++", "algorithm", "mfc", "string", "abbreviation", "" ]
I have a table that stores user information. The table has a userid (identity) column in it. The table data is queried by a view which is referenced by a lot of sprocs, but we reference something called auid which is created by the UDF below. The UDF is called in the view and sprocs then join or query from the view based on auid. It appears that this routine is being called A LOT (thousands of times) and is causing some unnecessary load on our SQL Server. Is there a better way to take a user\_id = 255 and turn it into a varchar = 000000255 (9 characters long)? UDF syntax: ``` ALTER FUNCTION [dbo].[udf_AUID] (@user_id int) RETURNS char(9) with schemabinding AS BEGIN DECLARE @user_id_string varchar(9) DECLARE @rval char(9) SELECT @user_id_string=CAST(@user_id as varchar(9)) SELECT @rval=LEFT('000000000',9-len(@user_id_string))+@user_id_string RETURN @rval END ``` Basic syntax from the view is: ``` ALTER VIEW [dbo].[v_users] AS SELECT dbo.udf_AUID(dbo.users.user_id) AS auid, user_id, dbo.users.username FROM dbo.users ``` Example call in a sproc looks like this: ``` DECLARE @auid CHAR(9) SET @auid = '000002444' --normally passed in, but set here for example SELECT dealer_range FROM users WHERE auid = @auid DECLARE @cat_access TINYINT, @mit_access TINYINT SELECT @cat_access = chan_access & 1, @mit_access = chan_access & 2 FROM appian.dbo.v_users WHERE auid = @auid ``` Thanks in advance!
You can use two functions that will help you out: [RIGHT](http://msdn.microsoft.com/en-us/library/ms177532.aspx) and [REPLICATE](http://msdn.microsoft.com/en-us/library/ms174383.aspx) ``` SELECT RIGHT(REPLICATE('0', 9) + '123456789', 9) -- Result: 123456789 SELECT RIGHT(REPLICATE('0', 9) + '255', 9) -- Result: 000000255 SELECT RIGHT(REPLICATE('0', 9) + '12', 9) -- Result: 000000012 SELECT RIGHT(REPLICATE('0', 9) + '1', 9) -- Result: 000000001 ```
Any reason you can't just store the userid that way to begin with?
SQL string manipulation
[ "", "sql", "stored-procedures", "string", "user-defined-functions", "" ]
### Exact Duplicate: > [In C# what is the difference between myint++ and ++myint?](https://stackoverflow.com/questions/437026/in-c-what-is-the-difference-between-myint-and-myint) Hopefully this is not too general or weird of a question. Also, couldn't find it on Google, don't whether this is just too dumb of a question or whether I fail at Google. So, I forget where I read this from but, it said that using '++x' (or whatever other variable) is somehow more optimized or whatever you might call this than, 'x++'. So, is this just a looks thing or is one truly faster? Like, they do the exact same thing so, that is why I am asking.
They're doing different things. The first is pre-increment, and the second is post-increment. If you use either alone on a line, you won't notice the difference. But if you do (for instance): ``` a = x++ ``` or ``` a = ++x ``` you will. With post-increment, you get the value, then increment. With pre-increment, you increment, then get the value. See <http://en.wikipedia.org/wiki/++#Use_in_programming_languages> for a brief explanation (they use JS as an example, but it applies equally to C#) EDIT: By popular demand (and to refute a couple exaggerations), here's a little about performance with primitives in C++. Take this example program: ``` int main() { int a; int x = 14, y = 19; a = x++; a = ++y; } ``` It compiles (g++, just -S) to the below on x86. I have removed irrelevant lines. Let's look at what's happening and see if unnecessary duplicates are being made.: ``` # Obvious initialization. movl $14, -12(%ebp) movl $19, -16(%ebp) movl -12(%ebp), %eax # This is moving "old x" to the accumulator. movl %eax, -8(%ebp) # Moving accumulator to a. addl $1, -12(%ebp) # Increment x (post-increment). addl $1, -16(%ebp) # Increment y (pre-increment) movl -16(%ebp), %eax # Move "new y" to accumulator. movl %eax, -8(%ebp) # Move accumulator to a. ``` We're done. As you can see, in this example, the exact same operations are required in each case. Exactly 2 movl, and 1 addl. The only difference is the order (surprised?). I think this is fairly typical of examples where the increment statement's value is used at all.
If you are optimizing at this level you are wasting time. There are surely some loops in your program that could get faster.
In C#, which is more optimized, if that is the right word: ++x or x++?
[ "", "c#", "" ]
I'm trying to test an Order entity method called AddItem and I'm trying to make sure that duplicate items cannot be added. Here is some example code: ``` [Test] public void ItemCannotBeAddedTwiceToOrder() { Order o = new Order(); Item i = new Item("Bike"); o.AddItem(i); o.AddItem(i); Assert.AreEqual(o.ItemCount, 1, "A duplicate item was added."); } public void AddItem(Item newItem) { if(!CheckForDuplicateItem(newItem)) _items.Add(newItem); } public bool CheckForDuplicateItem(Item newItem) { foreach(Item i in _items) { if(i.Id == newItem.Id) return true; } return false; } ``` So here is my problem: how do I set the new Item's private setter Id in the test method so the CheckForDuplicateItem method will work? I don't want to make that member public for good coding practices, I guess. Am I just being stupid and need to make the entity Item have a public Id setter? Or do I need to use reflection? Thanks Note - I'm using NHibernate for persistence
I usually use reflection for this purpose. Something like this will work: ``` typeof(Item).GetProperty(nameof(Item.Id)).SetValue(i, 1, null); ``` where 1 is the id that you want to set for the newItem instance. In my experience, you'll rarely need to set the Id, so it's better just to leave the setter private. In the few cases that you do need to set the Id for testing purposes, simply use Reflection.
Since you are checking the behavior of your Order you can use mock objects as its items. Using mock objects you can define your assertions of what's going to happen to your mock objects and test them too. In this case you can define two mock objects for each of items and expect that their id getter will be called and will return a unique value.Then you can test the Order behavior and check to see if id getter of item is called as you expected. I recommend using [Rhino Mocks](http://ayende.com/projects/rhino-mocks.aspx) by Ayende
Unit Testing Private Setter Question (C#)
[ "", "c#", "unit-testing", "tdd", "" ]
I am using anonymous methods to handle events in a COM object. Once the program terminates, it appears that the resources I am using in the anonymous method are not being "closed correctly" in that I get a first chance exception (InvalidComObjectException) for every resource I was watching. I suppose this isn't a big deal, but it doesn't feel "right." I can't fathom a way to access those captured variables outside the scope of the anonymous methods (which you're not supposed to be able to do, anyway). How can I close/dispose of the resources prior to exiting the application? EDIT: After a brief re-read, it may not be clear what I'm doing here. I am writing a managed application that consumes a COM object. Further Edit: I am using [ArcGIS Engine](http://www.esri.com/software/arcgis/arcgisengine/index.html) to manipulate GIS data. In this particular case, I am using the VisibilityChanged event in ILayerEvents\_Event to monitor when a GIS layer is made visible or invisible. The event ONLY passes a bool (visible or not visible) and NOT the layer name, so a method would need to be created for EACH layer to create it's visibility state change. Since I'm dealing with dynamic layers, I needed a way to somehow do this dynamically, hence the anonymous methods. Inside the anonymoua method, I have an ILayer variable which grabs the ILayerEvents\_Event from an outer loop (in an ILayer context) so that I know which layer I'm working with. It's at this point that I'm stuck. The functionality works and everything is grand until I exit the application, leaving those 20+ references hanging there with no place to go but to an exception. I have no idea when the user will hide/show a layer for the last time, so there's no way to null things out on the last go. I suppose I can just leave it as is (or, perhaps there's a better way to do this than the anonymous methods) since it doesn't seem to be hurting anything. I just think I'm missing something.
It's not quite possible to know this from how you've described it, but maybe you have a COM object that is holding references to C# objects, due to methods on those objects being enlisted as event handlers for an event exposed on the COM object, and when the COM object is no longer in use, it gets finalized. Assuming the COM object is "apartment" based, this means that a message will be posted from the finalizer thread to the Windows message queue of the thread that created the COM object, requesting that Release should be called on the COM object. At that point, the COM object will likely call Release on the C# objects implementing any enlisted event handlers. This is all probably happening when the last of your application's managed code has finished running, and so the CLR is in the process of trying to unload itself. It may be that during shutdown, the CLR has to cope with any possible reference count leaks by allowing objects to be collected or put into an invalid state before their reference counts have dropped to zero. So this might (pure conjecture) explain what you are seeing. If so, you need to shut down the COM object at a time of your own choosing. The solution is to call `Marshal.ReleaseComObject` in a loop until it returns zero, on the COM object, as part of the normal shutdown of the application. <http://msdn.microsoft.com/en-us/library/system.runtime.interopservices.marshal.releasecomobject(VS.71).aspx> **Update, based on updated question:** Okay, so you have some COM objects referred to by the anonymous method closures. The only thing that will happen to those COM objects is that Release will be called on them. If that's causing a problem, it is most likely due to them already being in an invalid state. So I'd recommend that when you make the set of anonymous method closures which hold references to the COM objects, you should also add those COM objects to a separate list. This will allow you to then call `Marshal.ReleaseComObject` on them when you're discarding this whole system.
Try to use unsafe mode in C#, create stuff on the heap and delete it when done. Another idea is to store a reference to the resources in variables that are outside of the anonymous method, and close them correctly at the programs termination. Then again, all you may need is a call to Dispose(). A little more info would be helpful. When is the exception being thrown? What do you mean by resources and "closed correctly."
How does one release/dispose/destroy captured variables in anonymous methods?
[ "", "c#", "com", "dispose", "anonymous-methods", "" ]
I have a webcam feed being displayed on my form and would like to draw on top of it. I was going to do this using a picture box, I have found the PictureBox doesn't support true transparency instead just the colour of the form it's on. It also doesn't support alphablending which is how I would want it to display, similar to how forms can be made to appear. Does anyone know how to do this? Or have a control implemented that can do this?
In most circumstances OwenP's answer of doing this using the method Bob Powell demonstrated in [transcontrols](https://web.archive.org/web/20141227200000/http://bobpowell.net/transcontrols.aspx) will work. However, because it was a direct draw interface to the webcam ,the live feed always seemed to be on top of the other controls. To solve this I cheated a little and created a secondary form that opens over the video feed - this had no borders, was set to always on top, and given transparency - I drew directly onto this form. I then just had to handle a few events in this secondary form to keep focus on the original form and handle when another program is in use.
Transparency in Windows Forms is kind of broken. As you have discovered, it doesn't really support overlapping controls; it just shows the form's background color through the transparent parts. With some Windows API magic, you can make many controls display as truly transparent with support for overlapping, as [this article by Bob Powell demonstrates](https://web.archive.org/web/20141227200000/http://bobpowell.net/transcontrols.aspx). I've been able to make his technique work for labels and custom controls, but I think I've tried to make it work for `PictureBox` with disappointing results. One workaround could be try create a custom control that manually draws the image; I haven't tried. [Here's a forum post](http://www.xtremevbtalk.com/showthread.php?t=288178) where I demonstrate a custom control that supports true transparency (my handle on that forum is AtmaWeapon.) My memory seems to suggest that this works best for custom controls due to some apparent magic that happens with Microsoft's controls when they are rendered. Alternatively, you could implement your application using WPF instead of WinForms. WPF's transparency works and supports overlapping controls. This is a pretty big shift in how you'd develop your application, but it works from the start.
C# Alpha Blend Transparent PictureBox
[ "", "c#", "transparency", "alphablending", "" ]
Having the following class: ``` public class SomeClass { private readonly int[] _someThings; public SomeClass() { _someThings = new int[4]; } public int[] SomeThings { get { return _someThings; } } } ``` How would I use the object initializer syntax to initialize the ***SomeThings*** property like in the following (non-working) code extract? ``` var anObject = new SomeClass { SomeThings[0] = 4, SomeThings[3] = 8 } ``` --- ### Update One could do (even without a *set* property): ``` anObject.SomeThings[0] = 4; anObject.SomeThings[3] = 8; ``` But I'm trying to use the object initializer syntax.
Theoretically you could do it this way: ``` var anObject = new SomeClass { InitialSomeThings = new[] { 1, 2, 3, 4 } } class SomeClass { private readonly int[] _somethings; public int[] get { return _somethings; } } public int[] InitialSomeThings { set { for(int i=0; i<value.Length; i++) _somethings[i] = value[i]; } } } ```
AFAIK, You could only have a Add method like this: ``` public class SomeClass { void Add(int index, int item) { // ... } } var anObject = new SomeClass() { {0, 4}, // Calls Add(0, 4) {4, 8} // Calls Add(4, 8) } ```
C# 3.0, object initializer and get property returning array, how to initialize?
[ "", "c#", "c#-3.0", "initialization", "" ]
**EDIT:** This post was originally specific to ASP.NET, but after thinking about it I'm quite interested to discover any contenders to .NET development. There used to be [sharpdevelop](http://www.icsharpcode.net/OpenSource/SD/) IDE, which I'm not even sure if it did ASP.NET (it did WinForms). Express killed it off I think. ***EDIT:** I was wrong about SharpDevelop (thanks for pointing that out Joel)* In my defence, I went to look it up and saw an old looking website. I clicked on [News History](http://www.icsharpcode.net/OpenSource/SD/NewsHistory.aspx) and the last update was 2005, which was when I last looked at it! So they made me think it was dead :) I love Visual Studio and it's very, very powerful - and it's evolved and matured over quite a few years with a big budget behind it. But I was wondering if anyone knew of anything with a fresh perspective? Any big open source projects that had slipped the radar? p.s. -1 for anyone who says "notepad + command prompt"! :)
[MonoDevelop](http://monodevelop.com/) is an up-and-coming IDE. It's strictly not pure ASPNET but it's pretty good for something *so* new.
As of this writing, [SharpDevelop 3.1 beta 1](http://community.sharpdevelop.net/forums/t/9510.aspx) was released only 13 days ago. Doesn't sound very dead to me. In fact it's the only choice on Windows if you want an IDE for the Boo programming language. And hey, it's even got a built-in profiler! I might have to check that out, thanks for reminding me to take another look.
Are there any serious contendors to Visual Studio for .NET development?
[ "", "c#", "asp.net", "visual-studio", "ide", "" ]
I haven't touched Java since using JBuilder in the late 90's while at University, so I'm a little out of touch - at any rate I've been working on a small Java project this week, and using Intellij IDEA as my IDE, for a change of pace from my regular .Net development. I notice it has support for adding interfaces and @interfaces, what is an @interface, and how does it differ from a normal interface? ``` public interface Test { } ``` vs. ``` public @interface Test { } ``` I've done a bit of searching, but couldn't find a great deal of useful info referring to @interface.
The *@* symbol denotes an annotation type definition. That means it is **not** really an interface, but rather a new annotation type -- to be used as a function modifier, such as *@override*. See this [javadocs entry](http://java.sun.com/j2se/1.5.0/docs/guide/language/annotations.html) on the subject.
interface: In general, an interface exposes a contract without exposing the underlying implementation details. In Object Oriented Programming, interfaces define abstract types that expose behavior, but contain no logic. Implementation is defined by the class or type that implements the interface. @interface : (Annotation type) Take the below example, which has a lot of comments: ``` public class Generation3List extends Generation2List { // Author: John Doe // Date: 3/17/2002 // Current revision: 6 // Last modified: 4/12/2004 // By: Jane Doe // Reviewers: Alice, Bill, Cindy // class code goes here } ``` Instead of this, you can declare an annotation type ``` @interface ClassPreamble { String author(); String date(); int currentRevision() default 1; String lastModified() default "N/A"; String lastModifiedBy() default "N/A"; // Note use of array String[] reviewers(); } ``` which can then annotate a class as follows: ``` @ClassPreamble ( author = "John Doe", date = "3/17/2002", currentRevision = 6, lastModified = "4/12/2004", lastModifiedBy = "Jane Doe", // Note array notation reviewers = {"Alice", "Bob", "Cindy"} ) public class Generation3List extends Generation2List { // class code goes here } ``` PS: **Many annotations replace comments in code.** Reference: <http://docs.oracle.com/javase/tutorial/java/annotations/declaring.html>
What's the difference between interface and @interface in java?
[ "", "java", "interface", "annotations", "language-features", "" ]
I have a Person object with a Nullable DateOfBirth property. Is there a way to use LINQ to query a list of Person objects for the one with the earliest/smallest DateOfBirth value? Here's what I started with: ``` var firstBornDate = People.Min(p => p.DateOfBirth.GetValueOrDefault(DateTime.MaxValue)); ``` Null DateOfBirth values are set to DateTime.MaxValue in order to rule them out of the Min consideration (assuming at least one has a specified DOB). But all that does for me is to set firstBornDate to a DateTime value. What I'd like to get is the Person object that matches that. Do I need to write a second query like so: ``` var firstBorn = People.Single(p=> (p.DateOfBirth ?? DateTime.MaxValue) == firstBornDate); ``` Or is there a leaner way of doing it?
``` People.Aggregate((curMin, x) => (curMin == null || (x.DateOfBirth ?? DateTime.MaxValue) < curMin.DateOfBirth ? x : curMin)) ```
Unfortunately there isn't a built-in method to do this, but it's easy enough to implement for yourself. Here are the guts of it: ``` public static TSource MinBy<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource, TKey> selector) { return source.MinBy(selector, null); } public static TSource MinBy<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource, TKey> selector, IComparer<TKey> comparer) { if (source == null) throw new ArgumentNullException("source"); if (selector == null) throw new ArgumentNullException("selector"); comparer ??= Comparer<TKey>.Default; using (var sourceIterator = source.GetEnumerator()) { if (!sourceIterator.MoveNext()) { throw new InvalidOperationException("Sequence contains no elements"); } var min = sourceIterator.Current; var minKey = selector(min); while (sourceIterator.MoveNext()) { var candidate = sourceIterator.Current; var candidateProjected = selector(candidate); if (comparer.Compare(candidateProjected, minKey) < 0) { min = candidate; minKey = candidateProjected; } } return min; } } ``` Example usage: ``` var firstBorn = People.MinBy(p => p.DateOfBirth ?? DateTime.MaxValue); ``` Note that this will throw an exception if the sequence is empty, and will return the *first* element with the minimal value if there's more than one. Alternatively, you can use the implementation we've got in [MoreLINQ](https://github.com/morelinq/MoreLINQ), in [MinBy.cs](https://github.com/morelinq/MoreLINQ/blob/ec4bbd3c7ca61e3a98695aaa2afb23da001ee420/MoreLinq/MinBy.cs). (There's a corresponding `MaxBy`, of course.) Install via package manager console: > PM> Install-Package morelinq
How to use LINQ to select object with minimum or maximum property value
[ "", "c#", ".net", "linq", "" ]
Similar to how you can define an integer constant in hexadecimal or octal, can I do it in binary?
So, with the release of Java SE 7, binary notation comes standard out of the box. The syntax is quite straight forward and obvious if you have a decent understanding of binary: ``` byte fourTimesThree = 0b1100; byte data = 0b0000110011; short number = 0b111111111111111; int overflow = 0b10101010101010101010101010101011; long bow = 0b101010101010101010101010101010111L; ``` And specifically on the point of declaring class level variables as binaries, there's absolutely no problem initializing a static variable using binary notation either: ``` public static final int thingy = 0b0101; ``` Just be careful not to overflow the numbers with too much data, or else you'll get a compiler error: ``` byte data = 0b1100110011; // Type mismatch: cannot convert from int to byte ``` Now, if you really want to get fancy, you can combine that other neat new feature in Java 7 known as numeric literals with underscores. Take a look at these fancy examples of binary notation with literal underscores: ``` int overflow = 0b1010_1010_1010_1010_1010_1010_1010_1011; long bow = 0b1__01010101__01010101__01010101__01010111L; ``` Now isn't that nice and clean, not to mention highly readable? I pulled these code snippets from a little article I wrote about the topic over at TheServerSide. Feel free to check it out for more details: [Java 7 and Binary Notation: Mastering the OCP Java Programmer (OCPJP) Exam](http://www.theserverside.com/tutorial/Java-7-and-Binary-Notation)
In Java 7: ``` int i = 0b10101010; ``` There are no binary literals in older versions of Java (see other answers for alternatives).
In Java, can I define an integer constant in binary format?
[ "", "java", "syntax", "binary", "" ]
I have an existing application which does all of its logging against log4j. We use a number of other libraries that either also use log4j, or log against Commons Logging, which ends up using log4j under the covers in our environment. One of our dependencies even logs against slf4j, which also works fine since it eventually delegates to log4j as well. Now, I'd like to add ehcache to this application for some caching needs. Previous versions of ehcache used commons-logging, which would have worked perfectly in this scenario, but as of [version 1.6-beta1](http://ehcache.sourceforge.net/changes-report.html#1.6.0-beta1) they have removed the dependency on commons-logging and replaced it with java.util.logging instead. Not really being familiar with the built-in JDK logging available with java.util.logging, is there an easy way to have any log messages sent to JUL logged against log4j, so I can use my existing configuration and set up for any logging coming from ehcache? Looking at the javadocs for JUL, it looks like I could set up a bunch of environment variables to change which `LogManager` implementation is used, and perhaps use that to wrap log4j `Logger`s in the JUL `Logger` class. Is this the correct approach? Kind of ironic that a library's use of built-in JDK logging would cause such a headache when (most of) the rest of the world is using 3rd party libraries instead.
One approach I have used successfully is to use [slf4j](http://www.slf4j.org/) as my primary logging API. I then have slf4j bind to log4j. 3rd party dependencies using other frameworks (like JUL) can be [bridged](http://www.slf4j.org/legacy.html#jul-to-slf4j) to slf4j.
We use [SLF4J](http://www.slf4j.org/) on our current project and it's worked very well for us. SLF4J is written by Ceki Gülcü, the creator of Log4J, and he's done a really great job. In our code we use the SLF4J logging APIs directly, and we configure SLF4J so that calls from the [Jakarta Commons Logging](http://commons.apache.org/logging/) (JCL), java.util.logging (JUL), and [Log4J](http://logging.apache.org/log4j/1.2/index.html) APIs are all bridged to the SLF4J APIs. We need to do that because like you we use third party (open source) libraries that have chosen different logging APIs. On the bottom of SLF4J, you configure it to use a particular logger implementation. It comes with an internal, or "simple" logger, and you can override this with Log4J, JUL, or [Logback](http://logback.qos.ch/). Configuration is all done simply by dropping in different jar files in your classpath. Originally, we used the Logback implementation, also written by Ceki Gülcü. This is very powerful. However, we then decided to deploy our application to the Glassfish Java EE application server, whose log viewer expects JUL-formatted messages. So today I switched from Logback to JUL, and in just a few minutes I replaced two Logback jars with an SLF4J jar that connects it to the JUL implementation. So like @overthink, I would heartily recommend using SLF4J in your setup.
How to send java.util.logging to log4j?
[ "", "java", "logging", "log4j", "apache-commons", "slf4j", "" ]
I got the requirement to output some reports as Excel 2002 spreadsheets. Normally a job for reporting services - however - that's "not great IMO" and I hate it so for this project I used ExtJs - which doesn't do any excel output - not really - but does do the UI really, really well. The reports will need to have outlining, grouping summaries and all sorts of formatting not available if I use the plain XML formatting. This is the one thing Reporting services does do really well. Gutted. So... Does anyone have any suggestions for alternatives to reporting services and definitely not installing Office on the server? Crystal reports are just as "not great IMO" as RS so not that either :) I have looked at aspose et al but they're a bit expensive and I'd like to find something open-source, if possible - such as perhaps using open office -, if I can find a way of using OOo on the server without actually installing it. Any ideas?
I ended up going the OpenXml SDK route - which is a bit of a PITA in some situs but good in others - once you get the hang of it...
If your reports are not very large perhaps you can get away using the [free version of Gembox Spreadsheed](http://www.gemboxsoftware.com/GBSpreadsheetFree.htm)?
How can I generate Excel spreadsheets on the server?
[ "", "c#", "asp.net", "excel", "" ]
I am writing an application that will ship in several different versions (initially around 10 variations of the code base will exist, and will need to be maintained). Of course, 98% or so of the code will be the same amongst the different systems, and it makes sense to keep the code base intact. My question is - what would be the preferred way to do this? If I for instance have a class (MyClass) that is different in some versions (MyClassDifferent), and that class is referenced at a couple of places. I would like for that reference to change depending on what version of the application I am compiling, rather than having to split all the classes referring to MyClassDifferent too. Preprocessor macros would be nice, but they bloat the code and afaik there are only proof of concept implementations available? I am considering something like a factory-pattern, coupled with a configuration file for each application. Does anyone have any tips or pointers?
Look up the AbstractFactory design pattern, "Dependency Injection", and "Inversion of Control". Martin Fowler writes about these [here](http://www.martinfowler.com/articles/injection.html). Briefly, you ship JAR files with all the needed components. For each service point that can be customized, you define an Interface for the service. Then you write one or more implementations of that Interface. To create a service object, you ask an AbstractFactory for it, eg: ``` AbstractFactory factory = new AbstractFactory(); ... ServiceXYZ s = factory.newServiceXYZ(); s.doThis(); s.doThat(); ``` Inside your AbstractFactory you construct the appropriate ServiceXYZ object using the Java reflection method Class.classForName(), and SomeClassObject.newInstance(). (Doing it this way means you don't have to have the ServiceXYZ class in the jar files unless it makes sense. You can also build the objects normally.) The actual class names are read in from a properties file unique to each site. You can roll your own solution easily enough, or use a framework like [Spring](http://www.springsource.org/), [Guice](http://code.google.com/p/google-guice/), or [Pico](http://www.picocontainer.org/).
You are on the right track: Factory patterns, configuration etc. You could also put the system specific features in separate jar files and then you would only need to include the appropriate jar alongside your core jar file.
Java - keeping multi-version application from splitting codebase
[ "", "java", "preprocessor", "multiple-versions", "" ]
Is there an existing Java library which provides a method to strip all HTML tags from a String? I'm looking for something equivalent to the `strip_tags` function in PHP. I know that I can use a regex as described in [this Stackoverflow question](https://stackoverflow.com/questions/44078/strip-all-html-tags-except-links), however I was curious if there may already be a `stripTags()` method floating around somewhere in the Apache Commons library that can be used.
Use [JSoup](http://jsoup.org/), it's well documented, available on Maven and after a day of spending time with several libraries, for me, it is the best one i can imagine.. My own opinion is, that a job like that, parsing html into plain-text, should be possible in one line of code -> otherwise the library has failed somehow... just saying ^^ So here it is, the one-liner of JSoup - in Markdown4J, something like that is not possible, in Markdownj too, in htmlCleaner this is pain in the ass with somewhat about 50 lines of code... ``` String plain = new HtmlToPlainText().getPlainText(Jsoup.parse(html)); ``` And what you got is real plain-text (not just the html-source-code as a String, like in other libs lol) -> he really does a great job on that. It is more or less the same quality as Markdownify for PHP....
Whatever you do, make sure you normalize the data before you start trying to strip tags. I recently attended a web app security workshop that covered XSS filter evasion. One would normally think that searching for `<` or `&lt;` or its hex equivalent would be sufficient. I was blown away after seeing a slide with 70 ways that `<` can be encoded to beat filters. **Update:** Below is the presentation I was referring to, see slide 26 for the 70 ways to encode `<`. [Filter Evasion: Houdini on the Wire](http://www.slideshare.net/rob.ragan/filter-evasion-houdini-on-the-wire)
Stripping HTML tags in Java
[ "", "java", "html", "" ]
Consider the situation below. Two tables (A & B), in two environments (DEV & TEST), with records in those tables. If you look the content of the tables, you understand that functionnal data are identical. I mean except the PK and FK values, the name Roger is sill connected to Fruit & Vegetable. ## In DEV environment : **Table A** 1 Roger 2 Kevin **Table B** (italic field is FK to table A) 1 *1* Fruit 2 *1* Vegetable 3 *2* Meat ## In TEST environment : **Table A** 4 Roger 5 Kevin **Table B** (italic field is FK to table A) 7 *4* Fruit 8 *4* Vegetable 9 *5* Meat I'm looking for a SQL Data Compare tool which will tell me there is no difference in the above case. Or if there is, it will generate insert & update scripts with the right order (insert first in A then B)
I found this on Red Gate : <http://www.red-gate.com/messageboard/viewtopic.php?t=8401#top> I contacted them and they told me this feature will be implemented in the next version of Data Compare.
Also you can try [dbForge Data Compare](http://www.devart.com/dbforge/) from Devart. It allows you to compare data and set that consequence of actions that you need. Check out it's perfomance and simplicity.
Advanced SQL Data Compare throught multiple tables
[ "", "sql", "synchronization", "comparison", "" ]
I've always wanted to create custom components in Java, or customize existing ones, but my searches never resulted in anything useful. So I decided to ask the StackOverflow community: **Where can I find information about customizing Java GUI Components in general?** And when I mean customizing, I'm not talking about changing colors, fonts etc. I mean **really** customize them. Here are two mockup example components: ![Custom Components Mockup](https://i.stack.imgur.com/t36RA.jpg) **Notes** I started this question mainly to find how to create the above two custom components. But then I realized that there isn't a general question about hacking swing components. So I thought it would be better to have a list of resources. In case you are wondering how do the two components in the mockup work, here it is: A customized JScrollPane that has two Scrollbars for each orientation. Each scrollbar can act differently. For example, the outer ones scroll normally and the inner ones move the view in a more [Picasa](http://picasa.google.com/)-like way. I actually got a working(!) answer from google groups [here](http://groups.google.com/group/comp.lang.java.programmer/browse_thread/thread/7a3c3558d7924661/11e7beb95c003575?#11e7beb95c003575), but that was just code. The second one is a custom JComboBox which, when the popup list is expanded, has a JComponent at the end. This can be anything, from a simple JLabel with an icon, to a JButton that manipulates the list in a way. But this question isn't about those specific components. It's about **finding resources (websites, books, articles etc.) to learn how to create them**.
This article, [How To Write a Custom Swing Component](https://web.archive.org/web/20131027161222/http://today.java.net/pub/a/today/2007/02/22/how-to-write-custom-swing-component.html) should be really helpful. It covers replicating a Windows slider control that has both discrete steps and a continuous range.
The JDK is open source. To understand how you write a Swing component, there is no better place to look than the source for Swing components. In general, when you create custom components, you are interested in one or more of the following: {interaction semantics, visual representation, compositional structure} Start with the simplest cases: Passive components: `JLabel` Interactive components: `JButton` `JLabel` will demonstrate the barebones extension of `JComponent` for custom drawing of a component; in this case, it is drawing the 'text' string value as its representation. `JButton` will demonstrate the barebones extension for user interaction in addition to drawing the component.
How to create a custom Swing Component
[ "", "java", "swing", "jcomponent", "" ]
I asked [this question](https://stackoverflow.com/questions/912469/is-the-following-code-using-stdset-legal) earlier. I am intrigued by std::set but I have another confusing scenario. Namely, is the following code legal, portable c++ for T=std::vector and T=std::set: ``` template <typename T> void remove_elements(T& collection, int removal_value) { typename T::iterator new_end = std::remove(collection.begin(), collection.end(), removal_value); collection.erase(new_end, collection.end()); } ``` According to the SGI reference, set::iterator and set::const\_iterator are the same, so I don't know if this is legit. However, I can't seem to find another way to get the operation I need to work regardless of type. I could resort to template specialization, however it would be nice not to have to specialize in the first place.
erase-remove idiom works only for sequence containers. For the standard associative containers it will not work and the solution is not so straightforward. Two approaches : 1. Use `remove_copy_if` to copy all the values into another temporary container and then swap the contents of the original container with those of temporary one. [Refer my [answer](https://stackoverflow.com/questions/800955/removeif-equivalent-for-stdmap/907606#907606) to related Q] 2. The other one would be loop to walk the container elements and post increment the iterator when you pass it to erase. Refer this Q for more details: [remove\_if equivalent for std::map](https://stackoverflow.com/questions/800955/removeif-equivalent-for-stdmap/907606#907606) Also, refer Item 9. Choose carefully among erasing options from Effective STL by Scott Meyers.
No, it won't work for `std::set`, because one of the requirements of `std::remove()` is that the iterator be a mutable iterator, and `std::set`'s iterators are not mutable. I don't have any good alternatives to suggest, unfortunately. One thing you could do is maybe use `std::find()` to find an iterator to an occurrence of the element, and then use the `.erase()` method on the iterator (which is present in both `std::vector` and `std::set`) to erase it; and keep doing it until there are no more such elements. But this might be very inefficient, O(n^2) instead of O(n).
Further std::set woes
[ "", "c++", "templates", "stl", "set", "" ]
Hey everyone, I'm back and looking forward to more of your brilliance. I have two tables: 1. newsletters — each row contains a 'id', 'subject', 'body' & 'from' headers for an email 2. newsletter\_queue — each row contains an 'id', 'email' address, 'date' added to queue and the 'newsletterid' My goal is to develop a MySQL query that can pull x amount of rows from 'newsletter\_queue', then group them by their 'newsletterid' while using GROUP\_CONCAT (or whatever works) to put all the emails into a character separated string which I will parse with PHP. The reason I'd like to have them together is because the mailer library I am using (swiftmailer) accepts an array with emails for batch emails. Also, if possible, it would be very neat to join the two tables together, thereby avoiding a second query. Here's what I have so far: ``` SELECT GROUP_CONCAT(email ORDER BY date ASC SEPARATOR '|'), newsletterid, date FROM newsletter_queue WHERE status='0' GROUP BY newsletterid LIMIT 125 ``` My problem is that the LIMIT 125 is being applied to the already concatenated rows, rendering it useless due to the fact that I'm trying to limit the amount of total emails being sent at a time, not unique newsletters. If anyone could guide me in the right direction, I would be very appreciative. If you wind up writing the example, that's great too.
``` SELECT GROUP_CONCAT(email ORDER BY date ASC SEPARATOR '|'), newsletterid, date FROM (SELECT email, newsletterid, date FROM newsletter_queue WHERE status="0" ORDER BY date ASC LIMIT 125) as Unsent GROUP BY newsletterid ``` This applies the limit to the inner query, before the group by statement is executed. It doesn't matter that the group by statement is in the outer query since a group by will need a temporary table and sort anyway. If you need some kind of ordering of the concatenated result, you can just apply it to the outer query, for instance by applying max or min to date and order by it.
This should also do what you want: ``` SELECT substring_index(GROUP_CONCAT(email ORDER BY date ASC SEPARATOR '|'),'|',125), newsletterid, date FROM newsletter_queue WHERE status='0' GROUP BY newsletterid ```
Complicated MySQL query for newsletter queue
[ "", "php", "mysql", "newsletter", "swiftmailer", "" ]
I'm trying to make it so that no matter how far apart two objects are they'll both remain on screen. I'm using JOGL, but that shouldn't matter as I just need help with the math. This is what I have so far: ``` float distance = (float) ((Math.sqrt((p1.x - p2.x) + (p1.y - p2.y)))); float camx = (float)((p1.x + p2.x) * 0.5); float camy = (float)((p1.y + p2.y) * 0.5); float camz = (float) (distance * 5); ``` What is the math I need so the Z zooms in and out correctly?
``` float distance = (float) ((Math.sqrt(Math.pow((p1.x - p2.x),2.0) + Math.pow((p1.y - p2.y), 2.0)))); float camx = (float)((p1.x + p2.x) * 0.5); float camy = (float)((p1.y + p2.y) * 0.5); float camz = (float) Math.abs(distance); ```
If both objects have z=0, and your screen viewing angle (from the *center* of the screen to an edge) is ax and ay for the horizontal and vertical angles, then: ``` zx = abs((p1.x-p2.x)*0.5)/tan(ax) zy = abs((p1.y-p2.y)*0.5)/tan(ay) ``` and ``` camz = max(zx, zy) ``` Here zx and zy are the distances to get the objects onto the horizontal and vertical dimensions of the screen, and camz is the distance that satisfies both criteria. Also note that ax and ay are in radians (for example, if you assume your screen is 40 deg wide, then ax is 20 deg, or ax =20\*(pi/180)=0.3419 radians). Your values for camx and camy were correct.
3D Camera Zoom and follow physics in java?
[ "", "java", "math", "camera", "physics", "" ]
I have a DLL that is written in C++ and I want to suppress the name mangling for a few exported methods. The methods are global and are not members of any class. Is there a way to achieve this? BTW: I'm using VS2008.
"bradtgmurray" is right, but for Visual C++ compilers, you need to explicitly export your function anyway. But using a .DEF file as proposed by "Serge - appTranslator" is the wrong way to do it. ## What is the universal way to export symbols on Visual C++ ? Using the declspec(dllexport/dllimport) instruction, which works for both C and C++ code, decorated or not (whereas, the .DEF is limited to C unless you want to decorate your code by hand). So, the right way to export undecorated functions in Visual C++ is combining the export "C" idiom, as answered by "bradtgmurray", and the dllimport/dllexport keyword. ## An example ? As an example, I created on Visual C++ an empty DLL project, and wrote two functions, one dubbed CPP because it was decorated, and the other C because it wasn't. The code is: ``` // Exported header #ifdef MY_DLL_EXPORTS #define MY_DLL_API __declspec(dllexport) #else #define MY_DLL_API __declspec(dllimport) #endif // Decorated function export : ?myCppFunction@@YAHF@Z MY_DLL_API int myCppFunction(short v) ; // Undecorated function export : myCFunction extern "C" { MY_DLL_API int myCFunction(short v) ; } ; ``` I guess you already know, but for completeness' sake, the MY\_DLL\_API macro is to be defined in the DLL makefile (i.e. the VCPROJ), but not by DLL users. The C++ code is easy to write, but for completeness' sake, I'll write it below: ``` // Decorated function code MY_DLL_API int myCppFunction(short v) { return 42 * v ; } extern "C" { // Undecorated function code MY_DLL_API int myCFunction(short v) { return 42 * v ; } } ; ```
Surround the function definitions with extern "C" {} ``` extern "C" { void foo() {} } ``` See <http://www.parashift.com/c++-faq-lite/mixing-c-and-cpp.html>
Is there a way to suppress c++ name mangling?
[ "", "c++", "visual-studio", "winapi", "name-mangling", "" ]
Does anyone know how to get a progress bar for an upload in php? I am trying writing code for a photo album uploader. I would like a progress bar to display while the photos are uploading. I am fairly new to php so I dont know everything about it.
This is by far (after hours of googling and trying scripts) the simplest to set up and nicest uploader I've found <https://github.com/FineUploader/fine-uploader> It doesn't require APC or any other external PHP libraries, I can get file progress feedback on a shared host, and it claims to support html5 drag and drop (personally untested) and multiple file uploads.
I'm sorry to say that to the best of my knowledge a pure PHP upload progress bar, or even a PHP/Javascript upload progress bar is not possible because of how PHP works. Your best bet is to use some form of Flash uploader. AFAIK This is because your script is not executed until all the superglobals are populated, which includes $\_FILES. By the time your PHP script gets called, the file is fully uploaded. EDIT: This is no longer true. It was in 2010.
Upload Progress Bar in PHP
[ "", "php", "upload", "progress-bar", "" ]
I've got this MFC application I'm working on that needs to have an embedded database. So I went hunting for a slick, fast "embeddable" database for it and stumbled accross SQLite. I created a DB with it, and I created a static library project with Visual Studio 2008. the library project will be used in another main project. In the library project, I created a class `DBClass` with a method `AddFeedToDB(CFeed f)`. The library project uses the `.lib` file from codeproject (`cppsqlite3.lib`). When compiling the static library, no error is detected, but when I try to use the library project file in the main project, I get these type of errors: ``` error LNK2019: unresolved external symbol "public:void __thiscall CppSQLite3DB::close(void)" (?close@CppSQLite3DB@@QAEXXZ referenced in function "public: int __thiscall CTalkingFeedsDB::AddFeedToDB(class CFeed,char const*)" (? AddFeedToDB@CTalkingFeedsDB@@QAEHVCFeed@@PDB@Z ``` What am I missing?
It happened to me more than once that I thought symbol `XXX` (i.e. `?close@CppSQLite3DB@@QAEXXZ`) *was* in the import lib, while the actual symbol was `__impXXX` (i.e. `__imp?close@CppSQLite3DB@@QAEXXZ`). The reason for the linker error is then to be found in the compilation step: the compiler will generate the `?close@CppSQLite3DB@@QAEXXZ` symbol to be imported, where it *should* generate `__imp?close@CppSQLite3DB@@QAEXXZ`. This often means that the function declaration itself didn't have `__declspec( dllimport )`. Which may be caused by some preprocessor symbol not being defined. Or the `__declspec` not being there at all...
I know it is already 2 years since this question... but i run in the same situation here. Added all the header files... added the lib directories.. and keep having this error. So i added manually the lib to the Configuration Properties -> Linker -> Input -> Aditional Dependencies and all works for me.
How can I resolve "error LNK2019: unresolved external symbol"?
[ "", "c++", "visual-c++", "linker", "static-libraries", "" ]
My team's current project involves re-writing retrieval libraries in JavaScript. We are basically looking for a setup which enables us to apply test-driven development methods. So far we plan to use Vim to write the code, no fancy IDE. For generating output we would use Spidermonkey's shell environment. JSLint could serve as a moderate syntax checking tool. The essential question remains: How do you develop JavaScript (browser-independent) programs? If we are already on the right track, then maybe you can supply us with a few tips and tricks.
You can test your code in Spidermonkey or [Rhino](http://www.mozilla.org/rhino/) (an older JS interpreter in Java), but you won't really know which browsers it works in until you test your scripts in them! I agree with the earlier poster, using a browser-independent library like jQuery is probably a good idea. I have not used Spidermonkey, but I know Rhino has a good debugging GUI, allowing the usual: setting breakpoints, watches, and stepping through code.
If you have the chance to rewrite it all, you might consider jQuery. It's essentially browser agnostic. Or at least it requires much less object sniffing than plain javascript.
What would be a good browser-independent JavaScript programming environment?
[ "", "javascript", "debugging", "tdd", "development-environment", "" ]
I have 2 matrices and I need to multiply them and then print the results of each cell. As soon as one cell is ready I need to print it, but for example I need to print the [0][0] cell before cell [2][0] even if the result of [2][0] is ready first. So I need to print it by order. So my idea is to make the printer thread wait until the `multiplyThread` notifies it that the correct cell is ready to be printed and then the `printerThread` will print the cell and go back to waiting and so on.. So I have this thread that does the multiplication: ``` public void run() { int countNumOfActions = 0; // How many multiplications have we done int maxActions = randomize(); // Maximum number of actions allowed for (int i = 0; i < size; i++) { result[rowNum][colNum] = result[rowNum][colNum] + row[i] * col[i]; countNumOfActions++; // Reached the number of allowed actions if (countNumOfActions >= maxActions) { countNumOfActions = 0; maxActions = randomize(); yield(); } } isFinished[rowNum][colNum] = true; notify(); } ``` Thread that prints the result of each cell: ``` public void run() { int j = 0; // Columns counter int i = 0; // Rows counter System.out.println("The result matrix of the multiplication is:"); while (i < creator.getmThreads().length) { synchronized (this) { try { this.wait(); } catch (InterruptedException e1) { } } if (creator.getmThreads()[i][j].getIsFinished()[i][j] == true) { if (j < creator.getmThreads()[i].length) { System.out.print(creator.getResult()[i][j] + " "); j++; } else { System.out.println(); j = 0; i++; System.out.print(creator.getResult()[i][j] + " "); } } } ``` Now it throws me these exceptions: ``` Exception in thread "Thread-9" java.lang.IllegalMonitorStateException at java.lang.Object.notify(Native Method) at multiplyThread.run(multiplyThread.java:49) Exception in thread "Thread-6" Exception in thread "Thread-4" java.lang.IllegalMonitorStateException at java.lang.Object.notify(Native Method) at multiplyThread.run(multiplyThread.java:49) java.lang.IllegalMonitorStateException at java.lang.Object.notify(Native Method) at multiplyThread.run(multiplyThread.java:49) Exception in thread "Thread-5" java.lang.IllegalMonitorStateException at java.lang.Object.notify(Native Method) at multiplyThread.run(multiplyThread.java:49) Exception in thread "Thread-8" java.lang.IllegalMonitorStateException at java.lang.Object.notify(Native Method) at multiplyThread.run(multiplyThread.java:49) Exception in thread "Thread-7" java.lang.IllegalMonitorStateException at java.lang.Object.notify(Native Method) at multiplyThread.run(multiplyThread.java:49) Exception in thread "Thread-11" java.lang.IllegalMonitorStateException at java.lang.Object.notify(Native Method) at multiplyThread.run(multiplyThread.java:49) Exception in thread "Thread-10" java.lang.IllegalMonitorStateException at java.lang.Object.notify(Native Method) at multiplyThread.run(multiplyThread.java:49) Exception in thread "Thread-12" java.lang.IllegalMonitorStateException at java.lang.Object.notify(Native Method) at multiplyThread.run(multiplyThread.java:49) ``` line 49 in `multiplyThread` is the "notify()"..I think I need to use the synchronized differently but I am not sure how. If anyone can help this code to work I will really appreciate it.
To be able to call [notify()](http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Object.html#notify()) you need to synchronize on the same object. ``` synchronized (someObject) { someObject.wait(); } /* different thread / object */ synchronized (someObject) { someObject.notify(); } ```
While using the `wait` and `notify` or `notifyAll` methods in Java the following things must be remembered: 1. Use `notifyAll` instead of `notify` if you expect that more than one thread will be waiting for a lock. 2. [The `wait` and `notify` methods must be called in a synchronized context](http://javarevisited.blogspot.com/2011/05/wait-notify-and-notifyall-in-java.html). See the link for a more detailed explanation. 3. Always call the `wait()` method in a loop because if multiple threads are waiting for a lock and one of them got the lock and reset the condition, then the other threads need to check the condition after they wake up to see whether they need to wait again or can start processing. 4. Use the same object for calling `wait()` and `notify()` method; every object has its own lock so calling `wait()` on object A and `notify()` on object B will not make any sense.
How to use wait and notify in Java without IllegalMonitorStateException?
[ "", "java", "multithreading", "exception", "java-threads", "" ]
Is there a better way to generate HTML email in C# (for sending via System.Net.Mail), than using a Stringbuilder to do the following: ``` string userName = "John Doe"; StringBuilder mailBody = new StringBuilder(); mailBody.AppendFormat("<h1>Heading Here</h1>"); mailBody.AppendFormat("Dear {0}," userName); mailBody.AppendFormat("<br />"); mailBody.AppendFormat("<p>First part of the email body goes here</p>"); ``` and so on, and so forth?
You can use the [MailDefinition class](http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.maildefinition.aspx). This is how you use it: ``` MailDefinition md = new MailDefinition(); md.From = "test@domain.example"; md.IsBodyHtml = true; md.Subject = "Test of MailDefinition"; ListDictionary replacements = new ListDictionary(); replacements.Add("{name}", "Martin"); replacements.Add("{country}", "Denmark"); string body = "<div>Hello {name} You're from {country}.</div>"; MailMessage msg = md.CreateMailMessage("you@anywhere.example", replacements, body, new System.Web.UI.Control()); ``` Also, I've written a blog post on how to [generate HTML e-mail body in C# using templates using the MailDefinition class](http://martinnormark.com/generate-html-e-mail-body-in-c-using-templates).
Use the System.Web.UI.HtmlTextWriter class. ``` StringWriter writer = new StringWriter(); HtmlTextWriter html = new HtmlTextWriter(writer); html.RenderBeginTag(HtmlTextWriterTag.H1); html.WriteEncodedText("Heading Here"); html.RenderEndTag(); html.WriteEncodedText(String.Format("Dear {0}", userName)); html.WriteBreak(); html.RenderBeginTag(HtmlTextWriterTag.P); html.WriteEncodedText("First part of the email body goes here"); html.RenderEndTag(); html.Flush(); string htmlString = writer.ToString(); ``` For extensive HTML that includes the creation of style attributes HtmlTextWriter is probably the best way to go. However it can be a bit clunky to use and some developers like the markup itself to be easily read but perversly HtmlTextWriter's choices with regard indentation is a bit wierd. In this example you can also use XmlTextWriter quite effectively:- ``` writer = new StringWriter(); XmlTextWriter xml = new XmlTextWriter(writer); xml.Formatting = Formatting.Indented; xml.WriteElementString("h1", "Heading Here"); xml.WriteString(String.Format("Dear {0}", userName)); xml.WriteStartElement("br"); xml.WriteEndElement(); xml.WriteElementString("p", "First part of the email body goes here"); xml.Flush(); ```
Generating HTML email body in C#
[ "", "c#", "html", "email", "" ]
When using COM boolean values are to be passed as VARIANT\_BOOL which is declared in wtypes.h as *short*. There are also predefined values for *true* and *false*: ``` #define VARIANT_TRUE ((VARIANT_BOOL)-1) #define VARIANT_FALSE ((VARIANT_BOOL)0) ``` Which is the best way to convert from VARIANT\_BOOL to C++ `bool` type? Obvious variants are: 1. compare with VARIANT\_FALSE 2. simply cast to bool Other ways can be easily invented. Which is the best way to do this - most readable, most standart-compliant, least prone to accidential bugs planting and least prone to issues with porting to 64-bit platforms?
Compare to `VARIANT_FALSE`. There is a lot of buggy code out there that mistakenly passes in the C++ bool `true` value (cast to the integer value 1) to a function expecting `VARIANT_BOOL`. If you compare to `VARIANT_FALSE`, you will still get the correct expected value.
I don't like to have to worry about compatibility between different boolean values, so I will normally write: ``` VARIANT_BOOL vb_bool = VARIANT_FALSE; // ... vb_bool set to something by some other code bool myBool = (vb_bool == VARIANT_TRUE); ``` Are there tinier (as in "will compile to simpler x86 code"), valid ways to do it? Of course. Not worth it. This is guaranteed to work, so I can worry about my business logic.
How to best convert VARIANT_BOOL to C++ bool?
[ "", "c++", "windows", "com", "interop", "boolean", "" ]
I have a class that I've been provided that I really don't want to change, but I do want to extend. I'm a pattern and template newbie experimenting with a Decorator pattern applied to a template class. Template class contains a pointer-to-member (if I understand the semantics correctly) in yet another class. The pointer-to-member is the deserializer of an XML istream. The type 'T' is the type of XML document to be deserialized. ``` template <typename T> class B { public: typedef std::auto_ptr<T> MYFUN( std::istream&, const std::string&, const std::string& ); public: B<T>( MYFUN* p ); private: MYFUN *fptr; std::string aString1; std::string aString2; ``` }; The typedef looks odd to me after reading <http://www.parashift.com/c++-faq-lite/pointers-to-members.html#faq-33.5>, and yet this class seems to work fine as-is. There aren't any additional #defines in the provided header file, so this is a little mysterious to me. Now I try to extend it, as Decorator because I want to do a bit more work on the auto\_ptr object returned by MYFUN: ``` template <typename T> class D : public class B<T> { D( B<T>::MYFUN *fPtr, B<T> *providedBase ); //compiler complaint //Looks like B private: B* base_; }; template <typename T> D<T>::D( B<T>::MYFUN *p, B<T> *base ) //compiler complaint : B<T>::B( p ), base_(providedBase) { } ``` When trying to compile this, I get a syntax complaint at the two lines shown. Error is something like "expected ')' at \*". There is no complaint about MYFUN being undefined. When I re-define the pointer-to-member in D with the same signature as in D, i.e. ``` //change MYFUN to NEWFUN in D) typedef std::auto_ptr<T> MYNEWFUN( std::istream&, const std::string&, const std::string& ); ``` This works. I prefer not to have to do this for every D/Decorator I might make of B. I tried to perform the typedef more globally, but couldn't get the syntax right due to the template parameter being undefined.
The compile error is due to the fact that the compiler can't tell you are talking about a type. Try: ``` D( typename B<T>::MYFUN *fPtr, B<T> *providedBase ); ``` and ``` template <typename T> D<T>::D( typename B<T>::MYFUN *p, B<T> *base ) ``` See: [the templates section of the C++ FAQ Lite](http://www.parashift.com/c++-faq-lite/templates.html#faq-35.18) for more details on why this is necessary, but the summary is that because of the possibility of template specialization, there is no way for the compiler to be sure that `B<T>::MYFUN` is actually referring to a type.
The definition of the MYFUN typedef in B is done with private visibility. D will not be able to access it. If you change it to protected or public, does it then work? ``` template <typename T> class B { protected: typedef std::auto_ptr<T> MYFUN( std::istream&, const std::string&, const std::string& ); ... }; ```
Accessing a template base classes function pointer type
[ "", "c++", "design-patterns", "templates", "pointer-to-member", "" ]
In python 2, it was possible to get debug output from urllib by doing ``` import httplib import urllib httplib.HTTPConnection.debuglevel = 1 response = urllib.urlopen('http://example.com').read() ``` However, in python 3 it looks like this has been moved to ``` http.client.HTTPConnection.set_debuglevel(level) ``` However, I'm using urllib not http.client directly. How can I set it up so that my http request display debugging information in this way? Here's what I"m using so far. What's the best way to proceed if I want to be able to get debug information? ``` #Request Login page cookiejar = http.cookiejar.CookieJar() opener = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cookiejar)) request = urllib.request.Request(options.uri) add_std_headers(request) response = opener.open(request) response_string = response.read().decode("utf8") # ... ```
You were right the first time. You can simply add the line `http.client.HTTPConnection.debuglevel = 1` at the start of your file to turn on HTTP debugging application-wide. `urllib.request` still uses `http.client`. It seems that there's also a way to set the debuglevel for a single handler (by creating `urllib.request.HTTPHandler(debuglevel=1)` and building an opener with that), but on my installation of Python3 (3.0b3) it's not actually implemented. I imagine that's changed in more recent versions!
For those who are seeing this question more recently (since ~May, 2016), while the accepted answer might have been correct at some point, it appears that since Python version 3.5.2 the `http.client.HTTPConnection.debuglevel` is entirely ignored in favor of the `debuglevel` constructor argument for `urllib.request.HTTPHandler`. This is due to [this](https://github.com/python/cpython/commit/9642eedc0a6d90d9502658a6569518741eea9ef3) change that sets the value of `http.client.HTTPConnection.debuglevel` to whatever is set in `urllib.request.HTTPHandler`'s constructor argument `debuglevel`, on [this](https://github.com/python/cpython/blob/v3.5.2/Lib/urllib/request.py#L1224) line A [PR](https://github.com/python/cpython/pull/99353) has been opened to fix this, but in the mean time you can monkey patch the `__init__` methods of `HTTPHandler` and `HTTPSHandler` to respect the global values like so: ``` https_old_init = urllib.request.HTTPSHandler.__init__ def https_new_init(self, debuglevel=None, context=None, check_hostname=None): debuglevel = debuglevel if debuglevel is not None else http.client.HTTPSConnection.debuglevel https_old_init(self, debuglevel, context, check_hostname) urllib.request.HTTPSHandler.__init__ = https_new_init http_old_init = urllib.request.HTTPHandler.__init__ def http_new_init(self, debuglevel=None): debuglevel = debuglevel if debuglevel is not None else http.client.HTTPSConnection.debuglevel http_old_init(self, debuglevel) urllib.request.HTTPHandler.__init__ = http_new_init ``` Note: I don't recommend setting the `debuglevel` in `HTTPHandler`'s as a method argument default value because the default values for method arguments get evaluated at function definition evaluation time, which, for `HTTPHandler`'s constructor, is when the module `urllib.request` is imported.
Turning on debug output for python 3 urllib
[ "", "python", "http", "debugging", "python-3.x", "urllib", "" ]
I have a bunch of Java code which was written using the Hibernate framework, originally destined to have a front end written using JSPs. However, the requirements for the front end have changed, and we've decided that a desktop client (which will be written in .NET) is a better match for our users. I don't really want to waste the code that's already been written - can anybody suggest a good set of tools for writing a document-based web services interface that we will be able to access from .NET? Thanks, Jim
We're developing an application with the exact architecture you describe for a finance application. We reviewed several different options, and have finally landed on using compressed CSV over HTTP. CSV was chosen since the vast majority of data was going to be displayed in a grid on the front end, we had very large result sets >250k rows on a regular basis, and it compresses really really well. We also looked at using: * ICE, but declined on that due to licensing costs and the need to reinvent so much. * Google's protocol buffers via servlets, but declined on that due to lack of C# support (as of last fall). * Compressed XML using WOX, but declined on that due to lock-in to a small thesis project for support and XML being too verbose. The industry supports a couple of different options as well: * SOAP, but that has its own well documented issues. * IIOP, J-Integra has a product called Espresso which will allow you to do RMI from a front end.
If you truly want a document based service interface (rather than an RPC style web service architecture), your best bet is going to be creating a SOAP based web service interface. A quick glance at the Java site shows that the Metro stack might help a bit: [Java Web Services at a Glance](http://java.sun.com/webservices/)
How to connect a Java back end with a .NET front end
[ "", "java", ".net", "web-services", "" ]
I am retrieving a list of files from a web service and displaying them as links. When someone clicks on the link, the file should start downloading. The problem is that no direct access to the file exists. Here is the process to download a file: 1. User clicks on link 2. Server calls web service to retrieve file 3. Browser is loading for as long as it takes to bring the file back from the web service 4. Browser finally offers file to user for download To counter the unfavorable user experience of having to wait for the web service before the download starts, I would like to display a "Loading..." feedback dialog when a link is clicked, and have the dialog go away when the file is ready. I am using jQuery, and have been playing around with adding an iframe to the page to load the file, but the problem I am having is I don't know how to determine that the file is ready. I am looking for tips, not only on the client side to give ample feedback, but perhaps also on the server side (using ASP.Net), just in case I can do something to streamline the process. Thank you. **Update**: To clarify, this is for downloading a file to a user's machine. What I'm specifically looking for is a way to determine when the file is ready for download. So, when step #4 above takes place, I'd like to remove the "Loading..." message.
It sounds like you need to expose a new request URL on your server, whose only job is to reply whether the web-service-retrieval has completed (or if not, how far it has got). Have AJAX poll that service every few seconds, and remove the "Loading..." message when it replied that the file is ready. The client should send the session ID (maybe also a file ID), so that the server knows which file is being asked about. The server side will need to be able to contact the running web-service-retrieval process/thread to ask it how far it got. (If it can't find the thread then presumably it has finished.)
you can use the complete option for $.ajax function in jquery which should get called when the request completes
Showing page load progress with JavaScript
[ "", "asp.net", "javascript", "jquery", "download", "" ]
I've tried updating my application's .config file during installer (**via a .NET Installer Class Action**). But, I can't seem to get ConfigurationManager to list any properties or be able to set anything. I learned of this approach from several stackoverflow posts that pointed me to this guide: <http://raquila.com/software/configure-app-config-application-settings-during-msi-install/> I've investigated the differences between my project and his and noticed that my configuration files are formatted differently. I believe this has to do with the fact that i'm using "Settings" files. Config files formatted in the guide look like: ``` <?xml version="1.0" encoding="utf-8" ?> <configuration> <appSettings> <add key="Param1" value="" /> <add key="Param2" value="" /> <add key="Param3" value="" /> </appSettings> </configuration> ``` Where mine looks like: ``` <?xml version="1.0" encoding="utf-8" ?> <configuration> <configSections> <sectionGroup name="userSettings" type="System.Configuration.UserSettingsGroup, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" > <section name="MyAppName.Properties.Settings" type="System.Configuration.ClientSettingsSection, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" allowExeDefinition="MachineToLocalUser" requirePermission="false" /> <section name="MyAppName.Settings1" type="System.Configuration.ClientSettingsSection, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" allowExeDefinition="MachineToLocalUser" requirePermission="false" /> </sectionGroup> <sectionGroup name="applicationSettings" type="System.Configuration.ApplicationSettingsGroup, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" > <section name="MyAppName.Settings1" type="System.Configuration.ClientSettingsSection, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" /> </sectionGroup> </configSections> <userSettings> <MyAppName.Properties.Settings> <setting name="TESTSETTING" serializeAs="String"> <value>asdfasdfasdf</value> </setting> </MyAppName.Properties.Settings> <MyAppName.Settings1> <setting name="VerboseErrorMode" serializeAs="String"> <value>False</value> </setting> <applicationSettings> <MyAppName.Settings1> <setting name="RunOnStartup" serializeAs="String"> <value>True</value> </setting> </MyAppName.Settings1> </applicationSettings> </configuration> ``` To shed some light on what was going on... I tried printing out the list of settings like so: ``` Configuration config = ConfigurationManager.OpenExeConfiguration(exePath); // Try getting the Settings1 Section AppSettingsSection appSettings = (AppSettingsSection)config.GetSection("Settings1"); // Also tried myNamespace.Settings1 if (appSettings != null) { valList = "Settings1: "; foreach (string key in appSettings.Settings.AllKeys) { string value = appSettings.Settings[key].Value; valList += ("Key: '" + key + "' = '" + value + "'\n"); } } else { valList = "appSettings was null"; } MessageBox.Show(valList); MessageBox.Show(valList); ``` I have tried several permutations of this... and in all cases output is "appSettings was null". I also tried initializing the configuration manager in several different ways... ``` Configuration config = ConfigurationManager.OpenExeConfiguration(exePath); MessageBox.Show("Section Count: " + config.Sections.Count); MessageBox.Show("Has File: " + config.HasFile); MessageBox.Show("Namespace Declared: " + config.NamespaceDeclared); config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); MessageBox.Show("Section Count: " + config.Sections.Count); MessageBox.Show("Has File: " + config.HasFile); MessageBox.Show("Namespace Declared: " + config.NamespaceDeclared); ``` For each of them the section count returned was 20. (I have no idea where the 20 comes from... I would have expected it to be 3). HasFile was true for the first case and false for the second. Namespace Declared was false in both cases. Thanks! **EDIT (6-18-09):** Still looking into this question. Anyone else have any ideas? Thanks. Search Keywords: "Object Reference Not Set to not set to an instance" <-- this occurs when trying to write to a property.
I came across the same problem, after deep investigation, I found out the easiest way to update any part of config files (e.g. app.config), that's by using XPath. We have an application which connects to web service, during the installation, the user enters the URL of the web service and this should be saved in the following app.config file: ``` <?xml version="1.0"?> <configuration> <configSections> <sectionGroup name="applicationSettings" type="System.Configuration.ApplicationSettingsGroup, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"> <section name="ApplicationServer.Properties.Settings" type="System.Configuration.ClientSettingsSection, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" /> </sectionGroup> </configSections> <applicationSettings> <ApplicationServer.Properties.Settings> <setting name="ApplicationServer_ApplicationServerUrl" serializeAs="String"> <value>whatever comes from setup should go here</value> </setting> </ApplicationServer.Properties.Settings> </applicationSettings> </configuration> ``` Here is the code to do this in the installer class: ``` public override void Install(System.Collections.IDictionary stateSaver) { base.Install(stateSaver); string targetDirectory = Context.Parameters["targetdir"]; string param1 = Context.Parameters["param1"]; string path = System.IO.Path.Combine(targetDirectory, "app.config"); System.Xml.XmlDocument xDoc = new System.Xml.XmlDocument(); xDoc.Load(path); System.Xml.XmlNode node = xDoc.SelectSingleNode("/configuration/applicationSettings/Intellisense.ApplicationServer.Properties.Settings/setting[@name='ApplicationServer_ApplicationServerUrl']/value"); node.InnerText = (param1.EndsWith("/") ? param1 : param1 + "/"); xDoc.Save(path); // saves the web.config file } ``` Basically, since the config file is a XML based document, I am using XPath expression to locate specific node and change its value.
One thing to try is moving it from install to Commit to ensure that the file has been written first before trying to access it. Alternatively you could use the custom action to write your own file and just alter your config file to point at the alternative xml file. I worked on a Sharepoint product install where I dug into all of this and I will admit it is very tedious to get working correctly. I was creating config and batch files on the fly based on install parameters.
Updating <appname>.config file from an Custom Installer Class Action
[ "", "c#", ".net", "windows-installer", "" ]
Is there is a difference between `size_t` and `container::size_type`? What I understand is `size_t` is more generic and can be used for any `size_type`s. But is `container::size_type` optimized for specific kinds of containers?
The standard containers define `size_type` as a typedef to `Allocator::size_type` (Allocator is a template parameter), which for `std::allocator<T>::size_type` is **typically** defined to be `size_t` (or a compatible type). So for the standard case, they are the same. However, if you use a custom allocator a different underlying type could be used. So `container::size_type` is preferable for maximum generality.
* `size_t` is defined as the type used for the size of an object and is **platform dependent**. * `container::size_type` is the type that is used for the number of elements in the container and is **container dependent**. All `std` containers use `size_t` as the `size_type`, but each independent library vendor chooses a type that it finds appropriate for its container. If you look at [qt](/questions/tagged/qt "show questions tagged 'qt'"), you'll find that the `size_type` of Qt containers is version dependent. In Qt3 it was `unsigned int` and in Qt4 it was changed to `int`.
'size_t' vs 'container::size_type'
[ "", "c++", "size-type", "container-data-type", "" ]
What is the typical underlying data structure used to implement Python's built-in list data type?
> List objects are implemented as > arrays. They are optimized for fast > fixed-length operations and incur O(n) > memory movement costs for pop(0) and > insert(0, v) operations which change > both the size and position of the > underlying data representation. See also: <http://docs.python.org/library/collections.html#collections.deque> Btw, I find it interesting that the Python tutorial on data structures recommends using pop(0) to simulate a queue but does not mention O(n) or the deque option. <http://docs.python.org/tutorial/datastructures.html#using-lists-as-queues>
CPython: ``` typedef struct { PyObject_VAR_HEAD /* Vector of pointers to list elements. list[0] is ob_item[0], etc. */ PyObject **ob_item; /* ob_item contains space for 'allocated' elements. The number * currently in use is ob_size. * Invariants: * 0 <= ob_size <= allocated * len(list) == ob_size * ob_item == NULL implies ob_size == allocated == 0 * list.sort() temporarily sets allocated to -1 to detect mutations. * * Items must normally not be NULL, except during construction when * the list is not yet visible outside the function that builds it. */ Py_ssize_t allocated; } PyListObject; ``` As can be seen on the following line, the list is declared as an array of pointers to `PyObjects`. ``` PyObject **ob_item; ```
What is the underlying data structure for Python lists?
[ "", "python", "list", "data-structures", "" ]
So I am a new programmer and I just installed XCode on my Macbook to get the GCC. I think Xcode is the only way for getting GCC on OSX. Now when I run my Hello World application, in C++, g++ comes up saying it is version 4.0.1 but when I look for commands starting with g I also see g++-4.2. Is there any way of making 4.2 default rather than 4.0.1, and also is there a way to updating gcc to the latest version 4.4.0? EDIT: Ok, so I installed macports and installed gcc4.4 and it shows up on terminal as gcc-mp-4.4 and how do I make it default with gcc\_select, like what are the commands and stuff. Thanks.
If you install macports you can install gcc select, and then choose your gcc version. ``` /opt/local/bin/port install gcc_select ``` To see your versions use ``` port select --list gcc ``` To select a version use ``` sudo port select --set gcc gcc40 ```
I know it is an old request. But it might still be useful to some. With current versions of MacPorts, you can choose the default gcc version using the port command. To list the available versions of gcc, use: > $ sudo port select --list gcc > > ``` > Available versions for gcc: > gcc42 > llvm-gcc42 > mp-gcc46 > none (active) > ``` To set gcc to the MacPorts version: > $ sudo port select --set gcc mp-gcc46
Update GCC on OSX
[ "", "c++", "macos", "gcc", "compiler-construction", "g++", "" ]