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 JavaScript snippet that runs very well on Firefox and Safari, but refuses to run on IE: ``` var drop= function(id) { if(document.getElementById("select1").value == "Ficha de pediatria"){ top.location.href = "print.jsp?id="+id+"&type=2"; } else if(document.getElementById("select1").value == "Ficha normal"){ top.location.href = "print.jsp?id="+id+"&type=1"; } } <select id="select1" name="select1" onChange="drop(id);return false;"> <option>Imprimir:</option> <option>Ficha de pediatria</option> <option>Ficha normal</option> </select> ``` I trimed this as it had more JSP code but it' remained the same. Anyone got any idea why it's not running on IE?
[EDIT] Sorry. I introduced an error with my first post by not carefully looking at how you are constructing your url. I shouldn't have removed the `id` parameter. I've updated the code and it should work now. Try this instead: ``` function drop(ctl,id) { var value = ctl.options[ctl.selectedIndex].value; if(value == "Ficha de pediatria"){ window.top.location.href = "print.jsp?id="+id+"&type=2"; } else if (value == "Ficha normal"){ window.top.location.href = "print.jsp?id="+id+"&type=1"; } } <select id="select1" name="select1" onChange="drop(this,id);return false;"> <option>Imprimir:</option> <option>Ficha de pediatria</option> <option>Ficha normal</option> </select> ``` [EDIT] A bit of explanation... I think the issue is how it is accessing the DOM. I don't think that IE has a value property on a select. I think you have to get at it via the selected option. Also, I'm not sure that there is a top property in the global namespace, but you should be able to get at it via `window.top` to set the location. Finally, I made a slight improvement in that by specifying `this` as the argument, you can skip the element lookup and reference it directly from the control passed as the argument.
IE doesn't like the way you're grabbing the value of the select ``` document.getElementById("select1").value ``` This is saying "give me the text that's in the value attribute of the selected option in the select element with the id *select1*. Your options don't have any values. When Firefox and Safari encounter this ambiguity, they return the text of the selected option. When Internet Explorer encounters this ambiguity, it returns a blank string. Your javascript would work as is if you did something like ``` <select id="select1" name="select1" onChange="drop(this,id);return false;"> <option value="Imprimir:">Imprimir:</option> <option value="Ficha de pediatria">Ficha de pediatria</option> <option value="Ficha normal">Ficha normal</option> </select> ``` If that's not possible, you'll want to grab the *text* of the option that's selected. ``` var theSelect = document.getElementById("select1"); var theValue = theSelect.options[theSelect.selectedIndex].text ``` Finally, while not your direct question, a the hard coded *select1* isn't the best way to get at the select list. Consider using the this keyword ``` function foo(theSelect){ alert(theSelect.options); } ``` ... ``` <select id="whatever" onchange="foo(this);"> ... </select> ``` This is a bit more generic, and you'll be able to use your function on a select with any ID.
Javascript not running on IE
[ "", "javascript", "internet-explorer", "" ]
Can someone explain how exactly prepared connection pooling using dbcp can be used? (with some example code if possible). I've figured out how to turn it on - passing a KeyedObjectPoolFactory to the PoolableConnectionFactory. But how should the specific prepared statements be defined after that? Right now I'm only using a PoolingDataSource to get connections from the pool. How do I use the prepared statements from the pool?
Well talking about getting connection from the pool vs getting "not-pooled" connection, do you have any change in your code :)? I bet you do not. Same way with prepared statements. Your code should not change. So, there is no useful code example to this. You should read docs for your JDBC Datasource implementation and see what developers have to say about pooling. There is no other source of reliable info on this. From [here](http://commons.apache.org/dbcp/configuration.html): This component has also the ability to pool PreparedStatements. When enabled a statement pool will be created for each Connection and PreparedStatements created by one of the following methods will be pooled: ``` * public PreparedStatement prepareStatement(String sql) * public PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency) ``` So, you just keep using prepareStatement() call and your dbcp will in theory take care of pooling (i.e. if you are trying to create "select \* from users u where u.name like :id", it will try to find this statement in the pool first)
Here's basic code I use. ``` GenericObjectPool connectionPool = new GenericObjectPool(null); connectionPool.setMinEvictableIdleTimeMillis(1000 * 60 * 30); connectionPool.setTimeBetweenEvictionRunsMillis(1000 * 60 * 30); connectionPool.setNumTestsPerEvictionRun(3); connectionPool.setTestOnBorrow(true); connectionPool.setTestWhileIdle(false); connectionPool.setTestOnReturn(false); props = new Properties(); props.put("user", username); props.put("password", password); ConnectionFactory connectionFactory = new DriverManagerConnectionFactory(url, props); PoolableConnectionFactory poolableConnectionFactory = new PoolableConnectionFactory(connectionFactory, connectionPool, null, "SELECT 1", false, true); PoolingDataSource dataSource = new PoolingDataSource(connectionPool); ```
Using PreparedStatement pooling in dbcp
[ "", "java", "prepared-statement", "connection-pooling", "apache-commons-dbcp", "" ]
Say for example I have the following string: var testString = "Hello, world"; And I want to call the following methods: var newString = testString.Replace("Hello", "").Replace("world", ""); Is there some code construct that simplifies this, so that I only have to specify the Replace method once, and can specify a bunch of parameters to pass to it in one go?
Create a function to which you pass the `String` and a `Dictionary(String, String)`. Iterate over each item in the Dictionary and `InputString.Replace(DictionaryEntry.Key, DictionaryEntry.Value)`. Return the string with the replaced values. But I'd just do `.Replace.Replace` if it's only 2 times...
Another option to make this more readable is to add new lines and proper indentation (which would be the better option to me): ``` var newString = testString.Replace("Hello", "") .Replace("world", "") .Replace("and", "") .Replace("something", "") .Replace("else",""); ```
Is there a sweet, efficient way to call the same method twice with two different arguments?
[ "", "c#", "arrays", "parameters", "methods", "call", "" ]
I'm trying to reorder/group a set of results using SQL. I have a few fields (which for the example have been renamed to something a bit less specific), and each logical group of records has a field which remains constant - the address field. There are also fields which are present for each address, these are the same for every address. ``` id forename surname address 1 John These Address1 2 Lucy Values Address1 3 Jenny Are Address1 4 John All Address2 5 Lucy Totally Address2 6 Jenny Different Address2 7 Steve And Address2 8 Richard Blah Address2 address John Lucy Jenny Steve Richard Address1 These Values Are (null) (null) Address2 All Totally Different And Blah ``` For example: John,Lucy,Jenny,Steve and Richard are the only possible names at each address. I know this because it's stored in another location. Can I select values from the actual records in the left hand image, and return them as a result set like the one on the right? I'm using MySQL if that makes a difference.
Assuming that the column headings "john", "lucy" etc are fixed, you can group by the address field and use if() functions combined with aggregate operators to get your results: ``` select max(if(forename='john',surname,null)) as john, max(if(forename='lucy',surname,null)) as lucy, max(if(forename='jenny',surname,null)) as jenny, max(if(forename='steve',surname,null)) as steve, max(if(forename='richard',surname,null)) as richard, address from tablename group by address; ``` It is a bit brittle though. There is also the group\_concat function that can be used (within limits) to do something similar, but it will be ordered row-wise rather than column-wise as you appear to require. eg. ``` select address, group_concat( concat( forename, surname ) ) tenants from tablename group by address; ```
I'm not certain, but I think what you're trying to do is GROUP BY. ``` SELECT Address,Name FROM Table GROUP BY Name ``` if you want to select more columns, make sure they're included in the GROUP BY clause. Also, you can now do aggregate functions, like MAX() or COUNT().
Remapping/Concatenating in SQL
[ "", "sql", "mysql", "concatenation", "" ]
It's a simple case of a javascript that continuously asks "are there yet?" Like a four year old on a car drive.. But, much like parents, if you do this too often or, with too many kids at once, the server will buckle under pressure.. How do you solve the issue of having a webpage that looks for new content in the order of every 5 seconds and that allows for a larger number of visitors?
stackoverflow does it some way, don't know how though. The more standard way would indeed be the javascript that looks for new content every few seconds. A more advanced way would use a [push-like](http://en.wikipedia.org/wiki/Push_technology) technique, by using [Comet](http://en.wikipedia.org/wiki/Comet_(programming)) techniques (long-polling and such). There's a lot of interesting stuff under that link. I'm still waiting for a good opportunity to use it myself... Oh, and here's a link from stackoverflow about it: [Is there some way to PUSH data from web server to browser?](https://stackoverflow.com/questions/19995/is-there-some-way-to-push-data-from-web-server-to-browser)
In Java I used Ajax library (DWR) using Comet technology - I think you should search for library in PHP using it. The idea is that server is sending one very long Http response and when it has something to send to the client it ends it and send new response with updated data. Using it client doens't have to ping server every x seconds to get new data - I think it could help you.
Ajax "Is there new content? If so, update page" - How to do this without breaking the server?
[ "", "javascript", "mysql", "ajax", "comet", "" ]
I'm working on a Spring MVC project, and I have unit tests for all of the various components in the source tree. For example, if I have a controller `HomeController`, which needs to have a `LoginService` injected into it, then in my unit test `HomeControllerTest` I simply instantiate the object as normal (outside of Spring) and inject the property: ``` protected void setUp() throws Exception { super.setUp(); //... controller = new HomeController(); controller.setLoginService( new SimpleLoginService() ); //... } ``` This works great for testing each component as an isolated unit - except now that I have a few dozen classes in the project, after writing a class and writing a successful unit test for it, I keep forgetting to update my Spring MVC context file that does the actual wiring-up in the deployed application. I find out that I forgot to update the context file when I deploy the project to Tomcat and find a bunch of NullPointers from non-wired-up beans. So, here are my questions: 1. This is my first Spring project - is it normal to create unit tests for the individual beans, as I have done, and then create a second suite of tests (integration tests) to test that everything works as expected with the actual application context? Is there an established best practice for this? 2. In addition, how do you separate the unit tests from the integration tests? I have all of the source code in `src`, the unit tests in `test` - should there be a 2nd test folder (such as `test-integration`) for integration test cases? Since this is my first Spring project, I'm curious how others usually go about doing this sort of thing - and rather than re-invent the wheel I rather ask the rest of the community.
I can't speak to being a best practice, but here's what I've done in the past. **Unit tests:** * Create unit tests for non-trivial beans (ie, most of your Spring related beans) * Use Mocks for injected services where practical (ie, most if not all the time). * Use a standard naming convention for these tests in the project `test` directory. Using `Test` or `TestCase` as a prefix or suffix to the classname seems to be widely practiced. **Integration Tests:** * Create an `AbstractIntegrationTestCase` that sets up a `Spring` `WebApplicationContext` for use in intetgration test clases. * Use a naming convention for integration tests in the `test` directory. I've used `IntTest` or `IntegrationTest` as a prefix or suffix for these tests. Set up three Ant `test` targets: 1. test-all (or whatever you want to name it): Run Unit and Integration Tests 2. test: Run Unit tests (just because `test` seems to be the most common usage for unit testing 3. test-integration: run the integration tests. As noted, you can use the naming conventions that make sense for your project. As to separating unit from integration tests into a separate directory, I don't think it matters as long as the developers *and their tools* can find and execute them easily. As an example, the last Java project I worked on with Spring used exactly what is described above, with integration tests and unit tests living in the same `test` directory. Grails projects, on the other hand, explicitly separate unit and integration test directories under a general test directory.
A few isolated points: Yes, it's a common approach to Spring testing - seperate unit tests and integration tests where the former doesn't load any Spring context. For your unit tests, maybe consider mocking to ensure that your tests are focussed on one isolated module. If you're tests are wiring in a ton of dependencies then they aren't really unit tests. They're integration tests where you are wiring of dependencies using new rather than dependency injection. A waste of time and duplicated effort when your production application uses Spring! Basic integration tests to bring up your Spring contexts are useful. The @required annotation may help you to ensure you catch required dependencies in your Spring wiring. Maybe look into Maven which will give you explicit phases to bind your unit and integration tests on to. Maven is quite widely used in the Spring community.
Unit tests vs integration tests with Spring
[ "", "java", "tdd", "junit", "spring-mvc", "integration-testing", "" ]
I'm writing a C++ program that doesn't work (I get a segmentation fault) when I compile it with optimizations (options -O1, -O2, -O3, etc.), but it works just fine when I compile it without optimizations. Is there any chance that the error is in my code? or should I assume that this is a bug in GCC? My GCC version is 3.4.6. Is there any known workaround for this kind of problem? There is a big difference in speed between the optimized and unoptimized version of my program, so I really need to use optimizations. --- This is my original functor. The one that works fine with no levels of optimizations and throws a segmentation fault with any level of optimization: ``` struct distanceToPointSort{ indexedDocument* point ; distanceToPointSort(indexedDocument* p): point(p) {} bool operator() (indexedDocument* p1,indexedDocument* p2){ return distance(point,p1) < distance(point,p2) ; } } ; ``` And this one works flawlessly with any level of optimization: ``` struct distanceToPointSort{ indexedDocument* point ; distanceToPointSort(indexedDocument* p): point(p) {} bool operator() (indexedDocument* p1,indexedDocument* p2){ float d1=distance(point,p1) ; float d2=distance(point,p2) ; std::cout << "" ; //without this line, I get a segmentation fault anyways return d1 < d2 ; } } ; ``` Unfortunately, this problem is hard to reproduce because it happens with some specific values. I get the segmentation fault upon sorting just one out of more than a thousand vectors, so it really depends on the specific combination of values each vector has.
Now that you posted the code fragment and a working workaround was found (@Windows programmer's answer), I can say that perhaps what you are looking for is `-ffloat-store`. > -ffloat-store > > Do not store floating point variables in registers, and inhibit other options that might change whether a floating point value is taken from a register or memory. > > This option prevents undesirable excess precision on machines such as the 68000 where the floating registers (of the 68881) keep more precision than a double is supposed to have. Similarly for the x86 architecture. For most programs, the excess precision does only good, but a few programs rely on the precise definition of IEEE floating point. Use -ffloat-store for such programs, after modifying them to store all pertinent intermediate computations into variables. Source: <http://gcc.gnu.org/onlinedocs/gcc-3.4.6/gcc/Optimize-Options.html>
I would assume your code is wrong first. Though it is hard to tell. Does your code compile with 0 warnings? ``` g++ -Wall -Wextra -pedantic -ansi ```
GCC: program doesn't work with compilation option -O3
[ "", "c++", "gcc", "compilation", "" ]
I use *lazy connection* to connect to my DB within my DB object. This basically means that it doesn't call mysql\_connect() until the first query is handed to it, and it subsequently skips reconnecting from then on after. Now I have a method in my DB class called `disconnectFromDB()` which pretty much calls `mysql_close()` and sets `$_connected = FALSE` (so the `query()` method will know to connect to the DB again). Should this be called after every query (as a private function) or externally via the object... because I was thinking something like (code is an example only) ``` $students = $db->query('SELECT id FROM students'); $teachers = $db->query('SELECT id FROM teachers'); ``` Now if it was closing after every query, would this slow it down a lot as opposed to me just adding this line to the end ``` $db->disconnectFromDB(); ``` Or should I just include that line above at the very end of the page? What advantages/disadvantages do either have? What has worked best in your situation? Is there anything really wrong with forgetting to close the mySQL connection, besides a small loss of performance? Appreciate taking your time to answer. Thank you!
As far as I know, unless you are using persistent connections, your MySQL connection will be closed at the end of the page execution. Therefore, you calling disconnect will add nothing and because you do the lazy connection, may cause a second connection to be created if you or another developer makes a mistake and disconnects at the wrong time. Given that, I would just allow my connection to close automatically for me. Your pages should be executing quickly, therefore holding the connection for that small amount of time shouldn't cause any problems.
I just read this comment on PHP website regarding persistent connection and it might be interesting to know: > Here's a recap of important reasons > NOT to use persistent connections: > > * When you lock a table, normally it is unlocked when the connection > closes, but since persistent > connections do not close, any tables > you accidentally leave locked will > remain locked, and the only way to > unlock them is to wait for the > connection to timeout or kill the > process. The same locking problem > occurs with transactions. (See > comments below on 23-Apr-2002 & > 12-Jul-2003) > * Normally temporary tables are dropped when the connection closes, > but since persistent connections do > not close, temporary tables aren't so > temporary. If you do not explicitly > drop temporary tables when you are > done, that table will already exist > for a new client reusing the same > connection. The same problem occurs > with setting session variables. (See > comments below on 19-Nov-2004 & > 07-Aug-2006) > * If PHP and MySQL are on the same server or local network, the > connection time may be negligible, in > which case there is no advantage to > persistent connections. > * Apache does not work well with persistent connections. When it > receives a request from a new client, > instead of using one of the available > children which already has a > persistent connection open, it tends > to spawn a new child, which must then > open a new database connection. This > causes excess processes which are just > sleeping, wasting resources, and > causing errors when you reach your > maximum connections, plus it defeats > any benefit of persistent connections. > (See comments below on 03-Feb-2004, > and the footnote at > <http://devzone.zend.com/node/view/id/686#fn1>) (I was not the one that wrote the text above)
PHP mySQL - When is the best time to disconnect from the database?
[ "", "php", "mysql", "" ]
What is the accepted practice for indenting SQL statements? How should this example be indented? ``` SELECT column1, column2 FROM table1 WHERE column3 IN ( SELECT TOP(1) column4 FROM table2 INNER JOIN table3 ON table2.column1 = table3.column1 ) ```
``` SELECT column1 , column2 FROM table1 WHERE column3 IN ( SELECT TOP(1) column4 FROM table2 INNER JOIN table3 ON table2.column1 = table3.column1 ) ``` I like to have all **"," in front**, this way I never search them when an error at line X from the SQL editor. --- ### This is an example for those who do not use this type of writting SQL statement. Both contain an error of a missing comma. ``` SELECT sdcolumn123 , dscolumn234 , sdcolumn343 , ffcolumn434 , sdcolumn543 , bvcolumn645 vccolumn754 , cccolumn834 , vvcolumn954 , cvcolumn104 FROM table1 WHERE column3 IN ( ... ) SELECT sdcolumn123, dscolumn234, asdcolumn345, dscolumn456, ascolumn554, gfcolumn645 sdcolumn754, fdcolumn845, sdcolumn954, fdcolumn1054 FROM table1 WHERE column3 IN ( ... ) ``` I found easier and more quick at the first example. Hope this example show you more my point of view.
``` SELECT column1, column2 FROM table WHERE column3 IN ( SELECT TOP(1) column4 FROM table2 INNER JOIN table3 ON table2.column1 = table3.column1 ) ``` This is pretty short and easy to read. I'd make adjustments if there were more columns selected or more join conditions.
SQL Statement indentation good practice
[ "", "sql", "coding-style", "indentation", "" ]
What's the best way to output the public contents of an object to a human-readable file? I'm looking for a way to do this that would not require me to know of all the members of the class, but rather use the compiler to tell me what members exist, and what their names are. There have to be macros or something like that, right? Contrived example: ``` class Container { public: Container::Container() {/*initialize members*/}; int stuff; int otherStuff; }; Container myCollection; ``` I would like to be able to do something to see output along the lines of "myCollection: stuff = value, otherStuff = value". But then if another member is added to Container, ``` class Container { public: Container::Container() {/*initialize members*/}; int stuff; string evenMoreStuff; int otherStuff; }; Container myCollection; ``` This time, the output of this snapshot would be "myCollection: stuff = value, evenMoreStuff=value, otherStuff = value" Is there a macro that would help me accomplish this? Is this even possible? (Also, I can't modify the Container class.) Another note: I'm most interested about a potential macros in VS, but other solutions are welcome too.
Take a look at [this library](http://s11n.net) .
What you're looking for is "[reflection](<http://en.wikipedia.org/wiki/Reflection_(computer_science)#C.2B.2B)>". I found two promising links with a Google search for "C++ reflection": <http://www.garret.ru/cppreflection/docs/reflect.html> <http://seal-reflex.web.cern.ch/seal-reflex/index.html>
Best way to take a snapshot of an object to a file
[ "", "c++", "visual-studio-2005", "file-io", "" ]
I am looking for the highest key value (a defined by the comparison operator) of a std::map. Is this guaranteed to be ``` map.rbegin()->first ``` ? (I am a bit shaky on reverse iterators, and how much freedom there is in the implementation of std::map) If not, please advise. I cannot change the data structure.
Yes. Map is a sorted container, the reverse iterator must return the elements in reverse (i.e. decreasing) order of their keys. [Edit: as Charles Bailey points out in his answer, your code gives the greatest key **if it exists** - i.e. if the map is non-empty]
Yes, but remember to check that `map.rbegin() != map.rend()`.
Last key in a std::map
[ "", "c++", "iterator", "stdmap", "" ]
How do I extract a tar (or tar.gz, or tar.bz2) file in Java?
*Note:* This functionality was later published through a separate project, Apache Commons Compress, as [described in another answer.](https://stackoverflow.com/a/7556307/3474) This answer is out of date. --- I haven't used a tar API directly, but tar and bzip2 are implemented in Ant; you could borrow their implementation, or possibly use Ant to do what you need. [Gzip is part of Java SE](http://java.sun.com/j2se/1.5.0/docs/api/java/util/zip/package-summary.html) (and I'm guessing the Ant implementation follows the same model). `GZIPInputStream` is just an `InputStream` decorator. You can wrap, for example, a `FileInputStream` in a `GZIPInputStream` and use it in the same way you'd use any `InputStream`: ``` InputStream is = new GZIPInputStream(new FileInputStream(file)); ``` (Note that the GZIPInputStream has its own, internal buffer, so wrapping the `FileInputStream` in a `BufferedInputStream` would probably decrease performance.)
You can do this with the Apache Commons Compress library. You can download the 1.2 version from <http://mvnrepository.com/artifact/org.apache.commons/commons-compress/1.2>. Here are two methods: one that unzips a file and another one that untars it. So, for a file <fileName>tar.gz, you need to first unzip it and after that untar it. Please note that the tar archive may contain folders as well, case in which they need to be created on the local filesystem. Enjoy. ``` /** Untar an input file into an output file. * The output file is created in the output folder, having the same name * as the input file, minus the '.tar' extension. * * @param inputFile the input .tar file * @param outputDir the output directory file. * @throws IOException * @throws FileNotFoundException * * @return The {@link List} of {@link File}s with the untared content. * @throws ArchiveException */ private static List<File> unTar(final File inputFile, final File outputDir) throws FileNotFoundException, IOException, ArchiveException { LOG.info(String.format("Untaring %s to dir %s.", inputFile.getAbsolutePath(), outputDir.getAbsolutePath())); final List<File> untaredFiles = new LinkedList<File>(); final InputStream is = new FileInputStream(inputFile); final TarArchiveInputStream debInputStream = (TarArchiveInputStream) new ArchiveStreamFactory().createArchiveInputStream("tar", is); TarArchiveEntry entry = null; while ((entry = (TarArchiveEntry)debInputStream.getNextEntry()) != null) { final File outputFile = new File(outputDir, entry.getName()); if (entry.isDirectory()) { LOG.info(String.format("Attempting to write output directory %s.", outputFile.getAbsolutePath())); if (!outputFile.exists()) { LOG.info(String.format("Attempting to create output directory %s.", outputFile.getAbsolutePath())); if (!outputFile.mkdirs()) { throw new IllegalStateException(String.format("Couldn't create directory %s.", outputFile.getAbsolutePath())); } } } else { LOG.info(String.format("Creating output file %s.", outputFile.getAbsolutePath())); final OutputStream outputFileStream = new FileOutputStream(outputFile); IOUtils.copy(debInputStream, outputFileStream); outputFileStream.close(); } untaredFiles.add(outputFile); } debInputStream.close(); return untaredFiles; } /** * Ungzip an input file into an output file. * <p> * The output file is created in the output folder, having the same name * as the input file, minus the '.gz' extension. * * @param inputFile the input .gz file * @param outputDir the output directory file. * @throws IOException * @throws FileNotFoundException * * @return The {@File} with the ungzipped content. */ private static File unGzip(final File inputFile, final File outputDir) throws FileNotFoundException, IOException { LOG.info(String.format("Ungzipping %s to dir %s.", inputFile.getAbsolutePath(), outputDir.getAbsolutePath())); final File outputFile = new File(outputDir, inputFile.getName().substring(0, inputFile.getName().length() - 3)); final GZIPInputStream in = new GZIPInputStream(new FileInputStream(inputFile)); final FileOutputStream out = new FileOutputStream(outputFile); IOUtils.copy(in, out); in.close(); out.close(); return outputFile; } ```
How do I extract a tar file in Java?
[ "", "java", "archive", "tar", "" ]
I have an app that writes messages to the event log. The source I'm passing in to EventLog.WriteEntry does not exist, so the Framework tries to create the source by adding it to the registry. It works fine if the user is an Admin by I get the following whe the user is not an admin: "System.Security.SecurityException : Requested registry access is not allowed." message. How can I fix that? **Update** I have create the registry with the Admin account manually in the registry. Now, I have the error : System.Security.SecurityException: Requested registry access is not allowed. I do not understand because I have create a user in the Group Administrator... what do I have to do more?
For your update I have found something that might help you : ``` Run regedt32 Navigate to the following key: HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Eventlog\Security Right click on this entry and select Permissions Add the ASPNET user Give it Read permission 2. Change settings in machine.config file Run Explorer Navigate to WINDOWS or WINNT folder Open Microsoft.NET folder Open Framework folder Open v1.1.4322 folder (folder name may be different, depending on what dotnet version is installed) Open CONFIG folder Open machine.config file using notepad (make a backup of this file first) Locate processmodel tag (approx. at line 441) Locate userName="machine" (approx. at line 452) Change it to userName="SYSTEM" Save and close the file Close Explorer 3. Restart IIS Run IISReset ``` [The source is here](http://forums.codecharge.com/posts.php?post_id=67135)
The "non-programming way" is to grant the user that user your web application/web service with access to registry (Event Log are written in the event log).
Event Log SecurityException for Web Application?
[ "", "c#", "events", ".net-2.0", "c#-2.0", "" ]
I am reading log files but not all lines want to be processed straight away. I am using a queue / buffer to store the lines while they wait to be processed. This queue is regularly scanned for particular lines - when they are found, they are removed from the queue (they can be anywhere in it). When there isn't a particular line to be found, lines are taken out of the start of the queue one by one to be processed. Therefore, the queue needs the following: * Able to be resized (or give that impression) * Have elements removed from anywhere * Have elements added (will always be at the end of the queue) * Be scanned quickly * Depending on performance, have a pointer of where it got to on the last scan. I initially wrote the code when I had little experience of Java or the API, and just used an ArrayList because I knew it would work (not necessarily because it was the best option). Its performance is now becoming poor with more and more logs needing to be processed - so, what collection would you recommend to be used in this situation? There's always the possibility of writing my own too. Thanks
LinkedHashSet might be of interest. It is effectively a HashSet but it also maintains a LinkedList to allow a predictable iteration order - and therefore can also be used as a FIFO queue, with the nice added benefit that it can't contain duplicate entries. Because it is a HashSet too, searches (as opposed to scans) can be O(1) if they can match on `equals()`
A LinkedList would probably be most appropriate. It has all the requested properties, and allows links to be removed from the middle in constant time, rather than the linear time required for an ArrayList. If you have some specific strategy for finding the next element to remove, a PriorityQueue or even a sorted set might be more appropriate.
Best Collection To Use?
[ "", "java", "performance", "collections", "queue", "buffer", "" ]
During navigation of the `java.lang.reflect.Method` class I came across the method `isBridge`. Its Javadoc says that it returns true only if the Java spec declares the method as true. Please help me understand what this is used for! Can a custom class declare its method as a bridge if required?
A bridge method may be created by the compiler when extending a parameterized type whose methods have parameterized arguments. You can find in this class [BridgeMethodResolver](https://fisheye.springsource.org/browse/spring-framework/spring-core/src/main/java/org/springframework/core/BridgeMethodResolver.java?r=02a4473c62d8240837bec297f0a1f3cb67ef8a7b) a way to get the actual Method referred by a 'bridge method'. See [Create Frame, Synchronize, Transfer Control](http://java.sun.com/docs/books/jls/third_edition/html/expressions.html#15.12.4.5): As an example of such a situation, consider the declarations: ``` class C<T> { abstract T id(T x); } class D extends C<String> { String id(String x) { return x; } } ``` Now, given an invocation ``` C c = new D(); c.id(new Object()); // fails with a ClassCastException ``` The erasure of the actual method being invoked, `D.id(String)` differs in its signature from that of the compile-time method declaration, `C.id(Object)`. The former takes an argument of type String while the latter takes an argument of type Object. The invocation fails with a ClassCastException before the body of the method is executed. Such situations can only arise if the program gives rise to an unchecked warning ([§5.1.9](http://java.sun.com/docs/books/jls/third_edition/html/conversions.html#190772)). Implementations can enforce these semantics by creating bridge methods. In the above example, the following bridge method would be created in class D: ``` Object id(Object x) { return id((String) x); } ``` This is the method that would actually be invoked by the Java virtual machine in response to the call `c.id(new Object())` shown above, and it will execute the cast and fail, as required. See also **[Bridge](http://books.google.com/books?id=zaoK0%5A2STlkC&pg=PA50&lpg=PA50&dq=java+bridge+%22covariant+return+types%22&source=web&ots=6WoofeXYFM&sig=8bS5Y0sw%5ApBu%5ACuf1EkIR_L4Ddo&hl=en&sa=X&oi=book_result&resnum=4&ct=result#PPA48,M1)**: as mentioned in the comment, bridge methods are also needed for **covariant overriding**: * In Java 1.4, and earlier, one method can override another if the signatures match exactly. * In Java 5, a method can override another if the arguments match exactly *but the return type* of the overriding method, if it is a *subtype* of the return type of the other method. Typically, a method `Object clone()` can be overridden by a `MyObject clone()`, but a bridge method will be generated by the compiler: ``` public bridge Object MyObject.clone(); ```
The example shown there (quoted from the JLS) makes it sound like bridge methods are only used in situations where raw types are used. Since this is not the case, I thought I'd pipe in with an example where bridge methods are used for totally type-correct generic code. Consider the following interface and function: ``` public static interface Function<A,R> { public R apply (A arg); } public static <A, R> R applyFunc (Function<A,R> func, A arg) { return func.apply(arg); } ``` If you use this code in the following way, a bridge method is used: ``` Function<String, String> lower = new Function<String, String>() { public String apply (String arg) { return arg.toLowerCase(); } }; applyFunc(lower, "Hello"); ``` After erasure, the `Function` interface contains the method `apply(Object)Object` (which you can confirm by decompiling the bytecode). Naturally, if you look at the decompiled code for `applyFunc` you'll see that it contains a call to `apply(Object)Object`. `Object` is the upper bound of its type variables, so no other signature would make sense. So when an anonymous class is created with the method `apply(String)String`, it doesn't actually implement the `Function` interface unless a bridge method is created. The bridge method allows all generically typed code to make use of that `Function` implementation. Interestingly, only if the class implemented some *other* interface with the signature `apply(String)String` and only if the method was called via a reference of that interface type would the compiler ever emit a call with that signature. Even if I have the following code: ``` Function<String, String> lower = ...; lower.apply("Hello"); ``` The compiler still emits a call to `apply(Object)Object`. There is actually one other way to get the compiler to call `apply(String)String`, but it takes advantage of the magical type assigned to an anonymous class creation expression which cannot otherwise be written down: ``` new Function<String, String>() { public String apply (String arg) { return arg.toLowerCase(); } }.apply("Hello"); ```
What Method.isBridge used for?
[ "", "java", "api", "reflection", "" ]
``` import sys words = { 1 : 'one', 2 : 'two', 3 : 'three', 4 : 'four', 5 : 'five', 6 : 'six', 7 : 'seven', 8 : 'eight', 9 : 'nine', 10 : 'ten', 11 : 'eleven', 12 : 'twelve', 13 : 'thirteen', 14 : 'fourteen', 15 : 'fifteen', 16 : 'sixteen', 17 : 'seventeen', 18 : 'eighteen', 19 : 'nineteen' } tens = [ '', 'twenty', 'thirty', 'forty', 'fifty', 'sixty', 'seventy', 'eighty', 'ninety', ] placeholders = [ '', 'thousand', 'million', 'billion', 'trillion', 'quadrillion' ] # segMag = segment magnitude (starting at 1) def convertTrio(number): return ' '.join([words[int(number[0])], 'hundred', convertDuo(number[1:3])]) # convertDuo(number[1:3]) def convertDuo(number): #if teens or less if int(number[0]) == 1: return words[int(number)] #twenty-five else: return tens[int(number[0]) - 1] + '-' + words[int(number[1])] if __name__ == "__main__": string = [] numeralSegments = [] numeral = sys.argv[1] if int(numeral) < 100: print convertDuo(numeral) else: # split number into lists, grouped in threes for i in range (0, len(numeral), 3): numeralSegments.append(numeral[i:i+3]) numeralSegments.reverse() # for every segment, convert to trio word and append thousand, million, etc depending on magnitude for i in range (len(numeralSegments)): string.append(convertTrio(numeralSegments[i]) + ' ' + placeholders[i]) # reverse the list of strings before concatenating to commas string.reverse() print ', '.join(string) ``` **Warning**: I'm a total python novice. I'm aware there are probably many times more efficient ways of doing things. I'd appreciate any pointers to them. **Edit**: The code currently only works for numbers whose digit counts are multiples of three. I'd appreciate a suggestion for an elegant way to fix that as well. Thanks.
You can't group digits into "segments" going from left-to-right. The `range(0,len(),3)` is not going to work out well. You'll have to write the same algorithm for inserting digit separators. You start from the right, picking off segments of digits. What's left over (on the left, get it?) will be 1, 2 or 3 digits. You've got convertTrio and convertDuo, which handle 3 and 2 digits, respectively. Somewhere in there is a convert one digit function (can't see it). If it's not homework, then, here's a proper digit clustering algorithm ``` def segment( n ): segList= [] while len(n) > 3: segList.insert( 0, n[-3:] ) n= n[:-3] segList.insert( 0, n ) return segList ``` Edit To be more Pythonic, package this as a tidy, reusable module. The stuff inside the `if __name__ == "__main__"` does two things, which should be separated. Your command-line parsing (anything having to do with `sys.argv` is one thing. The actual "convert a number" function is something else entirely. You want to look more like this. ``` if __name__ == "__main__": import sys for number in sys.argv[1:]: print number2string( number ) ``` Then, your `number2string` function becomes an easily reused piece of this module.
Two improvements come to mind: * 40 is spelled "forty", not "fourty" * your program needs unit tests Have a look at the Python [doctest](http://python.org/doc/2.5/lib/module-doctest.html) and [unittest](http://python.org/doc/2.5/lib/module-unittest.html) modules.
How can I improve this number2words script
[ "", "python", "" ]
Our coding standards ask that we minimise the use of C# var (suggests limiting it's use to being in conjunction with Linq). However there are times when using generics where it's reasonably convenient e.g. ``` Dictionary<DateTime, Dictionary<string, float>> allValues = ... // ... foreach (var dateEntry in allValue) ``` is easier to type ``` foreach (KeyValue<DateTime, Dictionary<string, float>> dateEntry in allValue) ``` (and easier than remembering what the explicit type is in some cases). Do any of the refactoring tools have the ability to convert the former to the latter. I've had a look at Resharper but it doesn't seem to do (indeed it's default suggestion is to go in the opposite direction).
I've got ReSharper 4.1, and it does offer this option (in either direction). Actually, I'd recommend challenging the standard... the former is far more readable than the latter (especially if you call the variable `pair` or something similar). I would't use "var" for `var i = 0`, but it is ideally suited to the above. For bulk changing, go to: * Cleanup Code... (pick a profile => "Edit Profiles" => Tools => Code Cleanup) + C# - Use 'var' in declaration * Replace direction = Can 'var' to type usage * 'foreach' iterator declaration style = Always use explicit type * Local variable declaration style = Always use explicit type and run...
This is possible in Visual Studio 2017. Tools > Options > Text Editor > C# > Code Style > General – Find 'var' preferences > When variable type is apparent. For Preference select "Prefer explicit type," and for Severity select "Suggestion." [![enter image description here](https://i.stack.imgur.com/wdxwh.png)](https://i.stack.imgur.com/wdxwh.png) You'll now get the light bulb actions when you use `var`, and you can quickly change to the explicit type by using the `Ctrl``.` shortcut key. [![enter image description here](https://i.stack.imgur.com/yvBKN.png)](https://i.stack.imgur.com/yvBKN.png) [![enter image description here](https://i.stack.imgur.com/rNInt.png)](https://i.stack.imgur.com/rNInt.png)
Tool to refactor C# var to explicit type
[ "", "c#", "refactoring", "" ]
I'm currently working on some logging code that supposed to - among other things - print information about the calling function. This should be relatively easy, standard C++ has a `type_info` class. This contains the name of the typeid'd class/function/etc. but it's mangled. It's not very useful. I.e. `typeid(std::vector<int>).name()` returns `St6vectorIiSaIiEE`. Is there a way to produce something useful from this? Like `std::vector<int>` for the above example. If it only works for non-template classes, that's fine too. The solution should work for gcc, but it would be better if I could port it. It's for logging so it's not so important that it can't be turned off, but it should be helpful for debugging.
Given the attention this question / answer receives, and the valuable feedback from [GManNickG](https://stackoverflow.com/questions/281818/unmangling-the-result-of-stdtype-infoname/4541470#comment26629807_4541470), I have cleaned up the code a little bit. Two versions are given: one with C++11 features and another one with only C++98 features. In file **type.hpp** ``` #ifndef TYPE_HPP #define TYPE_HPP #include <string> #include <typeinfo> std::string demangle(const char* name); template <class T> std::string type(const T& t) { return demangle(typeid(t).name()); } #endif ``` In file **type.cpp** (requires C++11) ``` #include "type.hpp" #ifdef __GNUG__ #include <cstdlib> #include <memory> #include <cxxabi.h> std::string demangle(const char* name) { int status = -4; // some arbitrary value to eliminate the compiler warning // enable c++11 by passing the flag -std=c++11 to g++ std::unique_ptr<char, void(*)(void*)> res { abi::__cxa_demangle(name, NULL, NULL, &status), std::free }; return (status==0) ? res.get() : name ; } #else // does nothing if not g++ std::string demangle(const char* name) { return name; } #endif ``` Usage: ``` #include <iostream> #include "type.hpp" struct Base { virtual ~Base() {} }; struct Derived : public Base { }; int main() { Base* ptr_base = new Derived(); // Please use smart pointers in YOUR code! std::cout << "Type of ptr_base: " << type(ptr_base) << std::endl; std::cout << "Type of pointee: " << type(*ptr_base) << std::endl; delete ptr_base; } ``` It prints: Type of ptr\_base: `Base*` Type of pointee: `Derived` Tested with g++ 4.7.2, g++ 4.9.0 20140302 (experimental), clang++ 3.4 (trunk 184647), clang 3.5 (trunk 202594) on Linux 64 bit and g++ 4.7.2 (Mingw32, Win32 XP SP2). If you cannot use C++11 features, here is how it can be done in C++98, the file **type.cpp** is now: ``` #include "type.hpp" #ifdef __GNUG__ #include <cstdlib> #include <memory> #include <cxxabi.h> struct handle { char* p; handle(char* ptr) : p(ptr) { } ~handle() { std::free(p); } }; std::string demangle(const char* name) { int status = -4; // some arbitrary value to eliminate the compiler warning handle result( abi::__cxa_demangle(name, NULL, NULL, &status) ); return (status==0) ? result.p : name ; } #else // does nothing if not g++ std::string demangle(const char* name) { return name; } #endif ``` --- --- *(Update from Sep 8, 2013)* [The accepted answer (as of Sep 7, 2013)](https://stackoverflow.com/a/281876/341970), when the call to `abi::__cxa_demangle()` is successful, **returns a pointer to a local, stack allocated array**... ouch! Also note that if you provide a buffer, `abi::__cxa_demangle()` assumes it to be allocated on the heap. Allocating the buffer on the stack is a bug (from the gnu doc): *"If `output_buffer` is not long enough, it is expanded using `realloc`."* **Calling `realloc()` on a pointer to the stack**... ouch! (See also [Igor Skochinsky](https://stackoverflow.com/questions/281818/unmangling-the-result-of-stdtype-infoname#comment16312718_4541470)'s kind comment.) You can easily verify both of these bugs: just reduce the buffer size in the accepted answer (as of Sep 7, 2013) from 1024 to something smaller, for example 16, and give it something with a name *not* longer than 15 (so `realloc()` is *not* called). Still, depending on your system and the compiler optimizations, the output will be: garbage / nothing / program crash. To verify the second bug: set the buffer size to 1 and call it with something whose name is longer than 1 character. When you run it, the program almost assuredly crashes as it attempts to call `realloc()` with a pointer to the stack. --- *(The old answer from Dec 27, 2010)* Important changes made to [KeithB's code](https://stackoverflow.com/a/281876/341970): **the buffer has to be either allocated by malloc or specified as NULL.** Do NOT allocate it on the stack. It's wise to check that status as well. I failed to find `HAVE_CXA_DEMANGLE`. I check `__GNUG__` although that does not guarantee that the code will even compile. Anyone has a better idea? ``` #include <cxxabi.h> const string demangle(const char* name) { int status = -4; char* res = abi::__cxa_demangle(name, NULL, NULL, &status); const char* const demangled_name = (status==0)?res:name; string ret_val(demangled_name); free(res); return ret_val; } ```
Boost core contains a demangler. Checkout [core/demangle.hpp](http://www.boost.org/doc/libs/master/libs/core/doc/html/core/demangle.html#core.demangle.header_boost_core_demangle_hpp): ``` #include <boost/core/demangle.hpp> #include <typeinfo> #include <iostream> template<class T> struct X { }; int main() { char const * name = typeid( X<int> ).name(); std::cout << name << std::endl; // prints 1XIiE std::cout << boost::core::demangle( name ) << std::endl; // prints X<int> } ``` It's basically just a wrapper for `abi::__cxa_demangle`, as has been suggested previously.
Unmangling the result of std::type_info::name
[ "", "c++", "gcc", "name-mangling", "" ]
During development I have to "clear cache" in Firefox all the time in order to make it use the latest version of JavaScript files. Is there some kind of setting (about:config) to turn off caching completely for JavaScript files? Or, if not, for all files?
Enter "about:config" into the Firefox address bar and set: ``` browser.cache.disk.enable = false browser.cache.memory.enable = false ``` If developing locally, or using HTML5's new manifest attribute you may have to also set the following in about:config - ``` browser.cache.offline.enable = false ```
The [Web Developer Toolbar](https://addons.mozilla.org/en-US/firefox/addon/60) has an option to disable caching which makes it very easy to turn it on and off when you need it.
How to turn off caching on Firefox?
[ "", "javascript", "firefox", "caching", "" ]
I am porting an MFC application to .NET WinForms. In the MFC application, you can right click on a menu or on a context menu item and we show another context menu with diagnostic and configuration items. I am trying to port this functionality to .NET, but I am having trouble. I have been able to capture the right click, disable the click of the underlying menu and pop up a context menu at the right location, but the original menu disappears as soon as it loses focus. In MFC, we show the new context menu by calling **TrackPopupMenuEx** with the **TPM\_RECURSE** flag. **ContextMenu** and the newer **ContextMenuStrip** classes in .NET only have a *Show* method. Does anyone know how to do this in .NET? **EDIT** I have tried using **TrackPopupMenuEx** through a p/invoke, but that limits you to using a ContextMenu instead of a ContextMenuStrip which looks out of place in our application. It also still does not work correctly. It doesn't work with the new **MenuStrip** and **ContextMenuStrip**. I have also tried subclassing ToolStripMenuItem to see if I can add a context menu to it. That is working for **MenuStrip**, but **ContextMenuStrip** still allows the right click events to pass through as clicks.
Edit, due to a comment: In: ``` protected override void OnClick(EventArgs e) { if (SecondaryContextMenu == null || MouseButtons != MouseButtons.Right) { base.OnClick(e); } } ``` this part ``` MouseButtons != MouseButtons.Right ``` should and does compile as it is a call to Control.MouseButtons. Since the Form inherits Control class, it is sufficient to call MouseButtons property directly. Hope this helps: ``` public partial class Form1 : Form { class CustomToolStripMenuItem : ToolStripMenuItem { private ContextMenuStrip secondaryContextMenu; public ContextMenuStrip SecondaryContextMenu { get { return secondaryContextMenu; } set { secondaryContextMenu = value; } } public CustomToolStripMenuItem(string text) : base(text) { } protected override void Dispose(bool disposing) { if (disposing) { if (secondaryContextMenu != null) { secondaryContextMenu.Dispose(); secondaryContextMenu = null; } } base.Dispose(disposing); } protected override void OnClick(EventArgs e) { if (SecondaryContextMenu == null || MouseButtons != MouseButtons.Right) { base.OnClick(e); } } } class CustomContextMenuStrip : ContextMenuStrip { private bool secondaryContextMenuActive = false; private ContextMenuStrip lastShownSecondaryContextMenu = null; protected override void Dispose(bool disposing) { if (disposing) { if (lastShownSecondaryContextMenu != null) { lastShownSecondaryContextMenu.Close(); lastShownSecondaryContextMenu = null; } } base.Dispose(disposing); } protected override void OnControlAdded(ControlEventArgs e) { e.Control.MouseClick += new MouseEventHandler(Control_MouseClick); base.OnControlAdded(e); } protected override void OnControlRemoved(ControlEventArgs e) { e.Control.MouseClick -= new MouseEventHandler(Control_MouseClick); base.OnControlRemoved(e); } private void Control_MouseClick(object sender, MouseEventArgs e) { ShowSecondaryContextMenu(e); } protected override void OnMouseClick(MouseEventArgs e) { ShowSecondaryContextMenu(e); base.OnMouseClick(e); } private bool ShowSecondaryContextMenu(MouseEventArgs e) { CustomToolStripMenuItem ctsm = this.GetItemAt(e.Location) as CustomToolStripMenuItem; if (ctsm == null || ctsm.SecondaryContextMenu == null || e.Button != MouseButtons.Right) { return false; } lastShownSecondaryContextMenu = ctsm.SecondaryContextMenu; secondaryContextMenuActive = true; ctsm.SecondaryContextMenu.Closed += new ToolStripDropDownClosedEventHandler(SecondaryContextMenu_Closed); ctsm.SecondaryContextMenu.Show(Cursor.Position); return true; } void SecondaryContextMenu_Closed(object sender, ToolStripDropDownClosedEventArgs e) { ((ContextMenuStrip)sender).Closed -= new ToolStripDropDownClosedEventHandler(SecondaryContextMenu_Closed); lastShownSecondaryContextMenu = null; secondaryContextMenuActive = false; Focus(); } protected override void OnClosing(ToolStripDropDownClosingEventArgs e) { if (secondaryContextMenuActive) { e.Cancel = true; } base.OnClosing(e); } } public Form1() { InitializeComponent(); CustomToolStripMenuItem itemPrimary1 = new CustomToolStripMenuItem("item primary 1"); itemPrimary1.SecondaryContextMenu = new ContextMenuStrip(); itemPrimary1.SecondaryContextMenu.Items.AddRange(new ToolStripMenuItem[] { new ToolStripMenuItem("item primary 1.1"), new ToolStripMenuItem("item primary 1.2"), }); CustomToolStripMenuItem itemPrimary2 = new CustomToolStripMenuItem("item primary 2"); itemPrimary2.DropDownItems.Add("item primary 2, sub 1"); itemPrimary2.DropDownItems.Add("item primary 2, sub 2"); itemPrimary2.SecondaryContextMenu = new ContextMenuStrip(); itemPrimary2.SecondaryContextMenu.Items.AddRange(new ToolStripMenuItem[] { new ToolStripMenuItem("item primary 2.1"), new ToolStripMenuItem("item primary 2.2"), }); CustomContextMenuStrip primaryContextMenu = new CustomContextMenuStrip(); primaryContextMenu.Items.AddRange(new ToolStripItem[]{ itemPrimary1, itemPrimary2 }); this.ContextMenuStrip = primaryContextMenu; } } ```
You'll probably have to p/invoke the method. ``` [DllImport("user32.dll")] static extern bool TrackPopupMenuEx(IntPtr hmenu, uint fuFlags, int x, int y, IntPtr hwnd, IntPtr lptpm); const int TPM_RECURSE = 0x0001; ```
How to show a Context Menu when you right click a Menu Item
[ "", "c#", ".net", "winforms", "contextmenu", "" ]
I'm having some trouble with a generic method I'm writing. It has the following signature; ``` public static ThingCollection<T> GetThings<T>(...) where T : Thing ``` There are several classes; ThingA, ThingB and ThingC that inherit from Thing; and I want to be able to have code something like this in the method. ``` var things = new ThingCollection<T>(); if (typeof(T) == typeof(Thing)) foreach (var item in someCollection) things.Add((T)new Thing(...)); else if (typeof(T) == typeof(ThingA)) foreach (var item in someCollection) things.Add((T)new ThingA(...)); else if (typeof(T) == typeof(ThingB)) foreach (var item in someCollection) things.Add((T)new ThingB(...)); else if (typeof(T) == typeof(ThingC)) foreach (var item in someCollection) things.Add((T)new ThingC(...)); else throw new Exception("Cannot return things of type " + typeof(T).ToString()); return things; ``` The problem is that I get a *best overloaded method match has invalid arguments* error if I don't cast the new objects. Adding the T casts as shown above is fine for the new Thing() but reports *Cannot convert type 'ThingA' to 'T'* for the other new calls. Intellisense indicates that T is a Thing but I don't understand why I can't cast the other objects to Thing, as they inherit from it. Perhaps this is not the right way to be doing what I'm trying to do. Am I on the right track? Perhaps missing some small nuance, or should I be doing something else entirely?
I don't get what you are trying to do with that code. If you want to create a Collection of Things where you could add any type of class derived from Thing, ThingCollection should not have a Typename: it's supposed to be a collection for concrete types. E.g, implementing A ThingCollection this way: ``` public class ThingCollection : List<Thing> {} ``` now you can do ``` ThingCollection tc = new ThingCollection(); tc.Add(new ThingA()); tc.Add(new ThingB()); tc.Add(new ThingC()); ``` Assuming of course that ThingA, ThingB and ThingC inherits from Thing. Or maybe you want to filter derived types of Things with the GetThings() i.e. you want that a call to GetThings() returns a ThingCollection.
Primarly I think, this code snippet has bad design. If you add "ThingD" class, you need change in another part of code, for clear behaviour. You should use something like: ``` public static ThingCollection<T> GetThings<T>(...) where T : Thing, new() ... ... T item = new T(); item.Something = Whatever(); ``` Or you can implement the "ICloneable" interface int Thing class.
Casting problem in C# generic method
[ "", "c#", "generics", "collections", "casting", "methods", "" ]
In the past I've always gone and called my namespace for a particular project the same as the project (and principle class) e.g.: ``` namespace KeepAlive { public partial class KeepAlive : ServiceBase {... ``` Then from other projects whenever i've called that class its always been: ``` KeepAlive.KeepAlive()... ``` I'm now beginning to think that this might not be such a good idea, but I'm sort of stumped what to actually call my namespace. What do other people do? Do you just have one namespace for all your projects?
We have this simple scheme: ``` CompanyName.ProductName ``` Then the application layer, e.g. ``` CompanyName.ProductName.Data CompanyName.ProductName.Web ``` etc. And inside divided per module and/or functionality, which normally correspond to folders ``` CompanyName.ProductName.Web.Shop CompanyName.ProductName.Web.Newsletter ``` etc. BTW: You can find answers to similar questions here: * [.NET namespaces](https://stackoverflow.com/questions/55692/net-namespaces) * [Should the folders in a solution match the namespace?](https://stackoverflow.com/questions/4664/should-the-folders-in-a-solution-match-the-namespace)
Having the name of a class being the same as the namespace is a bad idea - it makes it quite tricky to refer to the right thing in some cases, in my opinion. I usually call the project (and namespace) an appropriate name and then have "EntryPoint" or "Program" for the entry point where appropriate. In your example, I'd probably call the class "KeepAliveService".
What is best thing to call your namespace in .Net
[ "", "c#", ".net", "namespaces", "package", "" ]
I am working on a project where I need to create a boundary around a group of rectangles. Let's use this picture as an example of what I want to accomplish. EDIT: Couldn't get the image tag to work properly, so here is the full link: <http://www.flickr.com/photos/21093416@N04/3029621742/> We have rectangles A and C who are linked by a special link rectangle B. You could think of this as two nodes in a graph (A,C) and the edge between them (B). That means the rectangles have pointers to each other in the following manner: A->B, A<-B->C, C->B Each rectangle has four vertices stored in an array where index 0 is bottom left, and index 3 is bottom right. I want to "traverse" this linked structure and calculate the vertices making up the boundary (red line) around it. I already have some small ideas around how to accomplish this, but want to know if some of you more mathematically inclined have some neat tricks up your sleeves. The reason I post this here is just that someone might have solved a similar problem before, and have some ideas I could use. I don't expect anyone to sit down and think this through long and hard. I'm going to work on a solution in parallell as I wait for answers. Any input is greatly appreciated.
Using the example, where rectangles are perpendicular to each other and can therefore be presented by four values (two x coordinates and two y coordinates): ``` 1 2 3 4 5 6 1 +---+---+ | | 2 + A +---+---+ | | B | 3 + + +---+---+ | | | | | 4 +---+---+---+---+ + | | 5 + C + | | 6 +---+---+ ``` 1) collect all the x coordinates (both left and right) into a list, then sort it and remove duplicates ``` 1 3 4 5 6 ``` 2) collect all the y coordinates (both top and bottom) into a list, then sort it and remove duplicates ``` 1 2 3 4 6 ``` 3) create a 2D array by number of gaps between the unique x coordinates \* number of gaps between the unique y coordinates. It only needs to be one bit per cell, so in c++ a vector<bool> with likely give you a very memory-efficient version of this ``` 4 * 4 ``` 4) paint all the rectangles into this grid ``` 1 3 4 5 6 1 +---+ | 1 | 0 0 0 2 +---+---+---+ | 1 | 1 | 1 | 0 3 +---+---+---+---+ | 1 | 1 | 1 | 1 | 4 +---+---+---+---+ 0 0 | 1 | 1 | 6 +---+---+ ``` 5) for each cell in the grid, for each edge, if the cell beside it in that cardinal direction is not painted, draw the boundary line for that edge --- In the question, the rectangles are described as being four vectors where each represents a corner. If each rectangle can be at arbitrary and different rotation from others, then the approach I've outlined above won't work. The problem of finding the path around a complex polygon is regularly solved by vector graphics rasterizers, and a good approach to solving the problem is using a library such as Cairo to do the work for you!
The generalized solution to this problem is to implement boolean operations in terms of a scanline. You can find a brief discussion [here](http://boolean.klaasholwerda.nl/algdoc/top.html) to get you started. From the text: "The basis of the boolean algorithms is scanlines. For the basic principles the book: [Computational Geometry an Introduction](https://rads.stackoverflow.com/amzn/click/com/3540961313) by Franco P. Preparata and Michael Ian Shamos is very good." I own this book, though it's at the office now, so I can't look up the page numbers you should read, though chapter 8, on the geometry of rectangles is probably the best starting point.
Calculating a boundary around several linked rectangles
[ "", "c++", "graphics", "geometry", "" ]
``` abstract class Foo { private List<Object> container; private bool update; Foo Foo() { container = new List<object>(); update = false; } public abstract Bar CreateBar(); public void BeginUpdate() { if (!update) { Thread update_thread = new Thread(new ThreadStart(Update)); update_thread.Start(); } } private void Update() { update = true; while (update) { lock (container) { if (...) container.Add(this.CreateBar()); else container.Remove(...); } Thread.Sleep(1337); } } public void EndUpdate() { update = false; } public List<Object> Objects { get { lock (container) { return this.container; } } } } ``` When something outside of Foo calls the Foo's Object accessor like, ``` List<Objects> objects = foo_instance.Objects; foreach (Object o in objects) { Thread.Sleep(31173); } ``` How will the locking occur? Will the thread running Update() have to wait until the above foreach is done processing objects list? I would like that these two would work simultaneously, is the only solution to make a deep copy of objects?
Your code does not do what you think it does. This method ``` public List<Object> Objects { get { lock (container) { return this.container; } } } ``` Does not hold the lock after it has returned the value. So your loop is not locked. You cannot return the container instance from the clas
Several problems with this code: 1. You do not start the thread 2. You can have a race-condition (might not be applicable to your program) where multiple threads call BeginUpdate, both sees that update is false, and both start a thread, now you have two threads running, possibly interfering with each other, since you have a field member with the shared data 3. What is the point of locking in the property? You don't need it. Note that the container you return from the property will at times be in a state of flux due to the inner update. This means that outside code that calls the property will have to lock the container itself before accessing its contents. You do not need a lock to return the container reference though. 4. Race condition if you call EndUpdate and then BeginUpdate right after each other, the old thread might not have had a chance to exit yet I'd say that before you start worrying about what to lock and when, you should fix the code so that it doesn't have lots of other thread-related problems.
How will locking behave in .net?
[ "", "c#", ".net", "multithreading", "locking", "" ]
I added the columns in the select list to the order by list, but it is still giving me the error: ORDER BY items must appear in the select list if SELECT DISTINCT is specified. Here is the stored proc: ``` CREATE PROCEDURE [dbo].[GetRadioServiceCodesINGroup] @RadioServiceGroup nvarchar(1000) = NULL AS BEGIN SET NOCOUNT ON; SELECT DISTINCT rsc.RadioServiceCodeId, rsc.RadioServiceCode + ' - ' + rsc.RadioService as RadioService FROM sbi_l_radioservicecodes rsc INNER JOIN sbi_l_radioservicecodegroups rscg ON rsc.radioservicecodeid = rscg.radioservicecodeid WHERE rscg.radioservicegroupid IN (select val from dbo.fnParseArray(@RadioServiceGroup,',')) OR @RadioServiceGroup IS NULL ORDER BY rsc.RadioServiceCode,rsc.RadioServiceCodeId,rsc.RadioService END ```
Try this: ``` ORDER BY 1, 2 ``` OR ``` ORDER BY rsc.RadioServiceCodeId, rsc.RadioServiceCode + ' - ' + rsc.RadioService ```
While they are not the same thing, in one sense `DISTINCT` implies a `GROUP BY`, because every `DISTINCT` could be re-written using `GROUP BY` instead. With that in mind, it doesn't make sense to order by something that's not in the aggregate group. For example, if you have a table like this: ``` col1 col2 ---- ---- 1 1 1 2 2 1 2 2 2 3 3 1 ``` and then try to query it like this: ``` SELECT DISTINCT col1 FROM [table] WHERE col2 > 2 ORDER BY col1, col2 ``` That would make no sense, because there *could* end up being multiple `col2` values per row. Which one should it use for the order? Of course, in this query you know the results wouldn't be that way, but the database server can't know that in advance. This case is a little different. We included all the columns from the `order by` clause in the `select` clause, and therefore it seems at first glance they are all grouped. However, some of those columns are included in a calculated field. When we do this in combination with `distinct`, the `distinct` directive can *only* be applied to the *final results* of the calculation: it doesn't know anything about the source of the calculation any more. This means the server doesn't really know it can count on those columns. It knows they were used, but it doesn't know if the calculation operation might cause an effect similar to my first example above. Now we need to do something else to tell the server the columns are okay to use for ordering. There are several ways to do it, but this approach should work okay: ``` SELECT rsc.RadioServiceCodeId, rsc.RadioServiceCode + ' - ' + rsc.RadioService as RadioService FROM sbi_l_radioservicecodes rsc INNER JOIN sbi_l_radioservicecodegroups rscg ON rsc.radioservicecodeid = rscg.radioservicecodeid WHERE rscg.radioservicegroupid IN (SELECT val FROM dbo.fnParseArray(@RadioServiceGroup,',')) OR @RadioServiceGroup IS NULL GROUP BY rsc.RadioServiceCode,rsc.RadioServiceCodeId,rsc.RadioService ORDER BY rsc.RadioServiceCode,rsc.RadioServiceCodeId,rsc.RadioService ```
ORDER BY items must appear in the select list if SELECT DISTINCT is specified
[ "", "sql", "sql-server", "t-sql", "" ]
How do I clear the cin buffer in C++?
Possibly: ``` std::cin.ignore(INT_MAX); ``` This would read in and ignore everything until `EOF`. (you can also supply a second argument which is the character to read until (ex: `'\n'` to ignore a single line). Also: You probably want to do a: `std::cin.clear();` before this too to reset the stream state.
I would prefer the C++ size constraints over the C versions: ``` // Ignore to the end of Stream std::cin.ignore(std::numeric_limits<std::streamsize>::max()) // Ignore to the end of line std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n') ```
How do I flush the cin buffer?
[ "", "c++", "cin", "io-buffering", "" ]
If I have a for loop which is nested within another, how can I efficiently come out of both loops (inner and outer) in the quickest possible way? I don't want to have to use a boolean and then have to say go to another method, but rather just to execute the first line of code after the outer loop. What is a quick and nice way of going about this? I was thinking that exceptions aren't cheap/should only be thrown in a truly exceptional condition etc. Hence I don't think this solution would be good from a performance perspective. I don't feel it it is right to take advantage of the newer features in .NET (anon methods) to do something which is pretty fundamental.
Well, `goto`, but that is ugly, and not always possible. You can also place the loops into a method (or an anon-method) and use `return` to exit back to the main code. ``` // goto for (int i = 0; i < 100; i++) { for (int j = 0; j < 100; j++) { goto Foo; // yeuck! } } Foo: Console.WriteLine("Hi"); ``` vs: ``` // anon-method Action work = delegate { for (int x = 0; x < 100; x++) { for (int y = 0; y < 100; y++) { return; // exits anon-method } } }; work(); // execute anon-method Console.WriteLine("Hi"); ``` --- Note that in C# 7 we should get "local functions", which (syntax tbd etc) means it should work something like: ``` // local function (declared **inside** another method) void Work() { for (int x = 0; x < 100; x++) { for (int y = 0; y < 100; y++) { return; // exits local function } } }; Work(); // execute local function Console.WriteLine("Hi"); ```
C# adaptation of approach often used in C - set value of outer loop's variable outside of loop conditions (i.e. for loop using int variable `INT_MAX -1` is often good choice): ``` for (int i = 0; i < 100; i++) { for (int j = 0; j < 100; j++) { if (exit_condition) { // cause the outer loop to break: // use i = INT_MAX - 1; otherwise i++ == INT_MIN < 100 and loop will continue i = int.MaxValue - 1; Console.WriteLine("Hi"); // break the inner loop break; } } // if you have code in outer loop it will execute after break from inner loop } ``` As note in code says `break` will not magically jump to next iteration of the outer loop - so if you have code outside of inner loop this approach requires more checks. Consider other solutions in such case. This approach works with `for` and `while` loops but does not work for `foreach`. In case of `foreach` you won't have code access to the hidden enumerator so you can't change it (and even if you could `IEnumerator` doesn't have some "MoveToEnd" method). Acknowledgments to inlined comments' authors: `i = INT_MAX - 1` suggestion by [Meta](https://stackoverflow.com/users/167044/meta) `for`/`foreach` comment by [ygoe](https://stackoverflow.com/users/143684/ygoe). Proper `IntMax` by [jmbpiano](https://stackoverflow.com/users/4107124/jmbpiano) remark about code after inner loop by [blizpasta](https://stackoverflow.com/users/20646/blizpasta)
Breaking out of a nested loop
[ "", "c#", "for-loop", "nested-loops", "" ]
What is the best way to convert an Int value to the corresponding Char in Utf16, given that the Int is in the range of valid values?
``` (char)myint; ``` for example: ``` Console.WriteLine("(char)122 is {0}", (char)122); ``` yields: > (char)122 is z
``` int i = 65; char c = Convert.ToChar(i); ```
Int to Char in C#
[ "", "c#", "casting", "" ]
I have been banging my head on this one all day. The C++ project I am currently working on has a requirement to display an editable value. The currently selected digit displays the incremented value above and decremented value below for said digit. It is useful to be able to reference the editable value as both a number and collection of digits. What would be awesome is if there was some indexable form of a floating point number, but I have been unable to find such a solution. I am throwing this question out there to see if there is something obvious I am missing or if I should just roll my own. --- Thanks for the advice! I was hoping for a solution that wouldn't convert from float -> string -> int, but I *think* that is the best way to get away from floating point quantization issues. I ended up going with boost::format and just referencing the individual characters of the string. I can't see that being a huge performance difference compared to using combinations of modf and fmod to attempt to get a digit out of a float (It probably does just that behind the scenes, only more robustly than my implementation).
Internal representation of the float point numbers aren't like was you see. You can only cast to a stirng. To cast, do this: ``` char string[99]; sprintf(string,"%f",floatValue); ``` Or see this : <http://www.parashift.com/c++-faq-lite/misc-technical-issues.html#faq-39.1> The wikipedia article can explain more on the representation: <http://en.wikipedia.org/wiki/Floating_point>
[Oh, there are many ways to convert to a string.](https://stackoverflow.com/questions/303562/c-format-macro-inline-ostringstream#306053) (Though I do prefer s**n**printf() myself.) Or you could convert to an int and pull the digits out with modulus and integer-division. You can count the number of digits with log{base10}. (Remember: log{baseA}\_X / log{baseA}\_B = log{baseB}\_X.) Example: ``` #define SHOW(X) cout << # X " = " << (X) << endl int main() { double d = 1234.567; SHOW( (int(d)%10000) / 1000 ); SHOW( (int(d)%1000) / 100 ); SHOW( (int(d)%100) / 10 ); SHOW( (int(d)%10) ); SHOW( (int(d*10) % 10) ); SHOW( (int(d*100) % 10) ); SHOW( (int(d*1000)% 10) ); SHOW( log(d)/log(10) ); } ``` Though you ought to use static\_cast... Watch out for exponential notation. With a very big or very small numbers, you may have a problem. Floating point numbers also have round off issues that may cause you some grief. (It's the same reason why we don't use operator== between two doubles. Or why you can't rely on a\*b == b\*a. Depending on the exact values of a & b, they may differ very slightly out around 10^-25.)
Extracting individual digits from a float
[ "", "c++", "floating-point", "extract", "digits", "" ]
I have an arraylist that contains items called Room. Each Room has a roomtype such as kitchen, reception etc. I want to check the arraylist to see if any rooms of that type exist before adding it to the list. Can anyone recommend a neat way of doing this without the need for multiple foreach loops? (.NET 2.0) --- I havent got access to the linq technology as am running on .net 2.0. I should have stated that in the question. Apologies
I would not use `ArrayList` here; since you have .NET 2.0, use `List<T>` and all becomes simple: ``` List<Room> rooms = ... string roomType = "lounge"; bool exists = rooms.Exists(delegate(Room room) { return room.Type == roomType; }); ``` Or with C# 3.0 (still targetting .NET 2.0) ``` bool exists = rooms.Exists(room => room.Type == roomType); ``` Or with C# 3.0 and either [LINQBridge](http://www.albahari.com/nutshell/linqbridge.aspx) or .NET 3.5: ``` bool exists = rooms.Any(room => room.Type == roomType); ``` (the `Any` usage will work with more types, not just `List<T>`)
From your question it's not 100% clear to me if you want to enforce the rule that there may be only one room of a given type, or if you simply want to know. If you have the invariant that no collection of `Room`s may have more than one of the same `Room` type, you might try using a `Dictionary<Type, Room>`. This has the benefit of not performing a linear search on add. You would add a room using the following operations: ``` if(rooms.ContainsKey(room.GetType())) { // Can't add a second room of the same type ... } else { rooms.Add(room.GetType(), room); } ```
check for duplicates in arraylist
[ "", "c#", ".net", "asp.net", "" ]
I've written a program that counts lines, words, and characters in a text: it does this with threads. It works great sometimes, but not so great other times. What ends up happening is the variables pointing to the number of words and characters counted sometimes come up short and sometimes don't. It seems to me that the threads are sometimes ending before they can count all the words or characters that they want to. Is it because these threads go out of scope when the while (true) loop breaks? I've included the code from the thready part of my problem below: ``` private void countText() { try { reader = new BufferedReader(new FileReader("this.txt")); while (true) { final String line = reader.readLine(); if(line == null) {break;} lines++; new Thread(new Runnable() {public void run() {chars += characterCounter(line);}}).start(); new Thread(new Runnable() {public void run() {words += wordCounter(line);}}).start(); println(line); } } catch(IOException ex) {return;} } ``` (Sub Question: This is the first time I've asked about something and posted code. I don't want to use StackOverflow in place of google and wikipedia and am worried that this isn't an appropriate question? I tried to make the question more general so that I'm not just asking for help with my code... but, is there another website where this kind of question might be more appropriate?)
A different threaded design would make it easier to find and fix this kind of problem, and be more efficient into the bargain. This is a longish response, but the summary is "if you're doing threads in Java, check out [java.util.concurrent](http://java.sun.com/j2se/1.5.0/docs/api/java/util/concurrent/package-summary.html) as soon as humanly possible)". I guess you're multithreading this code to learn threads rather than to speed up counting words, but that's a very inefficient way to use threads. You're creating two threads *per line* - two thousand threads for a thousand line file. Creating a thread (in modern JVMs) uses operating system resources and is generally fairly expensive. When two - let alone two thousand - threads have to access a shared resource (such as your `chars` and `words` counters), the resulting memory contention also hurts performance. Making the counter variables `synchronized` as [Chris Kimpton suggests](https://stackoverflow.com/questions/289804/when-does-a-thread-go-out-of-scope#289818) or `Atomic` as [WMR suggests](https://stackoverflow.com/questions/289804/when-does-a-thread-go-out-of-scope#289851) will probably fix the code, but it will also make the effect of contention much worse. I'm pretty sure it will go slower than a single-threaded algorithm. I suggest having just one long-lived thread which looks after `chars`, and one for `words`, each with a work queue to which you submit jobs each time you want to add a new number. This way only one thread is writing to each variable, and if you make changes to the design it'll be more obvious who's responsible for what. It'll also be faster because there's no memory contention and you're not creating hundreds of threads in a tight loop. It's also important, once you've read all the lines in the file, to *wait* for all the threads to finish before you actually print out the values of the counters, otherwise you lose the updates from threads that haven't finished yet. With your current design you'd have to build up a big list of threads you created, and run through it at the end checking that they're all dead. With a queue-and-worker-thread design you can just tell each thread to drain its queue and then wait until it's done. Java (from 1.5 and up) makes this kind of design very easy to implement: check out [java.util.concurrent.Executors.newSingleThreadExecutor](http://java.sun.com/j2se/1.5.0/docs/api/java/util/concurrent/Executors.html#newSingleThreadExecutor). It also makes it easy to add more concurrency later on (assuming proper locking etc), as you can just switch to a thread pool rather than a single thread.
As Chris Kimpton already pointed out correctly you have a problem with the updating of `chars` and `words` in different threads. Synchronizing on `this` won't work either because `this` is a reference to the current thread which means different threads will synchronize on different objects. You could use an extra "lock object" you can synchronize on but the easiest way to fix this would probably be to use [AtomicIntegers](http://java.sun.com/javase/6/docs/api/java/util/concurrent/atomic/AtomicInteger.html) for the 2 counters: ``` AtomicInteger chars = new AtomicInteger(); ... new Thread(new Runnable() {public void run() { chars.addAndGet(characterCounter(line));}}).start(); ... ``` While this will probably fix your problem, [Sam Stoke's more detailed answer](https://stackoverflow.com/questions/289804/when-does-a-thread-go-out-of-scope#289869) is completely right, the original design is very inefficient. To answer your question about when a thread "goes out of scope": You are starting two new threads for every line in your file and all of them will run until they reach the end of their `run()` method. This is unless you make them [daemon threads)](http://java.sun.com/javase/6/docs/api/java/lang/Thread.html#setDaemon(boolean)), in that case they'll exit as soon as daemon threads are the only ones still running in this JVM.
when does a thread go out of scope?
[ "", "java", "multithreading", "scope", "" ]
In OOP languages like C# or VB.NET, if I make the properties or methods in a super class `protected` I can't access them in my Form - they can only be accessed in my class that inherits from that super class. To access those properties or methods I need to make them `public`, which defeats encapsulation, or re-write them into my class, which defeats inheritance. What is the right way to do this?
"need to make them public which defeats encapsulation" Don't conflate good design with the icky visibility rules. The visibility rules are confusing. There are really two orthogonal kinds of visibility -- subclass and client. It's not perfectly clear why we'd ever conceal anything from our subclasses. But we can, with `private`. Here's what's important. Encapsulation does not mean hiding. Protected and private are not an essential part of good encapsulation. You can do good design with everything being public (that's the way Python works, for example). The protected/private stuff is -- mostly -- about intellectual property management: are you willing to commit (in a legally binding, "see-you-in-court-if-it-doesn't-work" way) to an interface? If your software development involves lawyers, then you care about adding protect and private to the things you're not committed to. If you don't have to cope with lawyers, consider doing encapsulation right but leave everything public.
If you have code which needs to ask an Class to perform a specific operation but the class does not present your code with a means to do that then the Class doesn't fulfill you codes requirements. Its bit like saying I've got a Car (Automobile) that has a protected steering wheel so I can't access it. The car is no use to me. Either make those members Public (or at least internal) and use them or ditch the class and use one that gives your consuming code the features it needs. Perhaps what you are really looking for is an interface. The interface contains the members your code needs and you implement that interface on your class. The advantage here is that your class can determine that the members are being accessed via this Interface rather than an inheriting subclass.
Encapsulation VS Inheritance - How to use a protected function?
[ "", "c#", "vb.net", "oop", "inheritance", "encapsulation", "" ]
I run all my integers through a `(int)Integer` to make them safe to use in my query strings. I also run my strings through this function code:- ``` if(!get_magic_quotes_gpc()) { $string = mysql_real_escape_string($string); } $pattern = array("\\'", "\\\"", "\\\\", "\\0"); $replace = array("", "", "", ""); if(preg_match("/[\\\\'\"\\0]/", str_replace($pattern, $replace, $string))) $string = addslashes($string); $cleanedString = str_replace('%','',$string); ``` I obviously return the $cleanedString variable. Now I replace the % character because it is a wildcard to mySQL and it could potentially slow down my queries (or make them return incorrect data) if the user inserted them. Are there any other special characters for mySQL I should be concerned about? On a second note, is there anything wrong or redundant about my search and replace after the `mysql_real_escape_string`? I got it from a website when I was first starting out and (if I remember correctly) it said you had to use this search/replace in addition to the escape string. It looks like it's trying to remove any previously escaped injection characters?
yeah I think you've got things going a bit strangely there. First of all, I'd check for magic quotes and *remove* the slashes if it's turned on. That way you've got a string which actually represents the information you want (and not one that has been treated with slashes). If you particularly want to remove the % wildcard then you could just escape that or remove it altogether. Before you insert the string into an SQL query, finally run it through mysql\_real\_escape\_string, and everything will be fine. ``` $string = $_POST['searchTerm']; if (get_magic_quotes_gpc()) { $string = stripslashes($string); } $string = str_replace("%", "", $string); $safeString = mysql_real_escape_string($string); ```
Okay I have several comments: * The magic quoting feature is [deprecated](http://php.net/manual/en/security.magicquotes.php), your PHP environment should never enable magic quotes. So checking for it should be unnecessary, unless you're designing code that may be be deployed into other customers' environments who have (inadvisedly) enabled magic quotes. * The regular expression in your `preg_match()` is incorrect if you're searching for sequences of characters. A regular expression like `[xyz]` matches any *one* of the single characters x, y, or z. It does not match the string xy or yz. Anyway, this is academic because I don't think you need to search or replace special characters this way at all. * `mysql_real_escape_string()` is adequate to escape string literals that you intend to interpolate inside quotes in SQL strings. No need to do string substitution for other quotes, backslashes, etc. * `%` and `_` are wildcards in SQL *only* when using pattern-matching with `LIKE` expressions. These characters have no meaning if you're just comparing with equality or inequality operators or regexps. Even if you are using `LIKE` expressions, there's no need to escape these characters for the sake of defense against SQL injection. It's up to you if you want to treat them as literal characters (in which case escape them with a backslash) or wildcards in a `LIKE` expression (in which case just leave them in). * All of the above applies when you're interpolating PHP variables into SQL expressions in place of literal string values. Escaping is not necessary at all if you use [bound query parameters](http://php.net/manual/en/mysqli-stmt.bind-param.php) instead of interpolating. Bound parameters are not available in the plain "mysql" API, but only in the "mysqli" API. * Another case is where you interpolate PHP variables in place of SQL table names, column names, or other SQL syntax. You can't use bound parameters in such cases; bound parameters *only* take the place of string literals. If you need to make the column name dynamic (for example to `ORDER BY` a column of the user's preference), you should [delimit the column name](https://stackoverflow.com/questions/214309/do-different-databases-use-different-name-quote#214344) with back-quotes (in MySQL) or square brackets (Microsoft) or double-quotes (other standard SQL). So I would say your code could be reduced simply to the following: ``` $quotedString = mysql_real_escape_string($string); ``` That's *if* you are going to use the string for interpolation; if you're going to use it as a bound parameter value, it's even simpler: ``` $paramString = $string; ```
MySQL/PHP - escaping characters that may slow my database down (or make it perform unexpectedly)
[ "", "php", "mysql", "security", "sql-injection", "" ]
The assembly it's trying to find isn't the root assembly - it's a referenced one, but it's in the same folder, and Directory.GetCurrentDirectory() is the folder with all of the files in. I'm stuck - any suggestions?
You can either: 1. Create a new `AppDomain` to load the assembly (and set the `AppDomain`'s base directory to the directory containing all the assemblies). 2. Attach a handler for `AppDomain.AssemblyResolve` to help the CLR find the assembly's dependencies. 3. You might be able to add the directory in question to the list of paths to probe. However, it will need to reside somewhere under your application's directory. See the [probe](http://msdn.microsoft.com/en-us/library/823z9h8w.aspx) element for more info.
You could try using something like this ``` string myDll = string.Empty; string location = Assembly.GetExecutingAssembly().Location; if (location != null) { myDll = string.Format(@"{0}\my.assembly.name.dll", location.Substring(0, location.LastIndexOf(@"\"))); } ``` This should get physical directory in which the assemblies are running. This could be in the Windows .NET temporary directories. However, because the files are at the same level they should exist there side by side.
Trying to load an app through reflection and get error "Could not load file or assembly...The system cannot find the file specified."
[ "", "c#", "reflection", "" ]
I need a method for adding "business days" in PHP. For example, Friday 12/5 + 3 business days = Wednesday 12/10. At a minimum I need the code to understand weekends, but ideally it should account for US federal holidays as well. I'm sure I could come up with a solution by brute force if necessary, but I'm hoping there's a more elegant approach out there. Anyone? Thanks.
Here's a function from the [user comments](http://www.php.net/manual/en/function.date.php#79911) on the date() function page in the PHP manual. It's an improvement of an earlier function in the comments that adds support for leap years. Enter the starting and ending dates, along with an array of any holidays that might be in between, and it returns the working days as an integer: ``` <?php //The function returns the no. of business days between two dates and it skips the holidays function getWorkingDays($startDate,$endDate,$holidays){ // do strtotime calculations just once $endDate = strtotime($endDate); $startDate = strtotime($startDate); //The total number of days between the two dates. We compute the no. of seconds and divide it to 60*60*24 //We add one to inlude both dates in the interval. $days = ($endDate - $startDate) / 86400 + 1; $no_full_weeks = floor($days / 7); $no_remaining_days = fmod($days, 7); //It will return 1 if it's Monday,.. ,7 for Sunday $the_first_day_of_week = date("N", $startDate); $the_last_day_of_week = date("N", $endDate); //---->The two can be equal in leap years when february has 29 days, the equal sign is added here //In the first case the whole interval is within a week, in the second case the interval falls in two weeks. if ($the_first_day_of_week <= $the_last_day_of_week) { if ($the_first_day_of_week <= 6 && 6 <= $the_last_day_of_week) $no_remaining_days--; if ($the_first_day_of_week <= 7 && 7 <= $the_last_day_of_week) $no_remaining_days--; } else { // (edit by Tokes to fix an edge case where the start day was a Sunday // and the end day was NOT a Saturday) // the day of the week for start is later than the day of the week for end if ($the_first_day_of_week == 7) { // if the start date is a Sunday, then we definitely subtract 1 day $no_remaining_days--; if ($the_last_day_of_week == 6) { // if the end date is a Saturday, then we subtract another day $no_remaining_days--; } } else { // the start date was a Saturday (or earlier), and the end date was (Mon..Fri) // so we skip an entire weekend and subtract 2 days $no_remaining_days -= 2; } } //The no. of business days is: (number of weeks between the two dates) * (5 working days) + the remainder //---->february in none leap years gave a remainder of 0 but still calculated weekends between first and last day, this is one way to fix it $workingDays = $no_full_weeks * 5; if ($no_remaining_days > 0 ) { $workingDays += $no_remaining_days; } //We subtract the holidays foreach($holidays as $holiday){ $time_stamp=strtotime($holiday); //If the holiday doesn't fall in weekend if ($startDate <= $time_stamp && $time_stamp <= $endDate && date("N",$time_stamp) != 6 && date("N",$time_stamp) != 7) $workingDays--; } return $workingDays; } //Example: $holidays=array("2008-12-25","2008-12-26","2009-01-01"); echo getWorkingDays("2008-12-22","2009-01-02",$holidays) // => will return 7 ?> ```
Get the number of **working days without holidays** between two dates : ### Use example: ``` echo number_of_working_days('2013-12-23', '2013-12-29'); ``` ### Output: ``` 3 ``` ### Function: ``` function number_of_working_days($from, $to) { $workingDays = [1, 2, 3, 4, 5]; # date format = N (1 = Monday, ...) $holidayDays = ['*-12-25', '*-01-01', '2013-12-23']; # variable and fixed holidays $from = new DateTime($from); $to = new DateTime($to); $to->modify('+1 day'); $interval = new DateInterval('P1D'); $periods = new DatePeriod($from, $interval, $to); $days = 0; foreach ($periods as $period) { if (!in_array($period->format('N'), $workingDays)) continue; if (in_array($period->format('Y-m-d'), $holidayDays)) continue; if (in_array($period->format('*-m-d'), $holidayDays)) continue; $days++; } return $days; } ```
Calculate business days
[ "", "php", "calendar", "date", "" ]
I always hear that using "lastInsertId" (or mysql\_insert\_id() if you're not using PDO) is evil. In case of triggers it obviously is, because it could return something that's totally not the last ID that your INSERT created. ``` $DB->exec("INSERT INTO example (column1) VALUES ('test')"); // Usually returns your newly created ID. // However when a TRIGGER inserts into another table with auto-increment: // -> Returns newly created ID of trigger's INSERT $id = $DB->lastInsertId(); ``` What's the alternative?
If you go the route of ADOdb (<http://adodb.sourceforge.net/>), then you can create the insert ID *before hand* and explicitly specific the ID when inserting. This can be implemented portably (ADOdb supports a ton of different databases...) and guarantees you're using the correct insert ID. The PostgreSQL SERIAL data type is similar except that it's per-table/per-sequence, you specify the table/sequence you want the last insert ID for when you request it.
IMHO it's only considered "evil" because hardly any other SQL database (if any) has it. Personally I find it incredibly useful, and wish that I didn't have to resort to other more complicated methods on other systems.
Alternative to "PDO::lastInsertId" / "mysql_insert_id"
[ "", "php", "mysql", "auto-increment", "lastinsertid", "mysql-insert-id", "" ]
I have a need to populate a Word 2007 document from code, including repeating table sections - currently I use an XML transform on the document.xml portion of the docx, but this is extremely time consuming to setup (each time you edit the template document, you have to recreate the transform.xsl file, which can take up to a day to do for complex documents). Is there any better way, preferably one that doesn't require you to *run* Word 2007 during the process? Regards Richard
I tried myself to write some code for that purpose, but gave up. Now I use a 3rd party product: [**Aspose Words**](http://www.aspose.com/categories/file-format-components/aspose.words-for-.net-and-java/default.aspx) and am quite happy with that component. It doesn't need Microsoft Word on the machine. *"Aspose.Words enables .NET and Java applications to read, modify and write Word® documents without utilizing Microsoft Word®."* *"Aspose.Words supports a wide array of features including document creation, content and formatting manipulation, powerful mail merge abilities, comprehensive support of DOC, OOXML, RTF, WordprocessingML, HTML, OpenDocument and PDF formats. Aspose.Words is truly the most affordable, fastest and feature rich Word component on the market."* **DISCLAIMER**: I am not affiliated with that company.
Since a DOCX file is simply a ZIP file containing a folder structure with images and XML files, you should be able to manipulate those XML files using our favorite XML manipulation API. The specification of the format is known as **WordprocessingML**, part of the [Office Open XML standard](http://en.wikipedia.org/wiki/Office_Open_XML). I thought I'd mention it in case the 3rd party tool suggested by splattne is not an option.
What is the best way to populate a Word 2007 template in C#?
[ "", "c#", "ms-word", "openxml", "docx", "word-2007", "" ]
Are all the additions to C# for version 4 (dynamic, code contracts etc) expected to run on the current .NET CLR, or is there a planned .NET upgrade as well?
C# 4 will require the .NET 4.0 CLR.
Well, .NET 4.0 will require CLR 4.0; however, it is a little harder to answer what parts of C# 4.0 will work on .NET 2.0/3.x. We can hope that VS2010 will still be multi-targeting(I don't have the CTP "on me" so to speak, so I can't check...). But some of the language features don't *seem* hugely tied to the runtime (named parameters, some of the COM changes such as "ref") - so I can't think of a good reason why they wouldn't be available when talking to .NET 2.0/3.x. I haven't checked, though. However, as with C# 3.0, some of the features *are* tied to the runtime - in particular `dynamic`. I need to dig out the CTP and have another play, methinks...
C# 4 and CLR Compatibility
[ "", "c#", ".net", "clr", "" ]
I have an application where I would like to have mixed Java and Scala source (actually its migrating a java app to scala - but a bit at a time). I can make this work in IDEs just fine, very nice. But I am not sure how to do this with maven - scalac can compile java and scala intertwined, but how to I set up maven for the module? Also, does my scala source have to be a different folder to the java?
Using the maven scala plugin, a config like the one below will work for a project that mixes java and scala source (scala source of course goes in the /scala directory, as mentioned by someone else). You can run run mvn compile, test etc... and it will all work as normal. Very nice (it will run scalac first automatically). For a great IDE, IntelliJ 8 works nicely: add in the scala plug in, then add a scala facet, and then adjust the compile setting for scala to run scalac first (critical if you have circular dependencies with scala and java source). ``` <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>demo</groupId> <artifactId>scala-java-app</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging> <name>scala-java-app</name> <repositories> <repository> <id>scala-tools.org</id> <name>Scala-tools Maven2 Repository</name> <url>http://scala-tools.org/repo-releases</url> </repository> </repositories> <pluginRepositories> <pluginRepository> <id>scala-tools.org</id> <name>Scala-tools Maven2 Repository</name> <url>http://scala-tools.org/repo-releases</url> </pluginRepository> </pluginRepositories> <build> <plugins> <plugin> <groupId>org.scala-tools</groupId> <artifactId>maven-scala-plugin</artifactId> <executions> <execution> <id>compile</id> <goals> <goal>compile</goal> </goals> <phase>compile</phase> </execution> <execution> <id>test-compile</id> <goals> <goal>testCompile</goal> </goals> <phase>test-compile</phase> </execution> <execution> <phase>process-resources</phase> <goals> <goal>compile</goal> </goals> </execution> </executions> </plugin> <plugin> <artifactId>maven-compiler-plugin</artifactId> <configuration> <source>1.5</source> <target>1.5</target> </configuration> </plugin> </plugins> </build> <dependencies> <dependency> <groupId>org.scala-lang</groupId> <artifactId>scala-library</artifactId> <version>2.7.2</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>3.8.1</version> <scope>test</scope> </dependency> </dependencies> ```
Yeah, the scala part has to be in a separate module and in `src/main/scala` directory. Maven regards mixed source like this as heresy. You enable scala compilation by importing the [scala maven plugin](http://scala-tools.org/mvnsites/maven-scala-plugin/). The ["usage"](http://scala-tools.org/mvnsites/maven-scala-plugin/usage.html) page as a good example.
Building a scala app with maven (that has java source mixed in)
[ "", "java", "maven-2", "scala", "" ]
First, I know there are methods off of the generic `List<>` class already in the framework do iterate over the `List<>`. But as an example, what is the correct syntax to write a ForEach method to iterate over each object of a `List<>`, and do a `Console.WriteLine(object.ToString())` on each object. Something that takes the `List<>` as the first argument and the lambda expression as the second argument. Most of the examples I have seen are done as extension methods or involve LINQ. I'm looking for a plain-old method example.
``` public void Each<T>(IEnumerable<T> items, Action<T> action) { foreach (var item in items) action(item); } ``` ... and call it thusly: ``` Each(myList, i => Console.WriteLine(i)); ```
Is this what you're asking for? ``` int[] numbers = { 1, 2, 3 }; numbers.ToList().ForEach(n => Console.WriteLine(n)); ```
C# Syntax - Example of a Lambda Expression - ForEach() over Generic List
[ "", "c#", ".net", "syntax", "lambda", "" ]
I'm in the process of setting up a php project, but am not very familiar with how to properly use php's include/require commands. My layout currently looks like this: ``` /public --apache points into this directory /public/index.php /public/blah/page.php /utils/util1.php -- useful classes/code are stored in other directories out here /dbaccess/db1.php dbaccess/db1.php require '../utils/util1.php ``` public/index.php ``` require '../dbaccess/db1.php' ``` public/blah/page.php ``` require '../../dbaccess/db1.php' ``` The problem is this from the php 'include' documentation: > If filename begins with ./ or ../, it is looked only in the current working directory So public/blah/page.php fails because it includes dbaccess/db1.php which blows up when it tries to include util1.php. It fails because it's relative path is from the original script in public/blah/, not from dbaccess/ This seems pretty stupid -- db1.php has to just know where it's being included from which isn't going to work. I've seen strategies like this: ``` require_once dirname(__FILE__) . '/../utils/util1.php'); ``` That apparently works since now the path is an absolute path, but just seems really bizarre to me. Is that normal? Should I continue down that path or am I missing something obvious here?
Usually, the standard conventions are thus: like @grepsedawk said, you'll want to define a constant that contains the root of your project folder and if you can the root of your includes folder: ``` define('APP_ROOT', dirname(__FILE__)); define('INCLUDE_ROOT', APP_ROOT . "/includes"); ``` Note: the constant name needs to be a string! Also, you'll notice I'm using `dirname(__FILE__);`. If you place your constants definition file in a subdirectory, you can do a `dirname(dirname(__FILE__));`, which is the equivalent of a `../`. Now some other caveats. While `PATH_SEPARATOR` is a cool constant, it is not needed. Windows accepts / or \ in path names, and since Linux only users / as a path separator, go ahead and always use a / instead of mucking up your code with repeated references to `PATH_SEPARATOR`. Now that you have your root constants defined, what you'll do when you need a configuration file included is a simple: ``` include INCLUDE_ROOT . '/path/to/some/file.php'; ``` You'll probably want your constant definitions (the `define(...)`'s above) in a bootstrap script in your root directory: > ``` > www_root/ > index.php > bootstrap.php > ``` The bootstrap will contain the defines (or an `include` of the constants file), as well as an `include` of any files that will be required by EVERY page. And finally the last standard convention you may not use, but if you start doing object oriented programming, the most common method (the PEAR standard) is to name your classes by using an \_ to separate namespaces: ``` class GlobalNamespace_Namespace_Class //... ``` And then organizing your file structure mapping name spaces to subdirectories (literally replacing all \_'s with /'s): > ``` > include_dir/ > GlobalNamespace/ > Namespace/ > Class.php > ``` And using `__autoload()` functions to load your classes, but that's another question.
Have a configuration script that sets the "INSTALL ROOT" of your project and then use absolute paths. Relative path with multiple includes is a headache in php. DEFINE("INSTALL\_ROOT", "/path/to/www/project") require\_once(INSTALL\_ROOT . '/util1.php')
PHP include file strategy needed
[ "", "php", "" ]
What is the best way to deal with XML documents, XSD etc in C# 2.0? Which classes to use etc. What are the best practices of parsing and making XML documents etc. EDIT: .Net 3.5 suggestions are also welcome.
The primary means of reading and writing in C# 2.0 is done through the **XmlDocument** class. You can load most of your settings directly into the XmlDocument through the XmlReader it accepts. ### Loading XML Directly ``` XmlDocument document = new XmlDocument(); document.LoadXml("<People><Person Name='Nick' /><Person Name='Joe' /></People>"); ``` ### Loading XML From a File ``` XmlDocument document = new XmlDocument(); document.Load(@"C:\Path\To\xmldoc.xml"); // Or using an XmlReader/XmlTextReader XmlReader reader = XmlReader.Create(@"C:\Path\To\xmldoc.xml"); document.Load(reader); ``` I find the easiest/fastest way to read an XML document is by using XPath. ### Reading an XML Document using XPath (Using XmlDocument which allows us to edit) ``` XmlDocument document = new XmlDocument(); document.LoadXml("<People><Person Name='Nick' /><Person Name='Joe' /></People>"); // Select a single node XmlNode node = document.SelectSingleNode("/People/Person[@Name = 'Nick']"); // Select a list of nodes XmlNodeList nodes = document.SelectNodes("/People/Person"); ``` If you need to work with XSD documents to validate an XML document you can use this. ### Validating XML Documents against XSD Schemas ``` XmlReaderSettings settings = new XmlReaderSettings(); settings.ValidateType = ValidationType.Schema; settings.Schemas.Add("", pathToXsd); // targetNamespace, pathToXsd XmlReader reader = XmlReader.Create(pathToXml, settings); XmlDocument document = new XmlDocument(); try { document.Load(reader); } catch (XmlSchemaValidationException ex) { Trace.WriteLine(ex.Message); } ``` ### Validating XML against XSD at each Node (UPDATE 1) ``` XmlReaderSettings settings = new XmlReaderSettings(); settings.ValidateType = ValidationType.Schema; settings.Schemas.Add("", pathToXsd); // targetNamespace, pathToXsd settings.ValidationEventHandler += new ValidationEventHandler(settings_ValidationEventHandler); XmlReader reader = XmlReader.Create(pathToXml, settings); while (reader.Read()) { } private void settings_ValidationEventHandler(object sender, ValidationEventArgs args) { // e.Message, e.Severity (warning, error), e.Error // or you can access the reader if you have access to it // reader.LineNumber, reader.LinePosition.. etc } ``` ### Writing an XML Document (manually) ``` XmlWriter writer = XmlWriter.Create(pathToOutput); writer.WriteStartDocument(); writer.WriteStartElement("People"); writer.WriteStartElement("Person"); writer.WriteAttributeString("Name", "Nick"); writer.WriteEndElement(); writer.WriteStartElement("Person"); writer.WriteStartAttribute("Name"); writer.WriteValue("Nick"); writer.WriteEndAttribute(); writer.WriteEndElement(); writer.WriteEndElement(); writer.WriteEndDocument(); writer.Flush(); ``` ***(UPDATE 1)*** In .NET 3.5, you use XDocument to perform similar tasks. The difference however is you have the advantage of performing Linq Queries to select the exact data you need. With the addition of object initializers you can create a query that even returns objects of your own definition right in the query itself. ``` XDocument doc = XDocument.Load(pathToXml); List<Person> people = (from xnode in doc.Element("People").Elements("Person") select new Person { Name = xnode.Attribute("Name").Value }).ToList(); ``` ***(UPDATE 2)*** A nice way in .NET 3.5 is to use XDocument to create XML is below. This makes the code appear in a similar pattern to the desired output. ``` XDocument doc = new XDocument( new XDeclaration("1.0", Encoding.UTF8.HeaderName, String.Empty), new XComment("Xml Document"), new XElement("catalog", new XElement("book", new XAttribute("id", "bk001"), new XElement("title", "Book Title") ) ) ); ``` creates ``` <!--Xml Document--> <catalog> <book id="bk001"> <title>Book Title</title> </book> </catalog> ``` All else fails, you can check out this MSDN article that has many examples that I've discussed here and more. <http://msdn.microsoft.com/en-us/library/aa468556.aspx>
It depends on the size; for small to mid size xml, a DOM such as [XmlDocument](http://msdn.microsoft.com/en-us/library/system.xml.xmldocument.aspx) (any C#/.NET versions) or [XDocument](http://msdn.microsoft.com/en-us/library/system.xml.linq.xdocument.aspx) (.NET 3.5/C# 3.0) is the obvious winner. For using xsd, You can load xml using an [XmlReader](http://msdn.microsoft.com/en-us/library/system.xml.xmlreader.aspx), and an XmlReader accepts (to [Create](http://msdn.microsoft.com/en-us/library/system.xml.xmlreader.create.aspx)) an [XmlReaderSettings](http://msdn.microsoft.com/en-us/library/system.xml.xmlreadersettings.aspx). The XmlReaderSettings objects has a [Schemas](http://msdn.microsoft.com/en-us/library/system.xml.xmlreadersettings.schemas.aspx) property that can be used to perform xsd (or dtd) validation. For writing xml, the same things apply, noting that it is a little easier to lay out content with LINQ-to-XML (XDocument) than the older XmlDocument. However, for huge xml, a DOM may chomp too much memory, in which case you might need to use XmlReader/XmlWriter directly. Finally, for manipulating xml you may wish to use [XslCompiledTransform](http://msdn.microsoft.com/en-us/library/system.xml.xsl.xslcompiledtransform.aspx) (an xslt layer). The alternative to working with xml is to work with an object model; you can use [xsd.exe](http://msdn.microsoft.com/en-us/library/x6c1kb0s.aspx) to create classes that represent an xsd-compliant model, and simply load the xml *as objects*, manipulate it with OO, and then serialize those objects again; you do this with [XmlSerializer](http://msdn.microsoft.com/en-us/library/system.xml.serialization.xmlserializer.aspx).
How to deal with XML in C#
[ "", "c#", ".net", "xml", "" ]
I have recently written a dynamic querying tool using expression trees and as I went the power of expression trees began to dawn on me. My querying tool could also form the basis of a reporting tool, a dynamic decision engine and maybe other cases where you need to work with dynamic objects in abstract ways. The process has been painful (recursive calls to generic methods by reflection - ugh) so I am wondering whether anyone has created a generic library that might harness the power of expression trees to accomplish some of these kinds of tasks? I have seen [PredicateBuilder](http://www.albahari.com/nutshell/predicatebuilder.aspx) but does anyone know of any others?
[Generic operators](http://www.pobox.com/~skeet/csharp/miscutil/usage/genericoperators.html) (in [MiscUtil](http://www.pobox.com/~skeet/csharp/miscutil/)) is a pretty well utilised bit of code based on expression trees; very simple, but very versatile. Some other ideas: * [cloning objects](http://groups.google.com/group/microsoft.public.dotnet.languages.csharp/browse_thread/thread/d9722a51b04300a/0edae91abc1c0f1a#0edae91abc1c0f1a) * [dynamic ordering](http://groups.google.com/group/microsoft.public.dotnet.languages.csharp/browse_thread/thread/9ca28e3f0205bb87/c5b6c43ef3f38ae9) * [dynamic LINQ](http://weblogs.asp.net/scottgu/archive/2008/01/07/dynamic-linq-part-1-using-the-linq-dynamic-query-library.aspx) (lots of others)
Have you looked at the DLR? I don't know much about it in detail, but my understanding is that the expression-tree mechanism which is behind the scenes in Linq-to-SQL has effectively been published in the DLR.
Expression trees in .NET - Libraries?
[ "", "c#", ".net", "expression-trees", "" ]
I would like to create a simple program (in Java) which edits text files - particularly one which performs inserting arbitrary pieces of text at random positions in a text file. This feature is part of a larger program I am currently writing. Reading the description about java.util.RandomAccessFile, it appears that any write operations performed in the middle of a file would actually overwrite the exiting content. This is a side-effect which I would like to avoid (if possible). Is there a simple way to achieve this? Thanks in advance.
Okay, this question is pretty old, but FileChannels exist since Java 1.4 and I don't know why they aren't mentioned anywhere when dealing with the problem of replacing or inserting content in files. [FileChannels](http://docs.oracle.com/javase/6/docs/api/java/nio/channels/FileChannel.html) are fast, use them. Here's an example (ignoring exceptions and some other stuff): ``` public void insert(String filename, long offset, byte[] content) { RandomAccessFile r = new RandomAccessFile(new File(filename), "rw"); RandomAccessFile rtemp = new RandomAccessFile(new File(filename + "~"), "rw"); long fileSize = r.length(); FileChannel sourceChannel = r.getChannel(); FileChannel targetChannel = rtemp.getChannel(); sourceChannel.transferTo(offset, (fileSize - offset), targetChannel); sourceChannel.truncate(offset); r.seek(offset); r.write(content); long newOffset = r.getFilePointer(); targetChannel.position(0L); sourceChannel.transferFrom(targetChannel, newOffset, (fileSize - offset)); sourceChannel.close(); targetChannel.close(); } ```
Well, no, I don't believe there is a way to avoid overwriting existing content with a single, standard Java IO API call. If the files are not too large, just read the entire file into an ArrayList (an entry per line) and either rewrite entries or insert new entries for new lines. Then overwrite the existing file with new content, or move the existing file to a backup and write a new file. Depending on how sophisticated the edits need to be, your data structure may need to change. Another method would be to read characters from the existing file while writing to the edited file and edit the stream as it is read.
Inserting text into an existing file via Java
[ "", "java", "file", "file-io", "filesystems", "" ]
I've been told that the java class TreeMap uses an implementation of a RB tree. If this is the case, how does one do an inorder, preorder and postorder tree-walk on a TreeMap? Or is this not possible?
You wouldn't be able to do this with the TreeMap implemented in the Collections library. Here's an implementation of a [Red-Black Tree](https://www.java-tips.org/java-se-tips-100019/24-java-lang/1904-red-black-tree-implementation-in-java.html) in Java that you can look at though. Check out the `printTree()` methods to see how they walk the tree in sorted order. ``` /** * Print all items. */ public void printTree( ) { printTree( header.right ); } /** * Internal method to print a subtree in sorted order. * @param t the node that roots the tree. */ private void printTree( RedBlackNode t ) { if( t != nullNode ) { printTree( t.left ); System.out.println( t.element ); printTree( t.right ); } } ``` From that maybe you can write your own methods to traverse the tree in all three orders.
You can at least do the inorder walk using the iterator and a for each loop: ``` void inOrderWalk(TreeMap<K,V> treeMap) { //this will loop through the values in the map in sorted order (inorder traversal) for (Map.Entry<K,V> entry : treeMap.entrySet() { V value = entry.getValue(); K key = entry.getKey() } } ``` However, the other posters are right: Java doesn't expose any of the tree mechanics, so a preorder or postorder isn't possible at this view.
Java TreeMap sorting options?
[ "", "java", "binary-tree", "red-black-tree", "" ]
I've got mssql 2005 running on my personal computer with a database I'd like to run some python scripts on. I'm looking for a way to do some really simple access on the data. I'd like to run some select statements, process the data and maybe have python save a text file with the results. Unfortunately, even though I know a bit about python and a bit about databases, it's very difficult for me to tell, just from reading, if a library does what I want. Ideally, I'd like something that works for other versions of mssql, is free of charge and licensed to allow commercial use, is simple to use, and possibly works with ironpython.
I use [SQL Alchemy](http://www.sqlalchemy.org/) with cPython (I don't know if it'll work with IronPython though). It'll be pretty familiar to you if you've used Hibernate/nHibernate. If that's a bit too verbose for you, you can use [Elixir](http://elixir.ematia.de/trac/wiki), which is a thin layer on top of SQL Alchemy. To use either one of those, you'll need [pyodbc](http://pyodbc.sourceforge.net/), but that's a pretty simple install. Of course, if you want to write straight SQL and not use an ORM, you just need pyodbc.
Everyone else seems to have the cPython -> SQL Server side covered. If you want to use IronPython, you can use the standard ADO.NET API to talk to the database: ``` import clr clr.AddReference('System.Data') from System.Data.SqlClient import SqlConnection, SqlParameter conn_string = 'data source=<machine>; initial catalog=<database>; trusted_connection=True' connection = SqlConnection(conn_string) connection.Open() command = connection.CreateCommand() command.CommandText = 'select id, name from people where group_id = @group_id' command.Parameters.Add(SqlParameter('group_id', 23)) reader = command.ExecuteReader() while reader.Read(): print reader['id'], reader['name'] connection.Close() ``` If you've already got IronPython, you don't need to install anything else. Lots of docs available [here](http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlconnection.aspx) and [here](http://www.ironpython.info/index.php/Contents#Databases).
What's the simplest way to access mssql with python or ironpython?
[ "", "python", "sql-server", "ironpython", "" ]
Given the following class: ``` class TestClass { public void SetValue(int value) { Value = value; } public int Value { get; set; } } ``` I can do ``` TestClass tc = new TestClass(); Action<int> setAction = tc.SetValue; setAction.Invoke(12); ``` which is all good. Is it possible to do the same thing using the property instead of the method? Preferably with something built in to .net.
You could create the delegate using reflection : ``` Action<int> valueSetter = (Action<int>)Delegate.CreateDelegate(typeof(Action<int>), tc, tc.GetType().GetProperty("Value").GetSetMethod()); ``` or create a delegate to an anonymous method which sets the property; ``` Action<int> valueSetter = v => tc.Value = v; ``` Edit: used wrong overload for CreateDelegate(), need to use the one that takes and object as target. Fixed.
There are three ways of doing this; the first is to use GetGetMethod()/GetSetMethod() and create a delegate with Delegate.CreateDelegate. The second is a lambda (not much use for reflection!) [i.e. x=>x.Foo]. The third is via Expression (.NET 3.5). The lambda is the easiest ;-p ``` class TestClass { public int Value { get; set; } } static void Main() { Func<TestClass, int> lambdaGet = x => x.Value; Action<TestClass, int> lambdaSet = (x, val) => x.Value = val; var prop = typeof(TestClass).GetProperty("Value"); Func<TestClass, int> reflGet = (Func<TestClass, int>) Delegate.CreateDelegate( typeof(Func<TestClass, int>), prop.GetGetMethod()); Action<TestClass, int> reflSet = (Action<TestClass, int>)Delegate.CreateDelegate( typeof(Action<TestClass, int>), prop.GetSetMethod()); } ``` To show usage: ``` TestClass foo = new TestClass(); foo.Value = 1; Console.WriteLine("Via property: " + foo.Value); lambdaSet(foo, 2); Console.WriteLine("Via lambda: " + lambdaGet(foo)); reflSet(foo, 3); Console.WriteLine("Via CreateDelegate: " + reflGet(foo)); ``` Note that if you want the delegate pointing to the specific instance, you can use closures for the lambda, or the overload of CreateDelegate that accepts and instance.
Is there a delegate available for properties in C#?
[ "", "c#", ".net", "" ]
I distribute my application using a VS2008 install package, which normally works great. When I create new versions of the app, I go in and increment the `Version` property on the install package and verify the `RemovePreviousVersions` property is set to True. This works just fine most of the time - I just run the install package for the newer version and the older version is uninstalled and the newer version replaces it. However, occasionally the install package will run successfully, but when I start the program the old version starts up. Apparently the old version of the .exe is still present. I end up having to completely uninstall the software and install the new version, which always works, but is a pain. The file isn't in use as far as I can tell and the install package doesn't tell me to reboot. Any ideas about what's going on here?
Not a direct answer, but the key difference between an upgrade and an uninstall+ a reinstall is that any custom uninstall steps are not called in 2k8 but are in 2k5. This is referenced in [Visual Studio 2005 -> 2008/10 Service Installer Project Upgrade issue](https://stackoverflow.com/questions/370940/visual-studio-2008-service-installer-project-upgrade-issue) The other difference related to this is that in 2k8, the files get upgraded based on the version info resource - if your modules dont have newer versions, they dont get replaced. In some cases whether you strong name also has effects, but I'm pretty confident the last paragraph covers the issue you're seeing.
second is By using orca Orca is utility to modify msi files. You can download 'Orca' from following links. <http://www.softpedia.com/get/Authoring-tools/Setup-creators/Orca.shtml> Steps: ``` a. Install orca into your computer. b. Open orca c. Drag and drop your msi into orca UI d. Into left panel it will list the name of tables e. select property table f. go to right panel and right click g. click on 'Add Row' h. into 'Property' type REINSTALLMODE i. into 'Value' type amus j. save msi file k. and that's it ``` Now when you install it will overwrite all files.
.NET Install Package Sometimes Not Completely Removing Previous Versions
[ "", "c#", ".net", "visual-studio", "" ]
If I have something like a loop or a set of if/else statements, and I want to return a value from within the nest (see below), is the best way of doing this to assign the value to a field or property and return that? See below: ``` bool b; public bool ifelse(int i) { if(i == 5) { b = true; } else { b = false; } return b; } ```
Yes, that is good style. The alternative (which would be **bad**) would be to do this: ``` public bool ifelse(int i) { if(i == 5) { return true; } else { return false; } } ``` The reason multiple return points are regarded as bad style is that especially for larger methods it can be difficult to keep track of the program flow within a method because it could exit at **any** point. This can be a nightmare to debug. If you have a return variable that you assign to however, you can watch that variable and know exactly when it will be returned (from a single place). This isn't *always* the case, as with every stylistic point in programming there are good sides to it and bad sides.
what about ``` return i == 5; ```
Quick question about returning from a nested statement
[ "", "c#", "coding-style", "function-exit", "nested-statement", "" ]
I have a Repeater control on ASPX-page defined like this: ``` <asp:Repeater ID="answerVariantRepeater" runat="server" onitemdatabound="answerVariantRepeater_ItemDataBound"> <ItemTemplate> <asp:RadioButton ID="answerVariantRadioButton" runat="server" GroupName="answerVariants" Text='<%# DataBinder.Eval(Container.DataItem, "Text")%>'"/> </ItemTemplate> </asp:Repeater> ``` To allow select only one radio button in time I have used a trick form [this article](http://www.codeguru.com/csharp/csharp/cs_controls/custom/article.php/c12371/). But now when form is submitted I want to determine which radio button is checked. I could do this: ``` RadioButton checkedButton = null; foreach (RepeaterItem item in answerVariantRepeater.Items) { RadioButton control=(RadioButton)item.FindControl("answerVariantRadioButton"); if (control.Checked) { checkedButton = control; break; } } ``` but hope it could be done somehow simplier (maybe via LINQ to objects).
Since You are using javascript already to handle the radio button click event on the client, you could update a hidden field with the selected value at the same time. Your server code would then just access the selected value from the hidden field.
You could always use [`Request.Form`](http://msdn.microsoft.com/en-us/library/system.web.httprequest.form.aspx) to get the submitted radio button: ``` var value = Request.Form["answerVariants"]; ``` I think the submitted value defaults to the id of the `<asp:RadioButton />` that was selected, but you can always add a value attribute - even though it's not officially an `<asp:RadioButton />` property - and this will then be the submitted value: ``` <asp:RadioButton ID="answerVariantRadioButton" runat="server" GroupName="answerVariants" Text='<%# DataBinder.Eval(Container.DataItem, "Text")%>'" value='<%# DataBinder.Eval(Container.DataItem, "SomethingToUseAsTheValue")%>' /> ```
How to find checked RadioButton inside Repeater Item?
[ "", "asp.net", "javascript", "repeater", "radio-button", "" ]
I've got a bunch of legacy code that I need to write unit tests for. It uses pre-compiled headers everywhere so almost all .cpp files have a dependecy on stdafx.h which is making it difficult to break dependencies in order to write tests. My first instinct is to remove all these stdafx.h files which, for the most part, contain #include directives and place those #includes directly in the source files as needed. This would make it necessary to turn off pre-compiled headers since they are dependent on having a file like stdafx.h to determine where the pre-compiled headers stop. Is there a way to keep pre-compiled headers without the stdafx.h dependencies? Is there a better way to approach this problem?
Yes, there is a better way. The problem, IMHO, with the 'wizard style' of precompiled headers is that they encourage unrequired coupling and make reusing code harder than it should be. Also, code that's been written with the 'just stick everything in stdafx.h' style is prone to be a pain to maintain as changing anything in any header file is likely to cause the whole codebase to recompile every time. This can make simple refactoring take forever as each change and recompile cycle takes far longer than it should. A better way, again IMHO, is to use #pragma hdrstop and /Yc and /Yu. This enables you to easily set up build configurations that DO use precompiled headers and also build configurations that do not use precompiled headers. The files that use precompiled headers don't have a direct dependency on the precompiled header itself in the source file which enables them to be build with or without the precompiled header. The project file determines what source file builds the precompiled header and the #pragma hdrstop line in each source file determines which includes are taken from the precompiled header (if used) and which are taken directly from the source file... This means that when doing maintenance you would use the configuration that doesn't use precompiled headers and only the code that you need to rebuild after a header file change will rebuild. When doing full builds you can use the precompiled header configurations to speed up the compilation process. Another good thing about having the non-precompiled header build option is that it makes sure that your cpp files only include what they need and include everything that they need (something that is hard if you use the 'wizard style' of precompiled header. I've written a bit about how this works here: <http://www.lenholgate.com/blog/2004/07/fi-stlport-precompiled-headers-warning-level-4-and-pragma-hdrstop.html> (ignore the stuff about /FI) and I have some example projects that build with the #pragma hdrstop and /Yc /Yu method here: <http://www.lenholgate.com/blog/2008/04/practical-testing-16---fixing-a-timeout-bug.html> . Of course, getting from the 'wizard style' precompiled header usage to a more controlled style is often non-trivial...
When you normally use precompiled headers, "stdafx.h" serves 2 purposes. It defines a set of stable, common include files. Also in each .cpp file, it serves as a marker as where the precompiled headers end. Sounds like what you want to do is: * Leave precompiled header turned on. * Leave the "stdafx.h" include in each .cpp file. * Empty out the includes from "stdafx.h". * For each .cpp file, figure out which includes were needed from the old "stdafx.h". Add these before the #include "stdafx.h" in each .cpp file. So now you have the minimal set of dependancies, and you still are using precompiled headers. The loss is that you are not precompiling your common set of headers only once. This would be a big hit for a full rebuild. For development mode, where you are only recompiling a few files at a time, it would be less of a hit.
Is there a way to use pre-compiled headers in VC++ without requiring stdafx.h?
[ "", "c++", "unit-testing", "dependencies", "precompiled-headers", "stdafx.h", "" ]
Does anyone know in .Net 2.0 - .Net 3.5 how to load a jpeg into a System.Windows.Forms.WebControl as a byte-array and with the right mimetypes set so it will show? Something like: ``` webBrowser1.DocumentStream = new MemoryStream(File.ReadAllBytes("mypic.jpg")); webBrowser1.DocumentType = "application/jpeg"; ``` The webBrowser1.DocumentType seems to be read only, so I do not know how to do this. In general I want to be able to load any kind of filesource with a mimetype defined into the browser to show it. Solutions with writing temp files are not good ones. Currently I have solved it with having a little local webserver socket listener that delivers the jpeg I ask for with the right mimetype. UPDATE: Since someone deleted a answer-my-own question where I had info that others could use, I will add it as an update instead. (to those who delete that way, please update the questions with the important info). Sample solution in C# here that works perfectly: <http://www.codeproject.com/KB/aspnet/AspxProtocol.aspx>
You have to implement an async pluggable protocol, e.g. IClassFactory, IInternetProtocol... Then you use CoInternetGetSession to register your protocol. When IE calls your implementation, you can serve your image data from memory/provide mime type. It's a bit tedious, but doable. Look at IInternetProtocol and pluggable protocols documentation on [MSDN](http://msdn.microsoft.com/en-us/library/aa767743(VS.85).aspx).
You cannot do it. You cannot stuff images into Microsoft's web-browser control. The limitation comes from the IWebBrowser control itself, which .NET wraps up.
How do I get a C# WebBrowser control to show jpeg files (raw)?
[ "", "c#", ".net", "webbrowser-control", "" ]
In C++, is the return type considered part of the function signature? and no overloading is allowed with just return type modified.
Normal functions do not include the return type in their signature. (*note*: i've rewritten this answer, and the comments below don't apply to this revision - see the edit-history for details). ### Introduction However, the matter about functions and function declarations in the Standard is complicated. There are two layers that have to be considered: * Declarations * Entities The so-called *function declaration* may declare a function entity or a template entity. If a function entity is declared, then you either have to do with an explicit specialization of a function template (with all arguments specified), or a declaration of an ordinary function. If a template entity is declared, then you are declaring a primary function template, or an explicit specialization where some arguments are not specified. (This is very similar to the relation of "object declaration" and objects or references: The former may declare either an object or a reference. So an *object declaration* may not necessarily declare an object!). The Standard defines the signature of a function to include the following at `1.3.10`: > The types of its parameters and, if the function is a class member, the cv- qualifiers (if any) on the function itself and the class in which the member function is declared. The signature of a function template specialization includes the types of its template arguments. (14.5.5.1) It's missing the return type in this definition, which *is* part of the signature of a function template specialization (i.e a function declaration that declares a function which is a specialization of a template), as pointed out by `14.5.5.1` (recent C++0x working papers fixed that already to mention the return type in `1.3.10` too): > The signature of a function template specialization consists of the signature of the function template and of the actual template arguments (whether explicitly specified or deduced). > > The signature of a function template consists of its function signature, its return type and its template parameter list. ### So what exactly does a signature contain, again? So, when we ask about the signature of a *function*, we have to give two answers: * For functions that are specializations of function templates, the signature includes the return type. * For functions that are not specializations, the return type is not part of the signature. Notice, however, that the return type, in any case, *is* a significant part of the type of a function. That is, the following is not valid: ``` void f(); int (*pf)() = &f; // different types! ``` ### When is an overload invalid if only the return type differs? Major compilers currently reject the following code: ``` int f(); double f(); // invalid ``` But accept the following code: ``` template<typename T> int f(); template<typename T> double f(); // invalid? ``` However, the **Standard does forbid a function declaration that only differs in the return type** (when defining when an overload is valid, and when not). It does not define precisely what "differs only by return type" means, though. --- Standard paragraph references: * When can a function declaration be overloaded: `13.1` * What is a function declaration: `7/2` and `7/5` * What is the signature of a function template/specialization: `14.5.5.1` For reference, here is what the most recent C++0x draft n3000 says about "signature" in `1.3.11`, which is much more complete in its coverage of the different type of entities: > the name and the parameter type list (8.3.5) of a function, as well as the class or namespace of which it is a member. If a function or function template is a class member its signature additionally includes the cv-qualifiers (if any) and the ref-qualifier (if any) on the function or function template itself. The signature of a function template additionally includes its return type and its template parameter list. The signature of a function template specialization includes the signature of the template of which it is a specialization and its template arguments (whether explicitly specified or deduced). [ Note: Signatures are used as a basis for name mangling and linking. — end note ]
It depends if the function is a *function template* or not. In **C++ Templates -- the complete guides**, Jusuttis provides a different definition of that given in the C++ standard, but with equivalent consequences: We define the signature of a function as the the following information: 1. The *unqualified name* of the function 2. The *class* or *namespace* scope of that name, and if the name has internal linkage, the translation unit in which the name is declared 3. The `const`, `volatile`, or `const volatile` qualification of the function 4. The *types* of the function parameters 5. **its return *type*, if the function is generated from a function template** 6. The *template parameters* and the *template arguments*, if the function is generated from a function template As **litb** suggested, it's worth to clarify why the return type is part of the signature of a template function. > Functions can coexist in a program if > they have distinct signatures. . That said, if the return type is a template parameter: ``` template <typename T> T foo(int a) {return T();} ``` it's possibile to instantiate two function which differ only in the return type: ``` foo<int>(0); foo<char>(0); ``` Not only: as rightly reported by **litb**, it is also possible to overload two template functions, which differ only in the return type, even if the return type is not a dependent name. Here's his example: ``` template<class T> int foo(T) {} template<class T> bool foo(T) {} // at the instantiation point it is necessary to specify the cast // in order not to face ambiguous overload ((int(*)(char))foo<char>)('a'); ```
Is the return type part of the function signature?
[ "", "c++", "function", "" ]
Sorry for the bad title, but I couldn't think of a better one. I'm having a class A and a class B which is kind of a sub class of A, like so: (Is there actually a correct name for it? Isn't "sub class" reserved for inheritance?) ``` class A { int i = 0; class B { int j = 1; } } class Test { public static void main() { A a = new A(); B b = a.new B(); A c = ??? b ??? // get "a" back } } ``` From B every property of A can be accessed, therefore both, a.i and b.i, return 0. Now, I'm wondering whether it's somehow possible to retrieve the original object of type A out of b, as b contains everything that a contains? Simple casting apparently doesn't do the trick. Second one: ``` class A { void print() { System.out.println("This is class A."); } class B { void print() { // <--- How to access print() of class A (like this.A.print() or smth)? System.out.println("This is class B."); } } } ``` You could alternatively also provide me with some good resources on this topic, as I've been too stupid to find a good one so far. Thanks in advance. :)
There doesn't seem to be a way to access the outer class from outside. But you can do it like this: ``` class A { int i = 0; class B { final A outer = A.this; int j = 1; } } class Test { public static void main() { A a = new A(); A.B b = a.new B(); A c = b.outer // get "a" back } } ``` `ClassName.this` will be the instance of the outerclass associated with the instance of an inner class.
You can access it with the `ParentClass.this` syntax from within the inner class. e.g. ``` public class Outter { class Inner { public Outter getOutter() { return Outter.this; } } public Inner getInner(){ return new Inner(); } } class Runner{ public static void main(String[] args){ Outter out = new Outter(); Outter.Inner inner = out.getInner(); System.out.println(inner.getOutter().toString()); } } ```
Two questions on inner classes in Java (class A { class B { } })
[ "", "java", "class", "" ]
Simple case: i put a DataTable in Cache ``` DataTable table = SomeClass.GetTable(); Cache["test"] = table; then in later calls i use DataTable table = (DataTable)Cache["test"]; ``` now the question is: should i call table.dispose() on each call, though its stored in the Cache? Means the object is always the same? Or will Cache create a copy on each time? thx :)
All you are doing is storing a pointer in cache... The actual "table" is still on the heap, where all .Net reference types are stored... You are not making a copy of it... The variable in cache just acts to stop the garbage collector from erasing the object on the heap... and no, you don't want to call dispose until the actual object is no longer required.
i believe that you should only call Dispose once when you are completely done with the datatable; calling Dispose changes the state of the object. note that 'cached' does not always mean 'copied'!
Do I have to call dispose after each use though datatable is stored in cache?
[ "", "c#", "asp.net", "caching", "datatable", "dispose", "" ]
I have a simple WPF application with a menu. I need to add menu items dynamically at runtime. When I simply create a new menu item, and add it onto its parent MenuItem, it does not display in the menu, regardless of if UpdateLayout is called. What must happen to allow a menu to have additional items dynamically added at runtime? Note: the following code doesn't work. ``` MenuItem mi = new MenuItem(); mi.Header = "Item to add"; mi.Visibility = Visibility.Visible; //addTest is a menuitem that exists in the forms defined menu addTest.Items.Add(mi); addTest.UpdateLayout(); ``` At the moment, the default menu items are defined in the xaml file. I want to add additional menu items onto this menu and its existing menu items. However, as stated, the above code does nothing.
``` //Add to main menu MenuItem newMenuItem1 = new MenuItem(); newMenuItem1.Header = "Test 123"; this.MainMenu.Items.Add(newMenuItem1); //Add to a sub item MenuItem newMenuItem2 = new MenuItem(); MenuItem newExistMenuItem = (MenuItem)this.MainMenu.Items[0]; newMenuItem2.Header = "Test 456"; newExistMenuItem.Items.Add(newMenuItem2); ```
I have successfully added menu items to a pre-defined menu item. In the following code, the LanguageMenu is defined in design view in th xaml, and then added the sub items in C#. XAML: ``` <MenuItem Name="LanguageMenu" Header="_Language"> <MenuItem Header="English" IsCheckable="True" Click="File_Language_Click"/> </MenuItem> ``` C#: ``` // Clear the existing item(s) (this will actually remove the "English" element defined in XAML) LanguageMenu.Items.Clear(); // Dynamically get flag images from a specified folder to use for definingthe menu items string[] files = Directory.GetFiles(Settings.LanguagePath, "*.png"); foreach (string imagePath in files) { // Create the new menu item MenuItem item = new MenuItem(); // Set the text of the menu item to the name of the file (removing the path and extention) item.Header = imagePath.Replace(Settings.LanguagePath, "").Replace(".png", "").Trim("\\".ToCharArray()); if (File.Exists(imagePath)) { // Create image element to set as icon on the menu element Image icon = new Image(); BitmapImage bmImage = new BitmapImage(); bmImage.BeginInit(); bmImage.UriSource = new Uri(imagePath, UriKind.Absolute); bmImage.EndInit(); icon.Source = bmImage; icon.MaxWidth = 25; item.Icon = icon; } // Hook up the event handler (in this case the method File_Language_Click handles all these menu items) item.Click += new RoutedEventHandler(File_Language_Click); // Add menu item as child to pre-defined menu item LanguageMenu.Items.Add(item); // Add menu item as child to pre-defined menu item } ```
WPF: How can you add a new menuitem to a menu at runtime?
[ "", "c#", "wpf", "" ]
When I call a static method like: ``` Something.action(); ``` Since a instance isn't created how long will the Class of the static method be held in memory? If I call the same method will the Class be reloaded for each call since no instance exists? And are only individual static methods loaded when called or are all the methods and static methods of a Class loaded into memory even though only one static method maybe used?
Unless you have configured garbage collection of permgenspace, the class stays in memory until the vm exits. The full class is loaded with all static methods.
The class stays in memory till the classloader that loaded that class stays in memory. So, if the class is loaded from the system class loader, the class never gets unloaded as far as I know. If you want to unload a class, you need to: 1. Load the class and all the classes that refer to that class using a custom classloader 2. After you are done with that class, release all references to the class - ie make sure there are no object instances of that class around 3. Unload the class and all classes referring to it by releasing the custom classloader instance that loaded those classes.
Java: `static` Methods
[ "", "java", "static", "methods", "" ]
In other words, can `fn()` know that it is being used as `$var = fn();` rather than as `fn();`? A use case would be to `echo` the return value in the latter case but to `return` it in the former. Can this be done without passing a parameter to the function to declare which way it is being used?
Many PHP functions do this by passing a boolean value called $return which returns the value if $return is true, or prints the value if $return is false. A couple of examples are [print\_r()](http://php.net/print_r) and [highlight\_file()](http://php.net/highlight_file). So your function would look like this: ``` function fn($return=false) { if ($return) { return 'blah'; } else { echo 'blah'; } } ``` Any other way will not be good programming style.
No, and it shouldn't. It's a pretty basic premise of the language that functions are unaware of the context in which they are used. This allows you to decompose your application, because each part (function) is completely isolated from its surroundings. That said, what you can do about this particular use-case, is to tturn on output buffering. By default `echo` will send data to stdout, but you can set a buffer, which will capture the output into a variable instead. For example: ``` function foo() { echo "Hello World"; } foo(); // will output "Hello World" ob_start(); foo(); $foo = ob_get_clean(); // will assign the string "Hello World" into the variable $foo ``` In addition to that, it is generally considered bad style to have functions output directly. You should generally return a string and leave it for the top level of your script to output. Ideally there should be just one single echo statement in your entire application.
PHP: Can a function know if it's being assigned as a value?
[ "", "php", "function", "" ]
Does anyone know if there's a way to automatically expand a list in Python, separated by commas? I'm writing some Python code that uses the MySQLdb library, and I'm trying to dynamically update a list of rows in a MySQL database with certain key values. For instance, in the code below, I'd like to have the numeric values in the record\_ids list expand into a SQL "`IN`" clause. ``` import MySQLdb record_ids = [ 23, 43, 71, 102, 121, 241 ] mysql = MySQLdb.connect(user="username", passwd="secret", db="apps") mysql_cursor = mysql.cursor() sqlStmt="UPDATE apps.sometable SET lastmod=SYSDATE() where rec_id in ( %s )" mysql_cursor.execute( sqlStmt, record_ids ) mysql.commit() ``` Any help would be appreciated!
try: ``` ",".join( map(str, record_ids) ) ``` `",".join( list_of_strings )` joins a list of string by separating them with commas if you have a list of numbers, `map( str, list )` will convert it to a list of strings
I do stuff like this (to ensure I'm using bindings): ``` sqlStmt=("UPDATE apps.sometable SET lastmod=SYSDATE() where rec_id in (%s)" % ', '.join(['?' for n in record_ids])) mysql_cursor.execute(sqlStmt, record_ids) mysql.commit() ``` This works for all dynamic lists you want to bind without leaving you susceptible to SQL injection attacks.
Automagically expanding a Python list with formatted output
[ "", "python", "list", "mysql", "" ]
I know that I am supposed to use `delete []` after I use `new []`, so using `auto_ptr` with `new []` is not such a bright idea. However, while debugging `delete []` (using Visual Studio 2005), I noticed that the call went into a function that looked like this: ``` void operator delete[]( void * p ) { RTCCALLBACK(_RTC_Free_hook, (p, 0)) operator delete(p); } ``` Does this mean, the `[]` syntax is lost on Visual C++? If so, why? Is it to relieve the developer from the burden of remembering the right syntax?
Consider this code: ``` class DeleteMe { public: ~DeleteMe() { std::cout << "Thanks mate, I'm gone!\n"; } }; int main() { DeleteMe *arr = new DeleteMe[5]; delete arr; return 0; } ``` If you run that in VS2005 it will print: ``` Thanks mate, I'm gone! ``` If you change `main()` to correctly adhere to the C++ standard: ``` int main() { DeleteMe *arr = new DeleteMe[5]; delete[] arr; return 0; } ``` It will print: ``` Thanks mate, I'm gone! Thanks mate, I'm gone! Thanks mate, I'm gone! Thanks mate, I'm gone! Thanks mate, I'm gone! ``` Don't shoot yourself in the foot. VS2005 will **NOT** do the correct thing if you mismatch different flavors of new/delete. Neither will any other C++ standard conformant compiler. There's some compiler magic going on around `operator new` and `operator delete` (and their different flavors), basically the call to the ctors and dtors are added behind the scenes. This magic depends on those small brackets [], so don't lose them or you'll lose the magic.
I guess it's just an implementation detail. Their heap allocator works the same way when freeing arrays and pointers. But since the standard allows implementations to have different algorithms for the two cases, you really shouldn't assume that `delete` and `delete[]` do the same thing. The behaviour might even change between compiler versions.
delete and delete [] the same in Visual C++?
[ "", "c++", "visual-c++", "" ]
For what I can read, it is used to dispatch a new thread in a swing app to perform some "background" work, but what's the benefit from using this rather than a "normal" thread? Is not the same using a new Thread and when it finish invoke some GUI method using SwingUtilities.invokeLater?... What am I missing here? <http://en.wikipedia.org/wiki/SwingWorker> <http://java.sun.com/products/jfc/tsc/articles/threads/threads2.html>
Yes, you can accomplish what a SwingWorker does with vanilla threads + invokeLater. SwingWorker provides a predictable, integrated way to accomplish tasks on a background thread and report result on the EDT. SwingWorker additionally adds support for intermediate results. Again, you can do all of this yourself but sometimes it's easy to use the integrated and predictable solution especially when it comes to concurrency.
A code example: ``` import org.jdesktop.swingx.util.SwingWorker; // This one is from swingx // another one is built in // since JDK 1.6 AFAIK? public class SwingWorkerTest { public static void main( String[] args ) { /** * First method */ new Thread() { public void run() { /** Do work that would freeze GUI here */ final Object result = new Object(); java.awt.EventQueue.invokeLater( new Runnable() { public void run() { /** Update GUI here */ } } ); } }.start(); /** * Second method */ new SwingWorker< Object , Object >() { protected Object doInBackground() throws Exception { /** Do work that would freeze GUI here */ return null; } protected void done() { try { Object result = get(); /** Update GUI here */ } catch ( Exception ex ) { ex.printStackTrace(); if ( ex instanceof java.lang.InterruptedException ) return; } } }.execute(); } } ``` The choice always depends on personal preference and use case. The second method has an advantage when refactoring. You can more easily convert the anonymous class to an inner class when the method it's used in is too large. My personal preference goes to the second, for we have built a framework where SwingWorkers can be added and are executed one after the other...
What is the rationale of SwingWorker?
[ "", "java", "multithreading", "swing", "swingworker", "" ]
I just came over this syntax in some of the questions in this forum, but Google and any other searchengine tends to block out anything but letters and number in the search so it is impossible to search out "=>". So can anyone tell me what it is and how it is used?
It's the lambda operator. From C# 3 to C# 5, this was only used for [lambda expressions](http://msdn.microsoft.com/en-us/library/bb397687.aspx). These are basically a shorter form of the [anonymous methods](http://msdn.microsoft.com/en-us/library/0yw3tz5k.aspx) introduced in C# 2, but can also be converted into [expression trees](http://msdn.microsoft.com/en-us/library/bb397951.aspx). As an example: ``` Func<Person, string> nameProjection = p => p.Name; ``` is equivalent to: ``` Func<Person, string> nameProjection = delegate (Person p) { return p.Name; }; ``` In both cases you're creating a delegate with a `Person` parameter, returning that person's name (as a string). In C# 6 the same syntax is used for *expression-bodied members*, e.g. ``` // Expression-bodied property public int IsValid => name != null && id != -1; // Expression-bodied method public int GetHashCode() => id.GetHashCode(); ``` See also: * [What's the difference between anonymous methods (C# 2.0) and lambda expressions (C# 3.0)](https://stackoverflow.com/questions/208381/whats-the-difference-between-anonymous-methods-c-20-and-lambda-expressions-c-30) * [What is a Lambda?](https://stackoverflow.com/questions/150129/what-is-a-lambda) * [C# Lambda expression, why should I use this?](https://stackoverflow.com/questions/167343/c-lambda-expression-why-should-i-use-this) (And indeed many similar questions - try the [lambda](https://stackoverflow.com/questions/tagged/lambda) and [lambda-expressions](https://stackoverflow.com/questions/tagged/lambda-expressions) tags.)
It's a much more concise form of method notation. The following are roughly equivalent: ``` // explicit method int MyFunc(int x) { return x; } // anonymous (name-less) method // note that the method is "wrapped" up in a hidden object (Delegate) this way // so there is a very tiny bit of overhead compared to an explicit method // (though it's really the assignment that causes that and would also happen // if you assigned an explicit method to a reference) Func<int, int> MyFunc = delegate (int x) { return x; }; // lambda expression (also anonymous) // basically identical to anonymous method, // except with everything inferred as much as possible, intended to be minimally verbose Func<int, int> MyFunc = x => x; // and => is now also used for "expression-bodied" methods // which let you omit the return keyword and braces if you can evaluate // to something in one line int MyFunc(int x) => x; ``` Think of a lambda expression as saying, "given something, return something". In the example above, the lambda expression `x => x` says "given x, return x", although lambda expressions don't necessarily need to return something, in which case you might read them as "given x, do something with x". Also note that there are kind of three things called "delegate" which can be very confusing at first. An anonymous method uses the `delegate` keyword, but defines a method with no name: ``` Func<int, int> = delegate (int x) { return x; }; ``` Assigning a method (anonymous, explicit, or lambda) to a reference causes a hidden `Delegate` wrapper object to be created that is what allows the method to be referred to. (Basically a sort of "managed function pointer".) And then, you can also declare *named method **signatures*** using the `delegate` keyword as well: ``` public delegate int TestFunc(int x, int y); TestFunc myFunc = delegate (int x, int y) { return x + y; }; ``` This declares a named signature `TestFunc` that takes two `int`s and returns an `int`, and then declares a delegate reference of that type which is then assigned an anonymous method with matching signature.
What does the '=>' syntax in C# mean?
[ "", "c#", "syntax", "" ]
Is there a way to change the connection string of a DataBase object in Enterprise Library at runtime? I've found [this](http://blog.benday.com/archive/2005/05/05/357.aspx) link but its a little bit outdated (2005) I've also found [this](https://stackoverflow.com/questions/63546/vs2005-c-programmatically-change-connection-string-contained-in-appconfig) but it seems to apply to .Net in general, I was wondering if there was something that could be done specifically for EntLib. I was just passing the connection string name to the CreateDatabase() method in DatabaseFactory object and that worked til yesterday that my project manager asked me to support more than one database instance. It happens that we have to have one database per state (one for CA, one for FL, etc...) so my software needs to cycle through all databases and do something with data but it will use the same config file. Thanks in advance.
If you take a look at "[Enterprise Library Docs - Adding Application Code](http://msdn.microsoft.com/en-us/library/dd139953.aspx)" it says this: > "If you know the connection string for > the database you want to create, you > can bypass the application's > configuration information and use a > constructor to directly create the > Database object. Because the Database > class is an abstract base class, you > must construct one of its derived > types. The derived Database type > determines the ADO.NET data provider. > For example, the SqlDatabase class > uses the SqlClientFactory provider, > the SqlCeDatabase class uses the > SqlCeProviderFactory provider, and the > OracleDatabase class uses the > OracleClientFactory provider. It is > your responsibility to construct the > appropriate type of Database class for > the connection string." It then goes on to give some examples. This would suggest that you should not be using the DatabaseFactory and you should be creating a new Database class for each of your different connections.
look at this:[Open Microsoft.practices.EnterpriseLibrary database with just a connection string](https://stackoverflow.com/questions/401339/open-microsoft-practices-enterpriselibrary-database-with-just-a-connection-string) just use this follow code, you can programming create database at runtime ``` database mydb = new EnterpriseLibrary.Data.Sql.SqlDatabase("connection string here"); ``` It's solved my problem. I have a single web app using many database, according to the different subdomain in the url to connect to the different database. such as: * abc.test.com ------>using the Db\_projectABC * def.test.com ------>using the db\_ProjectDEF I use url-rewrite to parse the subdomain name, and use the subdomain name to chose it's database connection string which stored in the main database. Thanks
Changing connection string at runtime in Enterprise Library
[ "", "c#", ".net", "database", "configuration", "enterprise-library", "" ]
I am attempting to write a component in C# to be consumed by classic ASP that allows me to access the indexer of the component (aka default property). For example: C# component: ``` public class MyCollection { public string this[string key] { get { /* return the value associated with key */ } } public void Add(string key, string value) { /* add a new element */ } } ``` ASP consumer: ``` Dim collection Set collection = Server.CreateObject("MyCollection ") Call collection.Add("key", "value") Response.Write(collection("key")) ' should print "value" ``` Is there an attribute I need to set, do I need to implement an interface or do I need to do something else? Or this not possible via COM Interop? The purpose is that I am attempting to create test doubles for some of the built-in ASP objects such as Request, which make use of collections using these default properties (such as `Request.QueryString("key")`). Alternative suggestions are welcome. Update: I asked a follow-up question: [Why is the indexer on my .NET component not always accessible from VBScript?](https://stackoverflow.com/questions/317759/why-is-the-indexer-on-my-net-component-not-always-accessible-from-vbscript)
Try setting the DispId attribute of the property to be 0, as described here in the [MSDN documentation](http://msdn.microsoft.com/en-us/library/system.runtime.interopservices.dispidattribute(VS.71).aspx).
Thanks to Rob Walker's tip, I got it working by adding the following method and attribute to MyCollection: ``` [DispId(0)] public string Item(string key) { return this[key]; } ``` Edit: See [this better solution](https://stackoverflow.com/a/311946/3195477) which uses an indexer.
Exposing the indexer / default property via COM Interop
[ "", "c#", "collections", "asp-classic", "vbscript", "com-interop", "" ]
I have been looking at improving my ASP.NET page performance. Is it worth changing `autoeventwireup` from `true` to `false` and adding event handlers, or is the performance penalty very small? This is an ASP.NET 2.0 project.
The wireup isn't done at compile-time. It's done at runtime. As described in this article: <http://odetocode.com/Blogs/scott/archive/2006/02/16/2914.aspx> There IS a performance penalty because of the calls to CreateDelegate which must be made every time a page has been created. The performance hit is probably negligible, but it does exist.
From MSDN article. [Performance Tips and Tricks in .NET Applications](http://msdn.microsoft.com/en-us/library/ms973839.aspx) **Avoid the Autoeventwireup Feature** Instead of relying on autoeventwireup, override the events from Page. For example, instead of writing a Page\_Load() method, try overloading the public void OnLoad() method. This allows the run time from having to do a CreateDelegate() for every page. Knowledge Base article: [How to use the AutoEventWireup attribute in an ASP.NET Web Form by using Visual C# .NET](http://kbalertz.com/324151/AutoEventWireup-attribute-using-Visual.aspx) **When to avoid setting the value of the AutoEventWireup attribute to true** *If performance is a key consideration, do not set the value of the AutoEventWireup attribute to true.* The AutoEventWireup attribute requires the ASP.NET page framework to make a call to the CreateDelegate function for every ASP.NET Web Form page. Instead of using automatic hookup, you must manually override the events from the page.
What is the performance cost of autoeventwireup?
[ "", "c#", "asp.net", "performance", "" ]
I am a PHP developer who is kind of in a pickle. I'm trying to locate and/or build an API capable of speaking to Hotmail, Yahoo and GMAIL in order to retrieve contact lists (with the user's consent, of course). The one I'm having the most trouble finding is a Hotmail API. Where would I start to look as far as finding either a working, stable API or the steps I could take to developing one for hotmail? Is there one that covers all of these bases that I could implement? Any help would be greatly appreciated! Thanks! EDIT: I did manage to get a few services up, however, I've been using Open Inviter for at least one client project, and it seems to perform well.
Some pointers: * Gmail: [Google Contacts Data API](http://code.google.com/apis/contacts/) * Yahoo: + [Address Book API](http://developer.yahoo.com/addressbook/) **(deprecated)** + [Contacts API](http://developer.yahoo.com/social/rest_api_guide/contact_api.html) * Hotmail: [Windows Live Contacts API](http://msdn.microsoft.com/en-us/library/bb463989.aspx-) Most of the scripts, etc. I found didn't really work. There's a commercial one which uses scraping to retrieve the contacts but I think those attempts are rather flawed. The above links should give you an example of how to access the address books on each service.
Plaxo has an [API widget](http://www.plaxo.com/api/widget) to import contacts from Gmail, Yahoo, AOL and Hotmail. You can view a demo of it in action [here](http://www.plaxo.com/api/widget_demo). It previously had a small issue with IE7 (last checked half a year ago), but if its resolved it might suite your needs.
PHP APIs for Hotmail, Gmail and Yahoo?
[ "", "php", "api", "gmail", "yahoo", "hotmail", "" ]
Is there a way to prematurely abort a transaction? Say, I have sent a command to the database which runs five minutes and after four, I want to abort it. Does JDBC define a way to send a "stop whatever you are doing on this connection" signal to the DB?
As mentioned by james, [Statement.cancel()](https://docs.oracle.com/javase/7/docs/api/java/sql/Statement.html#cancel()) will cancel the execution of a running Statement (select, update, etc). The JDBC docs specifically say that Statement.cancel() is safe to run from another thread and even suggests the usage of calling it in a timeout thread. After canceling the statement, you're still stuck with the job of rolling back the transaction. That is *not* documented as being safe to run from another thread. The [Connection.rollback()](https://docs.oracle.com/javase/7/docs/api/java/sql/Connection.html#rollback()) should happen in the main thread doing all the other JDBC calls. You can handle that after the canceled Statement.execute...() call completes with a JDBCException (due to the cancel).
I am guessing what you want to do is prevent your application blocking on long running queries / transactions. To this end, JDBC supports the concept of a query time out. You can set the query timeout using this: ``` java.sql.Statement.setQueryTimeout(seconds) ``` And handle the `SQLException` thrown by the `execute()` method by rolling back the transaction (of course, that would only work if you have autocommit set to false, and your JDBC driver supports Statement.cancel()).
How can I abort a running JDBC transaction?
[ "", "java", "jdbc", "" ]
I need to write a tool in C++ to determine the changed bits in a file compared against another file for replication. What would be the best method of accomplishing this? I don't have a specific OS or library in mind, I'm open to suggestions. My primary goal is reducing the amount of network traffic involved in replicating.
Look at rsync - it splits the file into blocks, calculates a checksum for each block, and transmits only the checksum to determine if there are any changesto the destination before transmitting the block data only if necessary.
If you can't use rsync as is, check [librsync](http://librsync.sourceforge.net/). It's old, but the code is easy to read and improve.
Best method to determine changed data in C++
[ "", "c++", "file", "compare", "replication", "librsync", "" ]
I've been using the idiom below for some time now. And it seems to be the most wide-spread, at least on the sites I've visited. Is there a better/different way to read a file into a string in Java? ``` private String readFile(String file) throws IOException { BufferedReader reader = new BufferedReader(new FileReader (file)); String line = null; StringBuilder stringBuilder = new StringBuilder(); String ls = System.getProperty("line.separator"); try { while((line = reader.readLine()) != null) { stringBuilder.append(line); stringBuilder.append(ls); } return stringBuilder.toString(); } finally { reader.close(); } } ```
## Read all text from a file Java 11 added the [readString()](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/nio/file/Files.html#readString(java.nio.file.Path,java.nio.charset.Charset)) method to read small files as a `String`, preserving line terminators: ``` String content = Files.readString(path, encoding); ``` For versions between Java 7 and 11, here's a compact, robust idiom, wrapped up in a utility method: ``` static String readFile(String path, Charset encoding) throws IOException { byte[] encoded = Files.readAllBytes(Paths.get(path)); return new String(encoded, encoding); } ``` ## Read lines of text from a file Java 7 added a [convenience method to read a file as lines of text,](https://docs.oracle.com/javase/7/docs/api/java/nio/file/Files.html#readAllLines%28java.nio.file.Path,%20java.nio.charset.Charset%29) represented as a `List<String>`. This approach is "lossy" because the line separators are stripped from the end of each line. ``` List<String> lines = Files.readAllLines(Paths.get(path), encoding); ``` Java 8 added the [`Files.lines()`](https://docs.oracle.com/javase/8/docs/api/java/nio/file/Files.html#lines-java.nio.file.Path-java.nio.charset.Charset-) method to produce a `Stream<String>`. Again, this method is lossy because line separators are stripped. If an `IOException` is encountered while reading the file, it is wrapped in an [`UncheckedIOException`](https://docs.oracle.com/javase/8/docs/api/java/io/UncheckedIOException.html), since `Stream` doesn't accept lambdas that throw checked exceptions. ``` try (Stream<String> lines = Files.lines(path, encoding)) { lines.forEach(System.out::println); } ``` This `Stream` does need a [`close()`](https://docs.oracle.com/javase/8/docs/api/java/util/stream/BaseStream.html#close--) call; this is poorly documented on the API, and I suspect many people don't even notice `Stream` has a `close()` method. Be sure to use an ARM-block as shown. If you are working with a source other than a file, you can use the [`lines()`](https://docs.oracle.com/javase/8/docs/api/java/io/BufferedReader.html#lines--) method in `BufferedReader` instead. ## Memory utilization If your file is small enough relative to your available memory, reading the entire file at once might work fine. However, if your file is too large, reading one line at a time, processing it, and then discarding it before moving on to the next could be a better approach. Stream processing in this way can eliminate the total file size as a factor in your memory requirement. ## Character encoding One thing that is missing from the sample in the original post is the character encoding. This encoding generally can't be determined from the file itself, and requires meta-data such as an HTTP header to convey this important information. The [`StandardCharsets`](https://docs.oracle.com/javase/7/docs/api/java/nio/charset/StandardCharsets.html) class defines some constants for the encodings required of all Java runtimes: ``` String content = readFile("test.txt", StandardCharsets.UTF_8); ``` The platform default is available from [the `Charset` class](https://docs.oracle.com/javase/7/docs/api/java/nio/charset/Charset.html#defaultCharset%28%29) itself: ``` String content = readFile("test.txt", Charset.defaultCharset()); ``` There are some special cases where the platform default is what you want, but they are rare. You should be able justify your choice, because the platform default is not portable. One example where it might be correct is when reading standard input or writing standard output. --- Note: This answer largely replaces my Java 6 version. The utility of Java 7 safely simplifies the code, and the old answer, which used a mapped byte buffer, prevented the file that was read from being deleted until the mapped buffer was garbage collected. You can view the old version via the "edited" link on this answer.
If you're willing to use an external library, check out [Apache Commons IO](https://commons.apache.org/proper/commons-io/) (200KB JAR). It contains an [`org.apache.commons.io.FileUtils.readFileToString()`](https://commons.apache.org/proper/commons-io/javadocs/api-release/org/apache/commons/io/FileUtils.html#readFileToString-java.io.File-java.nio.charset.Charset-) method that allows you to read an entire `File` into a `String` with one line of code. Example: ``` import java.io.*; import java.nio.charset.*; import org.apache.commons.io.*; public String readFile() throws IOException { File file = new File("data.txt"); return FileUtils.readFileToString(file, StandardCharsets.UTF_8); } ```
How do I create a Java string from the contents of a file?
[ "", "java", "string", "file", "file-io", "io", "" ]
I am using the .NET 3.5 SP1 framework and I've implemented URL routing in my application. I was getting javascript errors: `Error: ASP.NET Ajax client-side framework failed to load. Resource interpreted as script but transferred with MIME type text/html. ReferenceError: Can't find variable: Sys` Which I believe is because my routing is picking up the microsoft axd files and not properly sending down the javascript. I did some research and found that I could use `Routes.IgnoreRoute`, which should allow me to ignore the axd like below: ``` Routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); ``` But, when I add that line to my Global.asax I get this error: `CS1061: 'System.Web.Routing.RouteCollection' does not contain a definition for 'IgnoreRoute' and no extension method 'IgnoreRoute' accepting a first argument of type 'System.Web.Routing.RouteCollection' could be found (are you missing a using directive or an assembly reference?)` I've got the `System.Web.Routing` namespace imported, any ideas?
You don't need to reference ASP.NET MVC. You can use the [StopRoutingHandler](http://msdn.microsoft.com/en-us/library/system.web.routing.stoproutinghandler.aspx) which implements IRouteHandler like so: ``` routes.Add(new Route("{resource}.axd/{*pathInfo}", new StopRoutingHandler())); ``` This is part of .NET 3.5 SP1 and doesn't require MVC. The IgnoreRoutes method is a convenience extension method which is part of ASP.NET MVC.
An old question but in case it still helps anyone, this worked for me: ``` routes.Ignore("{resource}.axd/{*pathInfo}"); ``` The "Ignore" method exists, whereas in standard ASP.NET the "IgnoreRoute" method appears not to (i.e., not using MVC). This will achieve the same result as Haacked's code, but is slightly cleaner ...
How to ignore route in asp.net forms url routing
[ "", "c#", "asp.net", "url-routing", "axd", "ignoreroute", "" ]
Some of you may recognize this as Project Euler's problem number 11. The one with the grid. I'm trying to replicate the grid in a large multidimensional array, But it's giving me a syntax error and i'm not sure why ``` grid = [ [ 08, 02, 22, 97, 38, 15, 00, 40, 00, 75, 04, 05, 07, 78, 52, 12, 50, 77, 91, 08 ], [ 49, 49, 99, 40, 17, 81, 18, 57, 60, 87, 17, 40, 98, 43, 69, 48, 04, 56, 62, 00 ], [ 81, 49, 31, 73, 55, 79, 14, 29, 93, 71, 40, 67, 53, 88, 30, 03, 49, 13, 36, 65 ], ... ``` And I get this error: ``` File "D:\development\Python\ProjectEuler\p11.py", line 3 [ 08, 02, 22, 97, 38, 15, 00, 40, 00, 75, 04, 05, 07, 78, 52, 12, 50, 77, 91 , 08 ], ^ SyntaxError: invalid token ``` Why is it throwing an error before the comma?
I think when you start a literal number with a 0, it interprets it as an octal number and you can't have an '8' in an octal number.
Note that the "^" symbol in the error points exactly to the erroneous column. Together with the line number it points exactly on the digit 8. This can help lead you to what Jeremy suggested.
Python: Invalid Token
[ "", "python", "octal", "" ]
The [build instructions of V8 JavaScript Engine](http://code.google.com/p/v8/wiki/BuildingOnWindows) mention only Visual Studio 2005 and 2008. Has anybody been successful with [MinGW](http://mingw.org/) on Windows XP/Vista?
You just need to change Scons a bit. Take a look at C:\YourPythonFolder\Lib\site-packages\scons-YourSconsVersion\SCons\Script\_\_ init\_\_.py and go to line 560. Change the linker to gnulink, the c compiler to mingw and the c++ compiler to g++. Eventually it should look like this: ``` linkers = ['gnulink', 'mslink', 'ilink', 'linkloc', 'ilink32' ] c_compilers = ['mingw', 'msvc', 'gcc', 'intelc', 'icl', 'icc', 'cc', 'bcc32' ] cxx_compilers = ['g++', 'msvc', 'intelc', 'icc', 'c++', 'bcc32' ] ``` Now MingW is activated by default :)
There is a patch for MinGW support: <http://codereview.chromium.org/18309> See also: <http://code.google.com/p/v8/issues/detail?id=64>
V8 JavaScript Engine on Windows (MinGW)
[ "", "javascript", "windows", "mingw", "v8", "" ]
I'm trying to make a calculator that will take inputs from users and estimate for them how much money they'll save if they use various different VoIP services. I've set it up like this: ``` <form method="get" action="voip_calculator.php"> How much is your monthly phone bill? <input name="monthlybill" type="text" value="$" size="8"> <p><input type="submit" name="Submit" value="Submit"> </p> </form> ``` On voipcalculator.php, the page I point to, I want to call "monthlybill" but I can't figure out how to do it. I also can't figure out how to make it do the subtraction on the numbers in the rows. This may be very simple to you but it's very frustrating to me and I am humbly asking for a bit of help. Thank you! Here is the relevant stuff from voip\_calculator, you can also click on the url and submit a number to see it in (in)action. I tried various times to call it with no success: ``` <table width="100%;" border="0" cellspacing="0" cellpadding="0"class="credit_table2" > <tr class="credit_table2_brd"> <td class="credit_table2_brd_lbl" width="100px;">Services:</td> <td class="credit_table2_brd_lbl" width="120px;">Our Ratings:</td> <td class="credit_table2_brd_lbl" width="155px;">Your Annual Savings:</td> </tr> Your monthly bill was <?php echo 'monthlybill' ?> <?php echo "$monthlybill"; ?> <?php echo "monthlybill"; ?> <?php echo '$monthlybill'; ?> <?php echo 'monthlybill'; ?> <?php $monthybill="monthlybill"; $re=1; $offer ='offer'.$re.'name'; $offername= ${$offer}; while($offername!="") { $offerlo ='offer'.$re.'logo'; $offerlogo=${$offerlo}; $offerli ='offer'.$re.'link'; $offerlink=${$offerli}; $offeran ='offer'.$re.'anchor'; $offeranchor=${$offeran}; $offerst ='offer'.$re.'star1'; $offerstar=${$offerst}; $offerbot='offer'.$re.'bottomline'; $offerbottomline=${$offerbot}; $offerca ='offer'.$re.'calcsavings'; $offercalcsavings=${$offerca}; echo '<tr > <td > <a href="'.$offerlink.'" target="blank"> <img src="http://www.nextadvisor.com'.$offerlogo.'" alt="'.$offername.'" /> </a> </td> <td > <span class="rating_text">Rating:</span> <span class="star_rating1"> <img src="IMAGE'.$offerstar.'" alt="" /> </span> <br /> <div style="margin-top:5px; color:#0000FF;"> <a href="'.$offerlink.'" target="blank">Go to Site</a> <span style="margin:0px 7px 0px 7px;">|</span> <a href="'.$offeranchor.'">Review</a> </div> </td> <td >'.$offercalcsavings.'</td> </tr>'; $re=$re+1; $offer ='offer'.$re.'name'; $offername= ${$offer}; } ?> ``` offercal(1,2,3,4,5,6,7)savings calls to a file called values.php where they are defined like this: ``` $offer1calcsavings="24.99"; $offer2calcsavings="20.00"; $offer3calcsavings="21.95"; $offer4calcsavings="23.95"; $offer5calcsavings="19.95"; $offer6calcsavings="23.97"; $offer7calcsavings="24.99"; ```
You need to get the value from the QueryString and put it into a PHP variable. Like this: ``` $monthlyBill = $_GET['monthlybill']; ``` Now the variable $monthlyBill contains the value from the QueryString. To display it: ``` echo "Your monthly bill is: $monthlyBill"; ```
One thing i do is this ``` echo "<pre>"; print_r($_GET); echo "</pre>"; ``` Put this somewhere in your receiving end and you'll get an understanding of whats happening.
basic php form help
[ "", "php", "forms", "calculator", "" ]
I am performing two validations on the client side on the samve event. I have defined my validations as shown below ``` btnSearch.Attributes["OnClick"] = "javascript:return prepareSave(); return prepareSearch();" ``` Pseudo code for ``` prepareSave(): { if (bPendingchanges) { return confirm('Need to save pending changes first, click OK and loose changes or cancel to save them first') } else {return true} } ``` Pseudo code for ``` prepareSearch(): { if (bNoSearchText) { alert('Please specify search criteria before proceeding') return false; } else {return true;} } ``` When `bPendingchanges=false`, I never get the second validation running. Anyone who can quickly spot what I have overlooked here? Please?
Your second `return` statement will never be reached. Execution stops after `javascript:return prepareSave()`. Looks like you want to return true if both functions return true - therefore, do: ``` btnSearch.Attributes["OnClick"] = javascript: return prepareSave() && prepareSearch(); ```
`return`, as the name implies, returns control back to whatever called the code in question. Therefore, anything that's after a return statement ``` return prepareSave(); return prepareSearch(); // ^^^^^^^^^^^^^^^^^^^^^^^ e.g. this part ``` never executes. Try `return (prepareSave() && prepareSearch());`
Javascript - multiple client-side validations on same event
[ "", "javascript", "html", "validation", "" ]
As Scott Myers wrote, you can take advantage of a relaxation in C++'s type-system to declare clone() to return a pointer to the actual type being declared: ``` class Base { virtual Base* clone() const = 0; }; class Derived : public Base { virtual Derived* clone() const }; ``` The compiler detects that clone() returns an pointer to the type of the object, and allows Derived to override it to return a pointer to derived. It would desirable to have clone() return a smart pointer that implies transfer of ownership semantics, like the following: ``` class Base { virtual std::auto_ptr<Base> clone() const = 0; }; class Derived : public Base { virtual std::auto_ptr<Derived> clone() const; }; ``` Unfortunately, the relaxation of the conventions does not apply to templated smart pointers, and the compiler will not allow the override. So, it seems I am left with two options: 1. Have clone() return a "dumb" pointer, and document that clients are responsible for disposing of it. 2. Have clone() return a smart base pointer, and have clients use dynamic\_cast to save them to a Derived pointer if they need it. Is one of these approaches preferred? Or is there a way for me to eat my transfer of ownership semantics and have my strong type safety too?
It depends on your use case. If you ever think you will need to call `clone` on a derived object whose dynamic type you know (remember, the whole point of `clone` is to allow copying *without* knowing the dynamic type), then you should probably return a dumb pointer and load that into a smart pointer in the calling code. If not, then you only need to return a smart\_ptr and so you can feel free to return it in all overrides.
Use the Public non-virtual / Private virtual pattern : ``` class Base { public: std::auto_ptr<Base> clone () { return doClone(); } private: virtual Base* doClone() { return new (*this); } }; class Derived : public Base { public: std::auto_ptr<Derived> clone () { return doClone(); } private: virtual Derived* doClone() { return new (*this); } }; ```
What's the best signature for clone() in C++?
[ "", "c++", "clone", "smart-pointers", "covariant-return-types", "" ]
What is the best way to scale a 2D image array? For instance, suppose I have an image of 1024 x 2048 bytes, with each byte being a pixel. Each pixel is a grayscale level from 0 to 255. I would like to be able to scale this image by an arbitrary factor and get a new image. So, if I scale the image by a factor of 0.68, I should get a new image of size 0.68\*1024 x 0.68\*2048. some pixels will be collapsed onto each other. And, if I scale by a factor of say 3.15, I would get a larger image with pixels being duplicated. So, what's the best way to accomplish this? Next, I would like to be able to rotate an image by an arbitrary angle, in the range of 0 to 360 degrees (0 - 2Pi). Cropping of the image after rotating isn't an issue. What would be the best way to do this?
There is no simple way of accomplishing this. Neither [scaling](http://en.wikipedia.org/wiki/Image_scaling) nor rotating are trivial processes. It is therefore advisable to use a 2d imaging library. [Magick++](http://www.imagemagick.org/Magick++/) can be an idea as divideandconquer.se point out, but there are others.
There are many ways to scale and rotate images. The simplest way to scale is: ``` dest[dx,dy] = src[dx*src_width/dest_width,dy*src_height/dest_height] ``` but this produces blocky effects when increasing the size and loss of detail when reducing the size. There are ways to produce better looking results, for example, [bilinear filtering](http://en.wikipedia.org/wiki/Bilinear_interpolation). For rotating, the src pixel location can be calculated using [a rotation matrix](http://mathworld.wolfram.com/RotationMatrix.html): ``` sx,sy = M(dx,dy) ``` where M is a matrix that maps destination pixels to the source image. Again, you'll need to do interpolation to produce non-blocky results. But there are plenty of libraries available if you don't want to get into the mathematics of image processing.
Image scaling and rotating in C/C++
[ "", "c++", "c", "image", "image-scaling", "" ]
In most programming languages, dictionaries are preferred over hashtables. What are the reasons behind that?
For what it's worth, a Dictionary **is** (conceptually) a hash table. If you meant "why do we use the `Dictionary<TKey, TValue>` class instead of the `Hashtable` class?", then it's an easy answer: `Dictionary<TKey, TValue>` is a generic type, `Hashtable` is not. That means you get type safety with `Dictionary<TKey, TValue>`, because you can't insert any random object into it, and you don't have to cast the values you take out. Interestingly, the `Dictionary<TKey, TValue>` implementation in the .NET Framework is based on the `Hashtable`, as you can tell from this comment in its source code: > The generic Dictionary was copied from Hashtable's source [Source](http://referencesource.microsoft.com/#mscorlib/system/collections/hashtable.cs)
## Differences | `Dictionary` | `Hashtable` | | --- | --- | | **Generic** | **Non-Generic** | | Needs **own thread synchronization** | Offers **thread safe** version through **`Synchronized()`** method | | Enumerated item: **`KeyValuePair`** | Enumerated item: **`DictionaryEntry`** | | Newer (> **.NET 2.0**) | Older (since **.NET 1.0**) | | is in **System.Collections.Generic** | is in **System.Collections** | | Request to non-existing key **throws exception** | Request to non-existing key **returns null** | | potentially a bit **faster for value types** | **bit slower** (needs boxing/unboxing) for value types | ## Similarities: * Both are internally **hashtables** == fast access to many-item data according to key * Both need **immutable and unique keys** * Keys of both need own **`GetHashCode()`** method ## Alternative .NET collections: *(candidates to use instead of Dictionary and Hashtable)* * `ConcurrentDictionary` - **thread safe** (can be safely accessed from several threads concurrently) * `HybridDictionary` - **optimized performance** (for few items and also for many items) * `OrderedDictionary` - values can be **accessed via int index** (by order in which items were added) * `SortedDictionary` - items **automatically sorted** * `StringDictionary` - strongly typed and **optimized for strings** (now Deprecated in favor of Dictionary<string,string>)
Why is Dictionary preferred over Hashtable in C#?
[ "", "c#", ".net", "vb.net", "data-structures", "" ]
In a PHP application I am writing, I would like to have users enter in text a mix of HTML and text with pointed-brackets, but when I display this text, I want to let the HTML tags be rendered by the non-HTML tags be shown literary, e.g. a user should be able to enter: ``` <b> 5 > 3 = true</b> ``` when displayed, the user should see: **5 > 3 = true** What is the best way to parse this, i.e. find all the non-HTML brackets, convert them to &gt; and &lt;?
I'd recommend having the users enter BBcode style markup which you then replace with the html tags: ``` [b]This is bold[/b] [i]this is italic with a > 'greater than' sign there[/i] ``` This gives you more control over how you parse user's input into html, though I admit it looks like an unnecessary burden.
If you're allowing user input HTML, you've got to solve a far bigger problem than a few unescaped angled brackets; HTML is really tough to validate and filter properly, and if you don't do it right you open yourself up to XSS attacks. I've written a library that does this; someone else already posted a link to it here so I won't reiterate. To answer your question, however, the most foolproof way of converting stray angled brackets to their escaped forms is parsing the HTML with DOM/libxml, and then reserializing it. Anything that uses regexes or such will be doomed to failure by edge-case. You could also write your own parser but that also takes a bit of work.
Best way to handle mixed HTML and in user input?
[ "", "php", "parsing", "" ]
Often you need to show a list of database items and certain aggregate numbers about each item. For instance, when you type the title text on Stack Overflow, the Related Questions list appears. The list shows the titles of related entries and the single aggregated number of quantity of responses for each title. I have a similar problem but needing multiple aggregates. I'd like to display a list of items in any of 3 formats depending on user options: * My item's name (15 total, 13 owned by me) * My item's name (15 total) * My item's name (13 owned by me) My database is: * **items**: itemId, itemName, ownerId * **categories**: catId, catName * **map**: mapId, itemId, catId The query below gets: category name, count of item ids per category ``` SELECT categories.catName, COUNT(map.itemId) AS item_count FROM categories LEFT JOIN map ON categories.catId = map.catId GROUP BY categories.catName ``` This one gets: category name, count of item ids per category for this owner\_id only ``` SELECT categories.catName, COUNT(map.itemId) AS owner_item_count FROM categories LEFT JOIN map ON categories.catId = map.catId LEFT JOIN items ON items.itemId = map.itemId WHERE owner = @ownerId GROUP BY categories.catId ``` But how do i get them at the same time in a single query? I.e.: category name, count of item ids per category, count of item ids per category for this owner\_id only Bonus. How can I optionally only retrieve where catId count != 0 for any of these? In trying "WHERE item\_count <> 0" I get: ``` MySQL said: Documentation #1054 - Unknown column 'rid_count' in 'where clause' ```
Here's a trick: calculating a `SUM()` of values that are known to be either 1 or 0 is equivalent to a `COUNT()` of the rows where the value is 1. And you know that a boolean comparison returns 1 or 0 (or NULL). ``` SELECT c.catname, COUNT(m.catid) AS item_count, SUM(i.ownerid = @ownerid) AS owner_item_count FROM categories c LEFT JOIN map m USING (catid) LEFT JOIN items i USING (itemid) GROUP BY c.catid; ``` As for the bonus question, you could simply do an inner join instead of an outer join, which would mean only categories with at least one row in `map` would be returned. ``` SELECT c.catname, COUNT(m.catid) AS item_count, SUM(i.ownerid = @ownerid) AS owner_item_count FROM categories c INNER JOIN map m USING (catid) INNER JOIN items i USING (itemid) GROUP BY c.catid; ``` Here's another solution, which is not as efficient but I'll show it to explain why you got the error: ``` SELECT c.catname, COUNT(m.catid) AS item_count, SUM(i.ownerid = @ownerid) AS owner_item_count FROM categories c LEFT JOIN map m USING (catid) LEFT JOIN items i USING (itemid) GROUP BY c.catid HAVING item_count > 0; ``` You can't use column aliases in the `WHERE` clause, because expressions in the `WHERE` clause are evaluated before the expressions in the select-list. In other words, the values associated with select-list expressions aren't available yet. You can use column aliases in the `GROUP BY`, `HAVING`, and `ORDER BY` clauses. These clauses are run after all the expressions in the select-list have been evaluated.
You can sneak a CASE statement inside your SUM(): ``` SELECT categories.catName, COUNT(map.itemId) AS item_count, SUM(CASE WHEN owner= @ownerid THEN 1 ELSE 0 END) AS owner_item_count FROM categories LEFT JOIN map ON categories.catId = map.catId LEFT JOIN items ON items.itemId = map.itemId GROUP BY categories.catId HAVING COUNT(map.itemId) > 0 ```
Query: count multiple aggregates per item
[ "", "mysql", "sql", "grouping", "mysql-error-1054", "" ]
So, I've been looking at [Hadoop](http://hadoop.apache.org/) with keen interest, and to be honest I'm fascinated, things don't get much cooler. My only minor issue is I'm a C# developer and it's in Java. It's not that I don't understand the Java as much as I'm looking for the Hadoop.net or NHadoop or the .NET project that embraces the [Google MapReduce](http://en.wikipedia.org/wiki/MapReduce) approach. Does anyone know of one?
Have you looked at using [Hadoop's streaming?](http://wiki.apache.org/hadoop/HadoopStreaming) I use it in python all the time :-). I'm starting to see that the heterogeneous approach is often the best and it looks like other folks are doing the same. If you look at projects like protocol-buffers or facebook's thrift you see that sometimes it's just best to use an app written in another language and build the glue in the language of your preference.
Recently, MySpace released their .NET MapReduce framework, [Qizmt](http://code.google.com/p/qizmt/), as Open Source, so this is also a potential contender in this space.
Is there a .NET equivalent to Apache Hadoop?
[ "", "c#", ".net", "hadoop", "mapreduce", "" ]
Should I use textbox.text.Trim() function every time when I insert any data from web page to database. I just have a habit of using the trim function? Does it effect the performance any way? Should I use everytime or just when needed?
I've seen many problems with spaces which had been added at the end to a text field by accident (for instance logins which mysteriously didn't work). So it's not a bad idea at all to trim() most textfield input as a standard practice. I think the performance hit of a trim() is absolutely neglible, except maybe for sites with ultra high traffic.
You should trim data as it comes into your application (from a submitted form), rather than just before you put it into the database. It's a validation step to get data into a controlled format, rather than an escaping step to store in a database safely. (\*) You should also be doing removal of control characters and anything else that will cause your application trouble at this point. For example, imagine the difficulty (and potential security problems) a username with a newline character or null byte in it could cause. A typical browser UI might not allow those characters to be typed, but that doesn't stop an attacker submitting them. Some form-reading libraries may take care of this for you, most won't. Not everything needs trimming. For example big text fields like the one I'm typing in now might have a valid reason to have whitespace at the start and/or end. But it's worth doing for anything that has logic associated with it, most notably things like usernames. \*: there is one database issue with untrimmed spaces: many databases will silently trim trailing spaces, and unexpectedly match strings with any number of trailing spaces. Don't expect to get trailing spaces back from the database unless it's a BLOB column, and again, trim before doing anything with logic like matching usernames.
Should I use Trim function everytime when I insert data from webpage to database?
[ "", "c#", "asp.net", "" ]
This question is simple. What function would I use in a PHP script to load data from a URL into a string?
CURL is usually a good solution: <http://www.php.net/curl> ``` // create a new cURL resource $ch = curl_init(); // set URL and other appropriate options curl_setopt($ch, CURLOPT_URL, "http://www.example.com/"); curl_setopt($ch, CURLOPT_HEADER, 0); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // grab URL and pass it to the browser $html = curl_exec($ch); // close cURL resource, and free up system resources curl_close($ch); ```
I think you are looking for ``` $url_data = file_get_contents("http://example.com/examplefile.txt"); ```
How do I load arbitrary data from a url PHP?
[ "", "php", "url", "scripting", "load", "" ]
Should my program support IA64, or should it only support x64? I haven't been able to easily find IA64 computers myself. Is IA64 dead? MS seems to have a wide support for IA64, but it took me a long time to be able to find an IA64, and I had to end up getting it on eBay.
What kind of software do you develop? If it's not a data center type of application or a high-end number crunching app, I'd be surprised if there were any demand for an ia64 version. And even then, I'd think it would be a situation where if you have to ask if you should support it, you probably don't need to. A couple things off the top of my head that might hamper an ia64 port: * any third party tools or libraries you're depending on need to support it * unaligned accesses that go largely unnoticed on x86 and x64 will cause headaches on ia64 Of course, I don't work for Gartner or IDC or anyone who does market analysis, so you should take what I say here with whatever skepticism you have lying around. Have any customers or potential customers inquired?
If you have access to an IA64, then it is absolutely worth it to make your code run on it. Porting your code to another CPU architecture will reveal all sorts of hidden problems. You might have a string overflow by 1 that doesn't show itself on Linux/Windows/x86 but crashes the program because of different stack layout or structure alignment. You might be assuming that ~1UL == 0xFFFFFFFF. I keep my C++ code IA64 clean, but I already have a couple of machines because I'm a fan.
Should my C++ program support IA64 or only x64?
[ "", "c++", "c", "64-bit", "itanium", "" ]
In Ruby I have often written a number of small classes, and had a main class organize the little guys to get work done. I do this by writing ``` require "converter.rb" require "screenFixer.rb" . . . ``` at the top of the main class. How do I do this in Java? Is it "import?" Also, could someone please come up with a better title for this question?
If you mean that you are going to write some code that will be using another class. Yes you will need to import those classes using an import statement. i.e. ``` package com.boo; import com.foo.Bar; public class StackOverflow { private Bar myBar; } ```
You don't import you own \*.java files in java. Instead you do like this. ``` javac file1.java file2.java file3.java java file1 ```
How do I "require" a neighbour class in Java?
[ "", "java", "" ]
I was looking into GWT. It seems nice, but our software have the must work without JS requirement. Is it possible?
No, it isn't. GWT provides a windowing toolkit that is specifically designed to run on the client, not on the server. Degraded (e.g. non-javascript) code would need to deliver complete HTML to the browser, which GWT simply does not do. It compiles your java code to a javascript file that is delivered to the client and builds the UI by DOM-manipulation on the client. Then there's some code to talk back to the server, some implicit, some written by you yourself. This model does not lend itself well to degrading gracefully. The only way to degrade somewhat gracefully is to provide a second, non-javascript UI or use another toolkit that doesn't render the frontend on the client but delivers HTML. Sorry.
You could degrade gracefully by creating an html structure that is just 'good enough' (with form posts, linked menus, etc) and then have GWT attach to each part of that structure, augmenting its behavior. For example, make an HTML drop down dynamic, replace a link to another page with a component that opens a lightbox, or replace a link to another page with an XML http request to do the same thing (e.g. cast a vote). I've done this a number of times for clients. It's the opposite way that most GWT gets developed, but it can work.
GWT without JavaScript?
[ "", "javascript", "web-applications", "gwt", "graceful-degradation", "noscript", "" ]
Kind of a basic question but I'm having troubles thinking of a solution so I need a push in the right direction. I have an input file that I'm pulling in, and I have to put it into one string variable. The problem is I need to split this string up into different things. There will be 3 strings and 1 int. They are separated by a ":". I know I can find the position of the first ":" by find(), but I really don't know how to progress through the string, for each thing and put it into it's own string / int. The actual input from the file looks something like this: ``` A:PEP:909:Inventory Item ``` A is going to be command I have to execute... so that will be a string. PEP is a key, needs to be a string. 909 is an int. and the last is a string. So what I think I want to do is have 3 string var's, and 1 int and get all those things put into their respective variables. So I think I'll end up wanting to conver this C++ string to a C string so I can use atoi to convert the one section to an int.
With C-style strings you can use [strtok()](http://linux.die.net/man/3/strtok) to do this. You could also use [sscanf()](http://linux.die.net/man/3/sscanf) But since you're dealing with C++, you probably want to stick with built in std::string functions. As such you can use find(). Find has a form which takes a second argument which is the offset to start searching. So you can do find( ':' ) to find the first instance, and then use find( ':', firstIndex+1 ) to find the next instances, where firstIndex is the value returned by the first call to find().
I usually use something like this: ``` void split(const std::string &s, char delim, std::vector<std::string> &elems) { std::stringstream ss(s); std::string item; while(std::getline(ss, item, delim)) { elems.push_back(item); } } ``` you can use it like this: ``` std::vector<std::string> tokens; split("this:is:a:test", ':', tokens); ``` tokens will now contain "this", "is", "a", and "test"
C++ Strings Modifying and Extracting based on Separators
[ "", "c++", "string", "" ]
I have a web application that uses Ext-JS 2.2. In a certain component, we have an empty toolbar that we are trying to add a button to using ``` myPanel.getTopToolbar().insertButton(0, [...array of buttons...]); ``` However, in IE6/7 this fails because of lines 20241-20242 in ext-all-debug.js: ``` var td = document.createElement("td"); this.tr.insertBefore(td, this.tr.childNodes[index]); ``` Since "this.tr.childNodes([0])" does not yet exist in IE, this fails with "Invalid argument". THE REAL QUESTION: Can I, using CSS similar to the below add a child to every toolbar <tr> so that this.tr.childNodes[0] is found: ``` div.x-toolbar tr:after { content: " "; } ``` I totally realize this is a hack, but for legal reasons I cannot change any Javascript, not even to add an empty button ({}) to each toolbar. Major kudos to anyone that can figure this out.
I didn't think there was a CSS-only solution. For the record, I ended up injecting javascript into the page that overrides the Ext.Toolbar prototype for the insertButton() function to check for the existance of "this.tr.childNodes([0])" and default to addButton() if it didn't exist.
What I've had to do in the past was include an empty toolbar in my element config: tbar:[] Then (and only after the element has completely rendered) use the .add() method for injecting buttons. Order of events will get you every time. It takes a while to get a handle on it.
Needing an ExtJS bug workaround
[ "", "javascript", "css", "extjs", "" ]
I have this method in my db class ``` public function query($queryString) { if (!$this->_connected) $this->_connectToDb(); //connect to database $results = mysql_query($queryString, $this->_dbLink) or trigger_error(mysql_error()); return mysql_num_rows($results) > 0 ? mysql_fetch_assoc($results) : false; } ``` This works great for queries that return 1 row, but how can I get an array returned something like this? ``` $array[0]['name'] = 'jim' $array[0]['id'] = 120 $array[1]['name'] = 'judith' $array[1]['ID'] = 121 ``` Now I know I could use a while loop to insert this data into the array like so, but I was wondering if PHP could do this with an internal function? I havn't been able to find on the docs what I'm after. The reason I don't want to run the while within the method is because I am going to reiterate back over the array when it's returned, and I'd rather not run through the results twice (for performance reasons). Is there a way to do this? Do I have a problem with my general query method design? Thank you muchly!
``` public function query($queryString) { if (!$this->_connected) $this->_connectToDb(); //connect to database $results = mysql_query($queryString, $this->_dbLink) or trigger_error(mysql_error()); $data = array(); while($row = mysql_fetch_assoc($results)) { $data[] = $row; } return $data; } ``` this will always return an array. EDIT: I didn't read the question well. If you realy don't want to use the loop then I would do this: ``` public function query($queryString) { if (!$this->_connected) $this->_connectToDb(); //connect to database return mysql_query($queryString, $this->_dbLink) or trigger_error(mysql_error()); } ``` then loop over it, however I would just use the loop.
You might also want to look at the [PDO](http://www.php.net/manual/en/book.pdo.php) extension. You can load the entire result set into an array or you can loop using foreach. ``` <?php $db = new PDO($connection_string, $username, $password); $result = $db->query($queryString); foreach($result as $row) { // do something } // or $result = $db->query($queryString); $result_array = $result->fetchAll(PDO::FETCH_ASSOC); ?> ```
PHP mySQL - Can you return an associated array with a number index?
[ "", "php", "mysql", "" ]
I'm trying to validate that a submitted URL doesn't already exist in the database. The relevant parts of the Form class look like this: ``` from django.contrib.sites.models import Site class SignUpForm(forms.Form): # ... Other fields ... url = forms.URLField(label='URL for new site, eg: example.com') def clean_url(self): url = self.cleaned_data['url'] try: a = Site.objects.get(domain=url) except Site.DoesNotExist: return url else: raise forms.ValidationError("That URL is already in the database. Please submit a unique URL.") def clean(self): # Other form cleaning stuff. I don't *think* this is causing the grief ``` The problem is, regardless of what value I submit, I can't raise the `ValidationError`. And if I do something like this in the `clean_url()` method: ``` if Site.objects.get(domain=url): raise forms.ValidationError("That URL is already in the database. Please submit a unique URL.") ``` then I get a `DoesNotExist` error, even for URLs that already exist in the Database. Any ideas?
django channel in IRC saved me here. The problem was that the URLField.clean() does two things I wasn't expecting: 1. If no URL scheme is present (eg, http://) the method prepends 'http://' to the url 2. the method also appends a trailing slash. The results are returned and stored in the form's cleaned\_data. So I was checking `cleaned_data['url']` expecting something like `example.com` and actually getting `http://example.com/`. Suffice to say, changing my `clean_url()` method to the following works: ``` def clean_url(self): url = self.cleaned_data['url'] bits = urlparse(url) dom = bits[1] try: site=Site.objects.get(domain__iexact=dom) except Site.DoesNotExist: return dom raise forms.ValidationError(u'That domain is already taken. Please choose another') ```
I do it this way. It's slightly simpler. ``` try: a = Site.objects.get(domain=url) raise forms.ValidationError("That URL is already in the database. Please submit a unique URL.") except Site.DoesNotExist: pass return url ```
Problems raising a ValidationError on a Django Form
[ "", "python", "django", "django-forms", "cleaned-data", "" ]
EDIT: I've tagged this C in a hope to get more response. It's more the theory I'm interested in than a specific language implementation. So if you're a C coder please treat the following PHP as pseudo-code and feel free to respond with an answer written in C. I am trying to speed up a PHP CLI script by having it execute its tasks in parallel instead of serial. The tasks are completely independent of each other so it doesn't matter which order they start/finish in. Here's the original script (note all these examples are stripped-back for clarity): ``` <?php $items = range(0, 100); function do_stuff_with($item) { echo "$item\n"; } foreach ($items as $item) { do_stuff_with($item); } ``` I've managed to make it work on the `$items` in parallel with [`pcntl_fork()`](http://php.net/pcntl_fork) as shown below: ``` <?php ini_set('max_execution_time', 0); ini_set('max_input_time', 0); set_time_limit(0); $items = range(0, 100); function do_stuff_with($item) { echo "$item\n"; } $pids = array(); foreach ($items as $item) { $pid = pcntl_fork(); if ($pid == -1) { die("couldn't fork()"); } elseif ($pid > 0) { // parent $pids[] = $pid; } else { // child do_stuff_with($item); exit(0); } } foreach ($pids as $pid) { pcntl_waitpid($pid, $status); } ``` Now I want to extend this so there's a maximum of, say, 10 children active at once. What's the best way of handling this? I've tried a few things but haven't had much luck.
There is no syscall to get a list of child pids, but `ps` can do it for you. `--ppid` switch will list all children for you process so you just need to count number of lines outputted by `ps`. Alternatively you can maintain your own counter that you will increment on `fork()` and decrement on `SIGCHLD` signal, assuming `ppid` stays unchanged for fork'ed processed.
The best thing I can come up with is to add all the tasks to a queue, launch the maximum number of threads you want, and then have each thread requesting a task from the queue, execute the task and requesting the next one. Don't forget to have the threads terminate when there are no more tasks to do.
How can I enforce a maximum amount of forked children?
[ "", "php", "c", "fork", "process-management", "" ]
For the moment the best way that I have found to be able to manipulate DOM from a string that contain HTML is: ``` WebBrowser webControl = new WebBrowser(); webControl.DocumentText = html; HtmlDocument doc = webControl.Document; ``` There are two problems: 1. Requires the `WebBrowser` object! 2. This can't be used with multiple threads; I need something that would work on different thread (other than the main thread). Any ideas?
I did a search to GooglePlex for HTML and I found [Html Agility Pack](https://html-agility-pack.net/) I do not know if it's for that or not, I am downloading it right now to give a try.
Depending on what you are trying to do (maybe you can give us more details?) and depending on whether or not the HTML is well-formed, you *could* convert this to an `XmlDocument`: ``` System.Xml.XmlDocument x = new System.Xml.XmlDocument(); x.LoadXml(html); // as long as html is well-formed, i.e. XHTML ``` Then you could manipulate it easily, without the `WebBrowser` instance. As for threads, I don't know enough about the implementation of `XmlDocument` to know the answer to that part. --- If the document isn't in proper form, you could use [**NTidy**](http://sourceforge.net/projects/ntidy/) (.NET wrapper for [**HTML Tidy**](http://tidy.sourceforge.net/)) to get it in shape first; I had to do this very thing for a project once and it really wasn't too bad.
How can I manipulate the DOM from a string of HTML in C#?
[ "", "c#", ".net", "html", "dom", ".net-2.0", "" ]
I'm building a python application from some source code I've found [Here](http://code.google.com/p/enso) I've managed to compile and fix some problems by searching the web, but I'm stuck at this point: When running the application this message appears. [alt text http://img511.imageshack.us/img511/4481/loadfr0.png](http://img511.imageshack.us/img511/4481/loadfr0.png) This python app, usues swig to link to c/c++ code. I have VC++2005 express edition which I used to compile along with scons and Python 2.5 ( and tried 2.4 too ) The dlls that are attempting to load is "msvcr80.dll" because before the message was "msvcr80.dll" cannot be found or something like that, so I got it and drop it in window32 folder. For what I've read in here: <http://msdn.microsoft.com/en-us/library/ms235591(VS.80).aspx> The solution is to run MT with the manifest and the dll file. I did it already and doesn't work either. Could anyone point me to the correct direction? This is the content of the manifest fie: ``` <?xml version='1.0' encoding='UTF-8' standalone='yes'?> <assembly xmlns='urn:schemas-microsoft-com:asm.v1' manifestVersion='1.0'> <dependency> <dependentAssembly> <assemblyIdentity type='win32' name='Microsoft.VC80.CRT' version='8.0.50608.0' processorArchitecture='x86' publicKeyToken='1fc8b3b9a1e18e3b' /> </dependentAssembly> </dependency> </assembly> ``` I'm going to try Python 2.6 now, I'm not quite sure of understanding the problem, but Python 2.5 and Python 2.5 .exe had the string "MSVCR71.dll" inside the .exe file. But probably this has nothing to do. ps. if only everything was as easy as jar files :( This is the stack trace for completeness ``` None INFO:root:Skipping provider enso.platform.osx. INFO:root:Skipping provider enso.platform.linux. INFO:root:Added provider enso.platform.win32. Traceback (most recent call last): File "scripts\run_enso.py", line 24, in <module> enso.run() File "C:\oreyes\apps\enso\enso-read-only\enso\__init__.py", line 40, in run from enso.events import EventManager File "C:\oreyes\apps\enso\enso-read-only\enso\events.py", line 60, in <module> from enso import input File "C:\oreyes\apps\enso\enso-read-only\enso\input\__init__.py", line 3, in <module> _input = enso.providers.getInterface( "input" ) File "C:\oreyes\apps\enso\enso-read-only\enso\providers.py", line 137, in getInterface interface = provider.provideInterface( name ) File "C:\oreyes\apps\enso\enso-read-only\enso\platform\win32\__init__.py", line 48, in provideInterface import enso.platform.win32.input File "C:\oreyes\apps\enso\enso-read-only\enso\platform\win32\input\__init__.py", line 3, in <module> from InputManager import * File "C:\oreyes\apps\enso\enso-read-only\enso\platform\win32\input\InputManager.py", line 7, in <module> import _InputManager ImportError: DLL load failed: Error en una rutina de inicializaci¾n de biblioteca de vÝnculos dinßmicos (DLL). ```
I've been able to compile and run Enso by using /LD as a compiler flag. This links dynamically to the MS Visual C++ runtime, and seems to allow you to get away without a manifest. If you're using SCons, see the diff file here: <http://paste2.org/p/69732>
Looking at your update, it looks like you need to install [Pycairo](http://www.cairographics.org/pycairo/) since you're missing the \_cairo module installed as part of Pycairo. See the [Pycairo downloads page](http://www.cairographics.org/download/) for instructions on how to obtain/install binaries for Windows.
load dll from python
[ "", "python", "swig", "scons", "dynamic-linking", "" ]
I created 26 `JButton` in an anonymous `actionListener` labeled as each letter of the alphabet. ``` for (int i = 65; i < 91; i++){ final char c = (char)i; final JButton button = new JButton("" + c); alphabetPanel.add(button); button.addActionListener( new ActionListener () { public void actionPerformed(ActionEvent e) { letterGuessed( c ); alphabetPanel.remove(button); } }); // set the name of the button button.setName(c + ""); } ``` Now I have an anonymous `keyListener` class, where I would like to disable the button based off of which letter was pressed on the keyboard. So if the user presses A, then the `A` button is disabled. Is this even possible given my current implementation?
Could you not simply declare an array of 26 JButton objects at class level, so that both listeners can access them? I believe anonymous inner classes can access class variables as well as final variables.
I don't know if you want to disable the button or do you want to remove it? In you code you're calling remove and in your answer you're talking about disabling. You could achieve this by adding a KeyListener to the alphabetPanel. So you could add this just before starting the for-loop: ``` InputMap iMap = alphabetPanel.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW); ActionMap aMap = alphabetPanel.getActionMap(); ``` and instead of your ActionListener added to the JButton call this: ``` iMap.put(KeyStroke.getKeyStroke(c), "remove"+c); aMap.put("remove"+c, new AbstractAction(){ public void actionPerformed(ActionEvent e) { // if you want to remove the button use the following two lines alphabetPanel.remove(button); alphabetPanel.revalidate(); // if you just want to disable the button use the following line button.setEnabled(false); } }); ```
Accessing a "nameless" Jbutton in an anonymous class from another anonymous class?
[ "", "java", "swing", "actionlistener", "keylistener", "" ]
How can I start writing a plugin for [Eclipse](http://en.wikipedia.org/wiki/Eclipse_%28software%29)? I've looked for documentation, but unfortunately there is very little or it's poor, so what articles can recommended?
There are some pretty good resources and tutorials on the main Eclipse and IBM's site. One of the best ways is to pick an open source plug-in that has some similar features to what you want to do and start to dissect it. * *[PDE Does Plug-ins](http://www.eclipse.org/articles/Article-PDE-does-plugins/PDE-intro.html)* * *[Plug-in development 101, Part 1: The fundamentals](http://www.ibm.com/developerworks/library/os-eclipse-plugindev1/index.html)* * *[Eclipse Plugins Exposed, Part 1: A First Glimpse](http://www.onjava.com/pub/a/onjava/2005/02/09/eclipse.html)* * *[Developing Eclipse plug-ins](http://www.ibm.com/developerworks/opensource/library/os-ecplug/)*
Eclipse has a pretty good "[Your First Plug-in](http://www.eclipse.org/articles/Article-Your%20First%20Plug-in/YourFirstPlugin.html)" tutorial. If it is confusing, I'm sure they would greatly appreciate your feedback. Keep in mind that Eclipse is essentially Java, so if you don't have a good grasp of Java go for general Java tutorials first, and then come back to Eclipse development. O'Reilly has two good Eclipse Plugin tutorials: * [Eclipse Plugins Exposed](http://www.onjava.com/pub/a/onjava/2005/02/09/eclipse.html) * [Develop Your Own Plugins for Eclipse](http://www.onjava.com/pub/a/onjava/2004/08/18/eclipseplugins.html) They not only go through the simple code examples, but give you screen shots of the process since a lot of work is done through wizard type interface windows. If these aren't helpful, perhaps you could be more specific as to what is difficult to follow. -Adam
How to write a plugin for Eclipse?
[ "", "java", "eclipse", "plugins", "" ]
I'm playing around with CodeIgniter; hoping to convert some of my old, ugly PHP into a more maintainable framework. However, I've come across a rather frustrating roadblock - I can't seem to define methods in my views. Any time I try I get a completely blank page, and when I look in the debug log the processing seemed to stop after the view was loaded. Can I define methods within views? If not, why, and what workarounds would you suggest? **Note**: The method has to do with formatting output strings.
Define your functions in a [helper](http://codeigniter.com/user_guide/general/helpers.html) and load them from the controller. That way you can reuse the functions in other views, as well.
I'm not familiar with CodeIgnitor, but it could be including your templates multiple times. Try wrapping your function in a check: ``` if (!function_exists('myfunc')) { function myfunc() {} } ``` CodeIgnitor is probably swallowing errors, so you could also try flushing buffers immediately before your function: ``` while(ob_end_flush()){} error_reporting(E_ALL); ini_set('display_errors', 1); ``` In reality though, you should probably make your string formatting code a bit more general. Your template is not really a good place to start adding functions. You'll begin duplicating code, and it defeats the purpose of having templates at all. I'd suggest experimenting with CodeIgnitor's [Helpers](http://codeigniter.com/user_guide/general/helpers.html) and [Plugins](http://codeigniter.com/user_guide/general/helpers.html)
CodeIgniter doesn't like methods in views?
[ "", "php", "codeigniter", "" ]
I keep it in single line, if it's short. Lately I've been using this style for longer or nested ternary operator expressions. A contrived example: ``` $value = ( $a == $b ) ? 'true value # 1' : ( $a == $c ) ? 'true value # 2' : 'false value'; ``` Personally which style you use, or find most readable? **Edit:** *(on when to use ternary-operator)* I usually avoid using more than 2 levels deep ternary operator. I tend prefer 2 levels deep ternary operator over 2 level if-else, when I'm echoing variables in PHP template scripts.
The ternary operator is generally to be avoided, but this form can be quite readable: ``` result = (foo == bar) ? result1 : (foo == baz) ? result2 : (foo == qux) ? result3 : (foo == quux) ? result4 : fail_result; ``` This way, the condition and the result are kept together on the same line, and it's fairly easy to skim down and understand what's going on.
I try not to use a ternary operator to write nested conditions. It defies readability and provides no extra value over using a conditional. Only if it can fit on a single line, and it's crystal-clear what it means, I use it: ``` $value = ($a < 0) ? 'minus' : 'plus'; ```
Which coding style you use for ternary operator?
[ "", "php", "language-agnostic", "coding-style", "ternary-operator", "" ]
As a beginning programmer, I'm trying to settle on a standard naming convention for myself. I realize that it's personal preference, but I was trying to get some ideas from some of you (well a LOT of you) who are much smarter than myself. I'm not talking about camel notation but rather how do you name your variables, etc. IMHO, var\_Quantity is much more descriptive than Q or varQ. However, how do you keep the variable from becoming too long. I've tried to be more descriptive with naming my controls, but I've ended up with some like "rtxtboxAddrLine1" for a RadTextBox that holds address line 1. Too me,that is unmanageable, although it's pretty clear what that control is. I'm just curious if you have some guides that you follow or am I left up to my own devices?
Some [basic rules can be found here](http://msdn.microsoft.com/en-us/library/ms229045.aspx). And [much more extended rules can be found here](http://msdn.microsoft.com/en-us/library/ms229002.aspx). These are the official guidelines from the Microsoft framework designers. As for your example, the variable should should be called simply `quantity`.
In this case, I think you'd be better off naming it as primaryAddressLine or firstAddressLine. Here's why - rtxt as a prefix uselessly tells you the type. Intellisense will help you with the type and is immune to changes made to the actual object type. Calling it firstAddressLine keeps it away from the (poor) convention of using 1, 2, 3...on the end of variable names to indicate that for some reason you needed more of them instead of a collection. Name it for what it represents/how it's meant to be interpreted or used not for its data type, and in naming it don't abbreviate if you don't need to.
What naming conventions do you use in C#?
[ "", "c#", "naming-conventions", "" ]
I've been exploring the details of Django for about a week now and like what I see. However I've come upon some.. negativity in relation to fine-grained control of permissions to the CRUD interface. What I'm writing is an Intranet client management web-app. The organisation is about 6 tiers, and I need to restrict access to client groups based on tiers. Continually expanding. I have a fairly good idea how I'm going to do this, but am not sure if I'll be able to integrate it well into the pre-built admin interface. I've done absolutely zero Django development otherwise I'd probably have a better idea on whether this would work or not. I probably won't use Django if the generated admin interface is going to be useless to this project - but like I said, there is a heavy reliance on fine-grained custom permissions. Will Django let me build custom permissions/rules and integrate it seamlessly into the admin CRUD interface? Update One: I want to use the admin app to minimise the repitition of generating CRUD interfaces, so yes I consider it a must have. Update Two: I want to describe the permissions required for this project. A client can belong to one or many 'stores'. Full time employees should only be able to edit clients at their store (even if they belong to another store). However, they should not be able to see/edit clients at another store. Casuals should only be able to view clients based on what store they are rostered too (or if the casual is logged in as the store user - more likely). Management above them need to be able to see all employees for the stores they manage, nothing more. Senior management should be able to edit ALL employees and grant permissions below themselves. After reading the django documentation, it says you can't (autmoatically) set permissions for a sub-set of a group. Only the entire group. Is it easy enough to mock up your own permissions for this purpose?
If I read your updated requirements correctly, I don't think Django's existing auth system will be sufficient. It sounds like you need a full-on ACL system. This subject has come up a number of times. Try googling on django+acl. Random samplings ... There was a Summer of Code project a couple of years ago, but I'm not sure where they got to. See <http://code.djangoproject.com/wiki/GenericAuthorization> There is a fresh ticket at djngoproject.org that might be interesting: * <http://code.djangoproject.com/ticket/9444> There is some interesting code snips on dumpz.org: * <http://dumpz.org/274/> models.py * <http://dumpz.org/273/> signals.py ... but there are zero docs. Good luck!
The Django permission system totally rules. Each model has a default set of permissions. You can add new permissions to your models, also. Each User has a set of permissions as well as group memberships. Individual users can have individual permissions. And they inherit permissions from their group membership. Your view functions (and templates) can easily check the presence of absence of those permissions at any level of granularity you need to use. And if this isn't enough for you, the Profile add-on gives you yet more options for defining a "User" and their capabilities, permissions, roles, responsibilities, etc. And if this isn't enough for you, you can define your own authentication schemes. --- What's important is not to try and define groups that are actual subsets of users, not *casually* defined titles or roles. You never need to "set permissions for a sub-set of a group". You need to have smaller groups. Groups defined around subsets of people. Django's default permissions are around model access, not row access within a model. On the other hand, your problem is about subsets of rows in several models: Client, Store, Employee, Manager. You'll need a basic set of FK's among these items, and some filters to subset the rows. You may have trouble doing this with default admin pages. You may need your own version of admin to make use of specialized filters. --- If you can't do it with the Django permission system, you should rethink your use cases. Seriously. [The Django-REST Interface, however, is another beast entirely, and requires some care and feeding.]
Will Django be a good choice for a permissions based web-app?
[ "", "python", "django", "permissions", "" ]
I have an interface called Dictionary which has a method `insert()`. This interface is implemented by class `BSTree`, but I also have a class `AVLTree` which is a child class of `BSTree`. `AVLTree` redefines the `insert()` so it suits it's needs. Now if I type the following code: ``` Dictionary data=new AVLTree(); data.insert(); ``` There is a problem, because the `insert()` method that is called is of `BSTree` instead of `AVLTree`. Why doesn't the polymorphism kick in here? What is the appropriate solution, one that retains the principle of polymorphism?
In java, (I'm talking relatively to C++), polymorphism should "always" work. It's hard to see what's wrong without looking at the code.. maybe you could post interesting part? Such as the method's signature, class declaration, etc.. My guess is that you haven't used the same signature for both methods.
When you say AVLTree "redefines" the insert, what exactly do you mean? It has to override the method, which means having exactly the same signature (modulo variance). Could you post the signatures of insert() in both BSTree and AVLTree? If you apply the @Override annotation in AVLTree (assuming a suitably recent JDK) you should get a warning/error if you've not got the right signature.
Polymorphism not working correctly
[ "", "java", "" ]
Does anyone know if its possible to create a new property on an existing Entity Type which is based on 2 other properties concatenated together? E.g. My Person Entity Type has these fields "ID", "Forename", "Surname", "DOB" I want to create a new field called "Fullname" which is ``` Forenames + " " + Surname ``` So i end up with "ID", "Forename", "Surname", "DOB", "Fullname". I know i can do this using Linq programmatically i.e. ``` var results = from p in db.People select new { ID = p.ID, Forename = p.Forename, Surname = p.Surname, DOB = p.DOB, Fullname = p.Forename+ " " + p.Surname }; ``` Then calling something like ``` var resultsAfterConcat = from q in results where q.Fullname.Contains(value) select q; ``` However i'd really like to use Linq to Entities to do this work for me at the Conceptual Model level.
Not yet, but maybe soon. First, note that your suggested query will not work at all in LINQ to Entities, with or without the property, because, at present, it doesn't support Contains. The new version of the Entity Framework in .NET 4.0, however, is supposed to support custom methods in LINQ to Entities queries. You can see [a video about this from PDC](http://mschnlnine.vo.llnwd.net/d1/pdc08/WMV-HQ/TL20.wmv). Essentially, you have to write the custom method twice; once in code, and once on your database (e.g., in a calculated field). See the video for more information.
For anyone happening in to read this so many years after the question has been answered: There is a more up to date and more DRY compliant answer here: [Using a partial class property inside LINQ statement](https://stackoverflow.com/questions/6879529/using-a-partial-class-property-inside-linq-statement)
Linq to Entities and concatenated properties
[ "", "c#", "linq", "c#-3.0", "linq-to-entities", "" ]