Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
Given some JS code like that one here: ``` for (var i = 0; i < document.getElementsByName('scale_select').length; i++) { document.getElementsByName('scale_select')[i].onclick = vSetScale; } ``` Would the code be faster if we put the result of getElementsByName into a variable before the loop and then use the variable after that? I am not sure how large the effect is in real life, with the result from `getElementsByName` typically having < 10 items. I'd like to understand the underlying mechanics anyway. Also, if there's anything else noteworthy about the two options, please tell me.
Definitely. The memory required to store that would only be a pointer to a DOM object and that's ***significantly*** less painful than doing a DOM search each time you need to use something! Idealish code: ``` var scale_select = document.getElementsByName('scale_select'); for (var i = 0; i < scale_select.length; i++) scale_select[i].onclick = vSetScale; ```
Caching the property lookup might help some, but c[aching the length of the array before starting the loop has proven to be faster.](http://www.robertnyman.com/2008/04/11/javascript-loop-performance/) So declaring a variable in the loop that holds the value of the scale\_select.length would speed up the entire loop some. ``` var scale_select = document.getElementsByName('scale_select'); for (var i = 0, al=scale_select.length; i < al; i++) scale_select[i].onclick = vSetScale; ```
How expensive are JS function calls (compared to allocating memory for a variable)?
[ "", "javascript", "function", "optimization", "" ]
I'm a Engineering student and I'm attending a Database and Information Systems class this semester. It's required that I produce a website/application that uses a database, using PHP/PGSQL. My questions are: * which IDE would you recommend? * does anyone have good tips and advices for a new developer? * it would help me (a lot) to develop this project attending some more "academic" aspects of the subject, such as the Entity/Association Model, etc. Are there any good tools to help structure my work? Thanks! EDIT: A few notes: * I forgot to ask one last thing, I tried installing BitNami's WAPP Stack. Does anyone know how good and/or reliable it is? * I'm actually working under Windows Vista Business (new laptop :S ). Would you recommend develloping under Linux for any specific reason?
* which IDE would you recommend? Anything that supports remote debugging. You will save yourselves hours and hours and learn so much quicker if you can actually step through your code. It always amazes me that more people don't use good debugging tools for PHP. The tools are there, not using them is crazy. FWIW I've always been a devotee of [Activestate Komodo](https://www.activestate.com/) - fantastic product. * does anyone have good tips and advices for a new developer? 1. get test infected. It will stand you in good stead in the future, and will force you to think about design issues properly. In fact the benefits are many and the drawbacks few. 2. learn to refactor, and make it part of your development "rhythm". 3. related to this is: think ahead, but don't programme ahead. Be aware that something you are writing will probably need to be bubbled up the class hierarchy so it is available more generically, but don't actual do the bubbling up till you need it. * it would help me (a lot) to develop this project attending some more "academic" aspects of the subject, such as the Entity/Association Model, etc. Are there any good tools to help structure my work? Learn about design patterns and apply the lessons you have learned from them. Don't programme the "PHP4" way. * I forgot to ask one last thing, I tried installing BitNami's WAPP Stack. Does anyone know how good and/or reliable it is? No idea, but if you have the time I'd avoid a prebuilt stack like WAMPP. It's important to understand how the pieces fit together. However, if you're running on Windows, you may not have time and your energy could be better focused on writing good code than working out how to install PHP, PostgreSQL and Apache. * I'm actually working under Windows Vista Business (new laptop :S ). Would you recommend developing under Linux for any specific reason? Yes I would. Assuming you are deploying on Linux (if you are deploying on Windows I'd be asking myself some serious questions!), then developing in the same environment is incredibly useful. I switched for that reason in 2005 and it was one of the most useful things I did development wise. However if you're a total \*nix newbie and are under tight time constraints maybe stick with what you know. If you have time to try things out, you'll find it pretty easy to get up and running with a good modern Linux desktop distro and the development work will fly along.
This is probably the only time in your career when you have the full freedom to chose what tools to use, so make the best use of it. Learn some of the classic tools that will go with you a long long way. So instead of using an IDE which you'll probably do all your professional life get a taste of using old school editors like vim/emacs. One advantage here is that the IDE will not hide all the details on getting your project to work, knowing the full technology stack is always a plus. For any technology that you'll be using try and get a good broad perspective before diving in to the implementation details, so for PHP I would suggest getting a grasp of XHTML, CSS and Javascript including libraries like jQuery; Object Relational Mapping (Take a look at Ruby on Rails, CakePHP, Django and SQL Alchemy) and Model View Controller Frameworks on various platforms. For PGSQL in addition to normalization try to get into the depths of information\_schema and the transaction isolation levels and when they're useful. Also important is understanding how the HTTP protocol works at a low level and how highly scalable websites can be built using HTTP. Rather than relying on tools I would say that just create a reading list on the topics mentioned above and that would automatically structure your thought process to take into account these kind of issues.
PHP Development - lot of (newbie) questions
[ "", "php", "ide", "" ]
Anybody knows how to do this? I got all the information of the email (body, subject, from , to, cc, bcc) and need to generate an .eml file out of it.
You can construct [`javax.mail.Message`](https://javaee-spec.java.net/nonav/javadocs/javax/mail/internet/MimeMessage.html) object (or have it already constructed from the mail server) and then you can use [`writeTo()`](https://javaee-spec.java.net/nonav/javadocs/javax/mail/internet/MimeMessage.html#writeTo%28java.io.OutputStream%29) method to save it to file. See [JavaMail API](http://www.oracle.com/technetwork/java/javamail/index.html) for more information.
You can create eml files with the following code. It works fine with thunderbird and probably with other email clients: ``` public static void createMessage(String to, String from, String subject, String body, List<File> attachments) { try { Message message = new MimeMessage(Session.getInstance(System.getProperties())); message.setFrom(new InternetAddress(from)); message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to)); message.setSubject(subject); // create the message part MimeBodyPart content = new MimeBodyPart(); // fill message content.setText(body); Multipart multipart = new MimeMultipart(); multipart.addBodyPart(content); // add attachments for(File file : attachments) { MimeBodyPart attachment = new MimeBodyPart(); DataSource source = new FileDataSource(file); attachment.setDataHandler(new DataHandler(source)); attachment.setFileName(file.getName()); multipart.addBodyPart(attachment); } // integration message.setContent(multipart); // store file message.writeTo(new FileOutputStream(new File("c:/mail.eml"))); } catch (MessagingException ex) { Logger.getLogger(Mailkit.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(Mailkit.class.getName()).log(Level.SEVERE, null, ex); } } ```
Create a .eml (email) file in Java
[ "", "java", "email", "outlook", "eml", "" ]
I was reading [this article](http://www.ibm.com/developerworks/java/library/j-dcl.html) about "Double-Checked locking" and out of the main topic of the article I was wondering why at some point of the article the author uses the next Idiom: > Listing 7. Attempting to solve the out-of-order write problem > > ``` > public static Singleton getInstance() > { > if (instance == null) > { > synchronized(Singleton.class) { //1 > Singleton inst = instance; //2 > if (inst == null) > { > synchronized(Singleton.class) { //3 > inst = new Singleton(); //4 > } > instance = inst; //5 > } > } > } > return instance; > } > ``` And my question is: Is there any reason to synchronize twice some code with the same lock? Have this any purpose it? Many thanks in advance.
The point of locking twice was to *attempt* to prevent out-of-order writes. The memory model specifies where reorderings can occur, partly in terms of locks. The lock ensures that no writes (including any within the singleton constructor) appear to happen after the "instance = inst;" line. However, to go deeper into the subject I'd recommend [Bill Pugh's article](http://www.cs.umd.edu/~pugh/java/memoryModel/DoubleCheckedLocking.html). And then never attempt it :)
The article refers to the pre-5.0 Java memory model (JMM). Under that model leaving a synchronised block forced writes out to main memory. So it appears to be an attempt to make sure that the Singleton object is pushed out before the reference to it. However, it doesn't quite work because the write to instance can be moved up into the block - the roach motel. However, the pre-5.0 model was never correctly implemented. 1.4 should follow the 5.0 model. Classes are initialised lazily, so you might as well just write ``` public static final Singleton instance = new Singleton(); ``` Or better, don't use singletons for they are evil.
Double checked locking Article
[ "", "java", "synchronization", "locking", "double-checked-locking", "" ]
I'm a web-guy stuck in "application world" in VS 2005. I created my windows forms program and want to give my end users the ability to install it (and some of it's resources) into a standard Program Files/App Directory location along with a start menu/desktop launcher. The help files don't give any instructions (that I can find). This seems like such a trivial task to create an installer - but it's eluding me. Any hints would be greatly appreciated!
You're looking for a "Setup Project" which should be under the "Other Project Types" -> "Setup and Deployment" category in the "New Project" dialog.
I would suggest using something WiX (windows installer XML). Its the toolkit most products from codeplex or OOB code drops use, and its pretty easy to get the hang of. There's also (in version 3) an IDE add-in called Votive to help make things 'easier'. Personally I find using WiX more flexible then using the built in Visual Studio installer template, though your means might vary. Take a look at <http://wix.sourceforge.net/> and there's also a great tutorial at <http://www.tramontana.co.hu/wix/>. If it seems kind of hard to start off with, persevere - I did and now I find it perfect for what I need.
Create program installer in Visual Studio 2005?
[ "", "c#", "visual-studio", "winforms", "" ]
Say I have the following web.config: ``` <?xml version="1.0" encoding="utf-8"?> <configuration> <system.web> <authentication mode="Windows"></authentication> </system.web> </configuration> ``` Using ASP.NET C#, how can I detect the Mode value of the Authentication tag?
Try `Context.User.Identity.AuthenticationType` Go for PB's answer folks
The mode property from the authenticationsection: [AuthenticationSection.Mode Property (System.Web.Configuration)](http://msdn.microsoft.com/en-us/library/system.web.configuration.authenticationsection.mode(VS.80).aspx). And you can even modify it. ``` // Get the current Mode property. AuthenticationMode currentMode = authenticationSection.Mode; // Set the Mode property to Windows. authenticationSection.Mode = AuthenticationMode.Windows; ``` This article describes [how to get a reference to the AuthenticationSection](http://msdn.microsoft.com/en-us/library/system.web.configuration.authenticationsection(VS.80).aspx).
Detecting Web.Config Authentication Mode
[ "", "c#", "asp.net", "authentication", "web-config", "" ]
How should I determine what to use for a listening socket's backlog parameter? Is it a problem to simply specify a very large number?
From the [docs](http://msdn.microsoft.com/en-us/library/ms739168(VS.85).aspx): > A value for the backlog of SOMAXCONN is a special constant that instructs the underlying service provider responsible for socket s to set the length of the queue of pending connections to a maximum reasonable value.
There's a very long answer to this in the [Winsock Programmer's FAQ](http://tangentsoft.net/wskfaq/advanced.html#backlog). It details the standard setting, and the dynamic backlog feature added in a hotfix to NT 4.0.
How to determine the value of socket listen() backlog parameter?
[ "", "c++", "c", "sockets", "tcp", "listen", "" ]
``` #include <vector> std::vector<long int> as; long int a(size_t n){ if(n==1) return 1; if(n==2) return -2; if(as.size()<n+1) as.resize(n+1); if(as[n]<=0) { as[n]=-4*a(n-1)-4*a(n-2); } return mod(as[n], 65535); } ``` The above code sample using memoization to calculate a recursive formula based on some input `n`. I know that this uses memoization, because I have written a purely recursive function that uses the same formula, but this one much, much faster for much larger values of `n`. I've never used vectors before, but I've done some research and I understand the concept of them. I understand that memoization is supposed to store each calculated value, so that instead of performing the same calculations over again, it can simply retrieve ones that have already been calculated. My question is: how is this memoization, and how does it work? I can't seem to see in the code at which point it checks to see if a value for n already exists. Also, I don't understand the purpose of the `if(as[n]<=0)`. This formula can yield positive and negative values, so I'm not sure what this check is looking for. --- Thank you, I think I'm close to understanding how this works, it's actually a bit more simple than I was thinking it was. I do not think the values in the sequence can ever be 0, so this should work for me, as I think n has to start at 1. However, if zero was a viable number in my sequence, what is another way I could solve it? For example, what if five could never appear? Would I just need to fill my vector with fives? Edit: Wow, I got a lot of other responses while checking code and typing this one. Thanks for the help everyone, I think I understand it now.
`if (as[n] <= 0)` is the check. If valid values can be negative like you say, then you need a different sentinel to check against. Can valid values ever be zero? If not, then just make the test `if (as[n] == 0)`. This makes your code easier to write, because by default vectors of `int`s are filled with zeroes.
The code appears to be incorrectly checking is (as[n] <= 0), and recalculates the negative values of the function(which appear to be approximately every other value). This makes the work scale linearly with n instead of 2^n with the recursive solution, so it runs a lot faster. Still, a better check would be to test if (as[n] == 0), which appears to run 3x faster on my system. Even if the function can return 0, a 0 value just means it will take slightly longer to compute (although if 0 is a frequent return value, you might want to consider a separate vector that flags whether the value has been computed or not instead of using a single vector to store the function's value and whether it has been computed)
How does this C++ function use memoization?
[ "", "c++", "dynamic-programming", "memoization", "" ]
I have a LAMP (PHP) web app which need to interface with programs on an IBM 3270 mainframe (via Microsoft SNA Server). One solution I'm looking at is screen-scraping via 3270. (I'm integrating the present with the past!) Many years ago, I wrote C code which used HLLAPI as the basis for such a task. 1. Is HLLAPI still the best way to approach this task? 2. If so, would I be best off just writing a C app to undertake the work necessary and exec() this C app from php? 3. Are there any open source HLLAPI providers for Linux? (In the past I used commercial solutions such as Cleo.)
I haven't used it but maybe look at <http://x3270.bgp.nu/> which says has a version: > s3270 is a displayless version for > writing screen-scraping scripts
I'm currently trying to do a similar thing but with a command line Python script. I open a pipe to the s3270 (on Windows the exe name is ws3270) to connect to the server and send all commands. Read carefully those part of the documentation for scripting: <http://x3270.bgp.nu/wc3270-man.html#Actions> <http://x3270.bgp.nu/x3270-script.html#Script-Specific-Actions>
How to 3270 screen-scrape from a Linux-based web app
[ "", "php", "c", "mainframe", "3270", "hllapi", "" ]
Does anybody know, if closures will be in Java 7?
At Devoxx 2008, [Mark Reinhold made it clear](http://java.dzone.com/articles/java-7-update-mark-reinhold-de) that closures *will not* be included in Java 7. --- Wait! Closures *will* be included in Java 7. Mark Reinhold [announced this reversal](http://blogs.oracle.com/mr/entry/closures) at Devoxx 2009. --- Belay that! Closures (*lambda expressions*) have been deferred until Java 8. Follow [Project Lambda (JSR 335)](http://openjdk.java.net/projects/lambda/) for more information.
It is unknown until the Java SE 7 JSR is created (presumably by Danny Coward) and an expert group is formed and the contents selected. My Java 7 page is a good collection of links about Java 7 in general and has links to all of the closures proposals and blog entries: <http://tech.puredanger.com/java7#closures> And I maintain a Java 7 link blog where you can find links on closures and other stuff at: <http://java7.tumblr.com> And you might find my Java 7 Predictions blog post to be interesting as well if you want my opinions: <http://tech.puredanger.com/2008/08/02/java7-prediction-update/> UPDATE: Mark Reinhold stated at Devoxx in Dec. 08 that closures will NOT be included in Java 7 due to a lack of consensus on how to implement.
What’s the current state of closures in Java?
[ "", "java", "closures", "" ]
Most people say *never* throw an exception out of a destructor - doing so results in undefined behavior. Stroustrup makes the point that *"the vector destructor explicitly invokes the destructor for every element. This implies that if an element destructor throws, the vector destruction fails... There is really no good way to protect against exceptions thrown from destructors, so the library makes no guarantees if an element destructor throws" (from Appendix E3.2)*. [This article](http://www.kolpackov.net/projects/c++/eh/dtor-1.xhtml) seems to say otherwise - that throwing destructors are more or less okay. *So my question is this - if throwing from a destructor results in undefined behavior, how do you handle errors that occur during a destructor?* If an error occurs during a cleanup operation, do you just ignore it? If it is an error that can potentially be handled up the stack but not right in the destructor, doesn't it make sense to throw an exception out of the destructor? Obviously these kinds of errors are rare, but possible.
Throwing an exception out of a destructor is dangerous. If another exception is already propagating the application will terminate. **But** said "terminate" is a very well specified behaviour of majority of compilers, hence it's almost never "Undefined Behaviour" (depending on compiler). ``` #include <iostream> class Bad { public: // Added the noexcept(false) so the code keeps its original meaning. // Post C++11 destructors are by default `noexcept(true)` and // this will (by default) call terminate if an exception is // escapes the destructor. // // But this example is designed to show that terminate is called // if two exceptions are propagating at the same time. ~Bad() noexcept(false) { throw 1; } }; class Bad2 { public: ~Bad2() { throw 1; } }; int main(int argc, char* argv[]) { try { Bad bad; } catch(...) { std::cout << "Print This\n"; } try { if (argc > 3) { Bad bad; // This destructor will throw an exception that escapes (see above) throw 2; // But having two exceptions propagating at the // same time causes terminate to be called. } else { Bad2 bad; // The exception in this destructor will // cause terminate to be called. } } catch(...) { std::cout << "Never print this\n"; } } ``` This basically boils down to: Anything dangerous (i.e. that could throw an exception) should be done via public methods (not necessarily directly). The user of your class can then potentially handle these situations by using the public methods and catching any potential exceptions. The destructor will then finish off the object by calling these methods (if the user did not do so explicitly), but any exceptions throw are caught and dropped (after attempting to fix the problem). So in effect you pass the responsibility onto the user. If the user is in a position to correct exceptions they will manually call the appropriate functions and processes any errors. If the user of the object is not worried (as the object will be destroyed) then the destructor is left to take care of business. # An example: std::fstream The close() method can potentially throw an exception. The destructor calls close() if the file has been opened but makes sure that any exceptions do not propagate out of the destructor. So if the user of a file object wants to do special handling for problems associated to closing the file they will manually call close() and handle any exceptions. If on the other hand they do not care then the destructor will be left to handle the situation. Scott Meyers has an excellent article about the subject in his book "Effective C++" ### Edit: Apparently also in "More Effective C++" [Item 11: Prevent exceptions from leaving destructors](http://bin-login.name/ftp/pub/docs/programming_languages/cpp/cffective_cpp/MEC/MI11_FR.HTM)
Throwing out of a destructor can result in a crash, because this destructor might be called as part of "Stack unwinding". Stack unwinding is a procedure which takes place when an exception is thrown. In this procedure, all the objects that were pushed into the stack since the "try" and until the exception was thrown, will be terminated -> their destructors will be called. And during this procedure, another exception throw is not allowed, because it's not possible to handle two exceptions at a time, thus, this will provoke a call to abort(), the program will crash and the control will return to the OS.
If you shouldn't throw exceptions in a destructor, how do you handle errors in it?
[ "", "c++", "exception", "destructor", "raii", "" ]
I'm writing a Winforms application and I've been writing these awful HTML reports where I have templates set up and use String.Replace to get my variables into the templates, then output the results to a WebBrowser control. I really don't like this set up. I'd love to be able to use ASP.NET for my reports, but my clients don't want to have to run IIS on all the machines this is getting installed on, so that's not really an option.
Like was said earlier, use the report viewer with client side reporting. You can create reports the same way as you do for sql reporting services, except you dont need sql server(nor asp.net). Plus you have complete control over them(how you present, how you collect data, what layer they are generated in, etc). You can also export as PDF and excel. Here is a great book i recommend to everyone to look at if interested in client side reports. It gives a lot of great info and many different scenarios and ways to use client side reporting. <http://www.apress.com/book/view/9781590598542>
Have you tried the [reportviewer control](http://www.gotreportviewer.com/)? Your customers will be happy with the fancy new reports. It is template based and can include data from database or from code data, you can use parameters, images, and the result can be exported to Excel or to PDF. Plus the control has some basic functionality like paging, zooming, printing, finding... Why do you need ASP.NET? I don't see, what difference it can make. Maybe you can render your HTML more easily, but it's still not "real" reporting.
Reports in a .NET Winforms App
[ "", "c#", ".net", "winforms", "report", "" ]
So, one commonly heard comment when talking about performance is that you write your code with whatever language gets the job done fastest. If performance in specific areas is a problem, then rewrite those bits in C/C++. But, what if you're starting with a native C++ app? What options do you have if you want to write the easy bits, or refactor the old bits, in a language like Python, Ruby, C#, or whatever? Keep in mind that transferring data between the native and other sides is a must. Being able to simply call a function written in an "easier" language, while passing C++ classes as data, would be beautiful. We've got a crusty Win32 app that would benefit greatly if we could crank out new code, or refactor old code, in C# or something. Very little of it requires the complexity of C++, and dealing with the little fiddly bits is dragging down the programming process.
As [Aaron Fischer](https://stackoverflow.com/questions/147378/options-for-refactoring-bits-of-code-away-from-native-c#147446) suggests, try recompiling your C++ application with the /clr option turned on and then start leveraging the .Net platform. CLI/C++ is pretty easy to pick up if you know C# and C++ already and it provides the bridge between the .Net world and native C++. If your current C++ code can't compile cleanly with /clr turned on then I'd suggest trying to build your application as a static lib (without /clr enabled) and then have your main() be in a CLI/C++ project that calls your legacy app entry point. That way you can at least start leveraging .Net for new functionality. For examples of "legacy" C/C++ apps that have been "ported" to .Net CLI/C++ check out the .Net ports of [Quake 2](http://www.vertigosoftware.com/Quake2.htm) and [Quake 3: Arena](http://gregs-blog.com/2008/01/22/update-quake-3-arena-net-port-is-done/).
If you want to work between C++ and Python, than [Boost Python](http://www.boost.org/doc/libs/1_36_0/libs/python/doc/index.html) is what you're looking for. You can write C Python bindings by hand for Cython, but that limits in many ways how you're going to write your code. This is the easiest way, as seen in some snippets from [this tutorial](http://www.boost.org/doc/libs/1_36_0/libs/python/doc/tutorial/doc/html/index.html): A simple function that performs a hello world: ``` char const* greet() { return "hello, world"; } ``` The Boost python code needed to expose it to python: ``` #include <boost/python.hpp> BOOST_PYTHON_MODULE(hello_ext) { using namespace boost::python; def("greet", greet); } ``` How to use this code from python: ``` >>> import hello_ext >>> print hello.greet() hello, world ``` Going in the opposite direction is bit tougher, since python doesn't compile to native code. You have to embed the python interpreter into your C++ application, but the work necessary to do that is documented [here](http://www.boost.org/doc/libs/1_36_0/libs/python/doc/tutorial/doc/html/python/embedding.html). This is an example of calling the python interpreter and extracting the result (the python interpreter defines the object class for use in C++): ``` object result = eval("5 ** 2"); int five_squared = extract<int>(result); ```
Options for refactoring bits of code away from native C++?
[ "", "c++", "performance", "refactoring", "native", "" ]
Im searching a Template Lib or Template Engine for generating HTML (XML) that runs under Jython (Jython 2.5 Alpha is ok).
Use StringTemplate, see <http://www.cs.usfca.edu/~parrt/papers/mvc.templates.pdf> for details of why. There is nothing better, and it supports both Java and Python (and .NET, etc.).
Have you tried [Cheetah](http://www.cheetahtemplate.org/), I don't have direct experience running it under Jython but there seem to be some people that do.
Template Lib (Engine) in Python running with Jython
[ "", "python", "jython", "template-engine", "" ]
I have a form with some radio buttons that are disabled by default. When a value gets entered into a text box, the radio buttons are enabled via javascript. The user then selects one of the radio buttons and clicks on a submit button which posts back to the server. When I get back to the server, the radio button that user clicked is not showing as checked. I'll use 'rbSolid' as the radio button I'm focusing on. I handle the 'onclick' event of the radio buttons, but I don't have the function doing anything yet other than firing: > Me.rbSolid.Attributes.Add("onclick", "styleLookupChanged(this);") On the client, this enables the radio button when the textbox value is changed: > document.getElementById("ctl00\_MainLayoutContent\_WebPanel4\_rbSolid").disabled = false; I then click the radio button then post back via a button, but back on the server this is always false: > If Me.rbSolid.Checked Then... If I have the radio button enabled by default, it shows as checked correctly. Thanks for any help!
This has to do with how ASP.NET postback data. If a control is disabled `control.enabled = false` when the page is rendered than the values will not be posted back to the server. How I have solved it in the past is to set the disabled flag using attributes tags instead of using the Enabled property. So instead of `control.enabled = false`, you use `control.attributes.add("disabled", "disabled")`.
This isn't working for me. I added: ``` Me.rbSolid.Style.Add("background-color", "red") Me.rbSolid.Style.Add("disabled", "true") ``` and the background style works but the `disabled` did not. It's still editable when the form renders. Here's the source after load: ``` <span style="font-family:Verdana;font-size:8pt;background-color:red;Disabled:true;"> <input id="ctl00_MainLayoutContent_WebPanel4_rbSolid" type="radio" name="ctl00$MainLayoutContent$WebPanel4$DetailType" value="rbSolid" onclick="styleLookupChanged(this);"/> <label for="ctl00_MainLayoutContent_WebPanel4_rbSolid">Solid</label> </span> ```
ASP.NET not seeing Radio Button value change
[ "", "asp.net", "javascript", "" ]
Relating to my [earlier question](https://stackoverflow.com/questions/48733/javahibernate-jpa-designing-the-server-data-reload), I want to ensure all the child objects are loaded as I have a multiple threads that may need to access the data (and thus avoid lazy loading exceptions). I understand the way to do this is to use the "fetch" keyword in the query (EJB QL). Like this: ``` select distinct o from Order o left join fetch o.orderLines ``` Assuming a model with an `Order` class which has a set of `OrderLines` in it. My question is that the "distinct" keyword seems to be needed as otherwise I seem to get back an `Order` for each `OrderLine`. Am I doing the right thing? Perhaps more importantly, is there a way to pull in all child objects, no matter how deep? We have around 10-15 classes and for the server we will need everything loaded... I was avoiding using `FetchType.EAGER` as that meant its always eager and in particular the web front end loads everything - but perhaps that is the way to go - is that what you do? I seem to remember us trying this before and then getting really slow webpages - but perhaps that means we should be using a second-level cache?
Changing the annotation is a bad idea IMO. As it can't be changed to lazy at runtime. Better to make everything lazy, and fetch as needed. I'm not sure I understand your problem without mappings. Left join fetch should be all you need for the use case you describe. Of course you'll get back an order for every orderline if orderline has an order as its parent.
I'm not sure about using the fetch keyword in your EJBQL, you might be getting it confused with the annotation... Have you tried adding the FetchType property to your relationship attribute? @OneToMany(fetch=FetchType.EAGER)? See: <http://java.sun.com/javaee/5/docs/api/javax/persistence/FetchType.html> <http://www.jroller.com/eyallupu/entry/hibernate_exception_simultaneously_fetch_multiple>
Hibernate (JPA) how to do an eager query, loading all child objects
[ "", "java", "hibernate", "jpa", "ejbql", "" ]
I've been building an error logging app recently and was after a way of accurately timestamping the incoming data. When I say accurately I mean each timestamp should be accurate relative to each other (no need to sync to an atomic clock or anything like that). I've been using datetime.now() as a first stab, but this isn't perfect: ``` >>> for i in range(0,1000): ... datetime.datetime.now() ... datetime.datetime(2008, 10, 1, 13, 17, 27, 562000) datetime.datetime(2008, 10, 1, 13, 17, 27, 562000) datetime.datetime(2008, 10, 1, 13, 17, 27, 562000) datetime.datetime(2008, 10, 1, 13, 17, 27, 562000) datetime.datetime(2008, 10, 1, 13, 17, 27, 578000) datetime.datetime(2008, 10, 1, 13, 17, 27, 578000) datetime.datetime(2008, 10, 1, 13, 17, 27, 578000) datetime.datetime(2008, 10, 1, 13, 17, 27, 578000) datetime.datetime(2008, 10, 1, 13, 17, 27, 578000) datetime.datetime(2008, 10, 1, 13, 17, 27, 609000) datetime.datetime(2008, 10, 1, 13, 17, 27, 609000) datetime.datetime(2008, 10, 1, 13, 17, 27, 609000) etc. ``` The changes between clocks for the first second of samples looks like this: ``` uSecs difference 562000 578000 16000 609000 31000 625000 16000 640000 15000 656000 16000 687000 31000 703000 16000 718000 15000 750000 32000 765000 15000 781000 16000 796000 15000 828000 32000 843000 15000 859000 16000 890000 31000 906000 16000 921000 15000 937000 16000 968000 31000 984000 16000 ``` So it looks like the timer data is only updated every ~15-32ms on my machine. The problem comes when we come to analyse the data because sorting by something other than the timestamp and then sorting by timestamp again can leave the data in the wrong order (chronologically). It would be nice to have the time stamps accurate to the point that any call to the time stamp generator gives a unique timestamp. I had been considering some methods involving using a time.clock() call added to a starting datetime, but would appreciate a solution that would work accurately across threads on the same machine. Any suggestions would be very gratefully received.
You're unlikely to get sufficiently fine-grained control that you can completely eliminate the possibility of duplicate timestamps - you'd need resolution smaller than the time it takes to generate a datetime object. There are a couple of other approaches you might take to deal with it: 1. Deal with it. Leave your timestamps non-unique as they are, but rely on python's sort being stable to deal with reordering problems. Sorting on timestamp *first*, then something else will retain the timestamp ordering - you just have to be careful to always start from the timestamp ordered list every time, rather than doing multiple sorts on the same list. 2. Append your own value to enforce uniqueness. Eg. include an incrementing integer value as part of the key, or append such a value only if timestamps are different. Eg. The following will guarantee unique timestamp values: ``` class TimeStamper(object): def __init__(self): self.lock = threading.Lock() self.prev = None self.count = 0 def getTimestamp(self): with self.lock: ts = str(datetime.now()) if ts == self.prev: ts +='.%04d' % self.count self.count += 1 else: self.prev = ts self.count = 1 return ts ``` For multiple processes (rather than threads), it gets a bit trickier though.
time.clock() only measures wallclock time on Windows. On other systems, time.clock() actually measures CPU-time. On those systems time.time() is more suitable for wallclock time, and it has as high a resolution as Python can manage -- which is as high as the OS can manage; usually using gettimeofday(3) (microsecond resolution) or ftime(3) (millisecond resolution.) Other OS restrictions actually make the real resolution a lot higher than that. datetime.datetime.now() uses time.time(), so time.time() directly won't be better. For the record, if I use datetime.datetime.now() in a loop, I see about a 1/10000 second resolution. From looking at your data, you have much, much coarser resolution than that. I'm not sure if there's anything Python as such can do, although you may be able to convince the OS to do better through other means. I seem to recall that on Windows, time.clock() is actually (slightly) more accurate than time.time(), but it measures wallclock since the first call to time.clock(), so you have to remember to 'initialize' it first.
Accurate timestamping in Python logging
[ "", "python", "logging", "timer", "timestamp", "" ]
In particular, wouldn't there have to be some kind of function pointer in place anyway?
Non virtual member functions are really just a syntactic sugar as they are almost like an ordinary function but with access checking and an implicit object parameter. ``` struct A { void foo (); void bar () const; }; ``` is basically the same as: ``` struct A { }; void foo (A * this); void bar (A const * this); ``` The vtable is needed so that we call the right function for our specific object instance. For example, if we have: ``` struct A { virtual void foo (); }; ``` The implementation of 'foo' might approximate to something like: ``` void foo (A * this) { void (*realFoo)(A *) = lookupVtable (this->vtable, "foo"); (realFoo)(this); // Make the call to the most derived version of 'foo' } ```
I think that the phrase "*classes with virtual functions are implemented with vtables*" is misleading you. The phrase makes it sound like classes with virtual functions are implemented "*in way A*" and classes without virtual functions are implemented "*in way B*". In reality, classes with virtual functions, ***in addition to*** being implemented as classes are, they also have a vtable. Another way to see it is that "'vtables' implement the 'virtual function' part of a class". ## More details on how they both work: All classes (with virtual or non-virtual methods) are structs. The **only** difference between a struct and a class in C++ is that, by default, members are public in structs and private in classes. Because of that, I'll use the term class here to refer to both structs and classes. Remember, they are almost synonyms! ### Data Members Classes are (as are structs) just blocks of contiguous memory where each member is stored in sequence. Note that some times there will be gaps between members for CPU architectural reasons, so the block can be larger than the sum of its parts. ### Methods Methods or "member functions" are an illusion. In reality, there is no such thing as a "member function". A function is always just a sequence of machine code instructions stored somewhere in memory. To make a call, the processor jumps to that position of memory and starts executing. You could say that all methods and functions are 'global', and any indication of the contrary is a convenient illusion enforced by the compiler. Obviously, a method acts like it belongs to a specific object, so clearly there is more going on. To tie a particular call of a method (a function) to a specific object, every member method has a hidden argument that is a pointer to the object in question. The member is *hidden* in that you don't add it to your C++ code yourself, but there is nothing magical about it -- it's very real. When you say this: ``` void CMyThingy::DoSomething(int arg); { // do something } ``` The compiler *really* does this: ``` void CMyThingy_DoSomething(CMyThingy* this, int arg) { /do something } ``` Finally, when you write this: ``` myObj.doSomething(aValue); ``` the compiler says: ``` CMyThingy_DoSomething(&myObj, aValue); ``` No need for function pointers anywhere! The compiler knows already which method you are calling so it calls it directly. Static methods are even simpler. They don't have a *this* pointer, so they are implemented exactly as you write them. That's is! The rest is just convenient syntax sugaring: The compiler knows which class a method belongs to, so it makes sure it doesn't let you call the function without specifying which one. It also uses that knowledge to translates `myItem` to `this->myItem` when it's unambiguous to do so. *(yeah, that's right: member access in a method is **always** done indirectly via a pointer, even if you don't see one)* (**Edit**: Removed last sentence and posted separately so it can be criticized separately)
If classes with virtual functions are implemented with vtables, how is a class with no virtual functions implemented?
[ "", "c++", "virtual-functions", "" ]
I have a program that uses the mt19937 random number generator from boost::random. I need to do a random\_shuffle and want the random numbers generated for this to be from this shared state so that they can be deterministic with respect to the mersenne twister's previously generated numbers. I tried something like this: ``` void foo(std::vector<unsigned> &vec, boost::mt19937 &state) { struct bar { boost::mt19937 &_state; unsigned operator()(unsigned i) { boost::uniform_int<> rng(0, i - 1); return rng(_state); } bar(boost::mt19937 &state) : _state(state) {} } rand(state); std::random_shuffle(vec.begin(), vec.end(), rand); } ``` But i get a template error calling random\_shuffle with rand. However this works: ``` unsigned bar(unsigned i) { boost::mt19937 no_state; boost::uniform_int<> rng(0, i - 1); return rng(no_state); } void foo(std::vector<unsigned> &vec, boost::mt19937 &state) { std::random_shuffle(vec.begin(), vec.end(), bar); } ``` Probably because it is an actual function call. But obviously this doesn't keep the state from the original mersenne twister. What gives? Is there any way to do what I'm trying to do without global variables?
In C++03, you cannot instantiate a template based on a function-local type. If you move the rand class out of the function, it should work fine (disclaimer: not tested, there could be other sinister bugs). This requirement has been relaxed in C++0x, but I don't know whether the change has been implemented in GCC's C++0x mode yet, and I would be highly surprised to find it present in any other compiler.
In the comments, Robert Gould asked for a working version for posterity: ``` #include <algorithm> #include <functional> #include <vector> #include <boost/random.hpp> struct bar : std::unary_function<unsigned, unsigned> { boost::mt19937 &_state; unsigned operator()(unsigned i) { boost::uniform_int<> rng(0, i - 1); return rng(_state); } bar(boost::mt19937 &state) : _state(state) {} }; void foo(std::vector<unsigned> &vec, boost::mt19937 &state) { bar rand(state); std::random_shuffle(vec.begin(), vec.end(), rand); } ```
Using boost::random as the RNG for std::random_shuffle
[ "", "c++", "stl", "boost-random", "" ]
I want to discover all xml files that my ClassLoader is aware of using a wildcard pattern. Is there any way to do this?
It requires a little trickery, but here's an relevant [blog entry](http://bill.burkecentral.com/2008/01/14/scanning-java-annotations-at-runtime/). You first figure out the URLs of the jars, then open the jar and scan its contents. I think you would discover the URLs of all jars by looking for `/META-INF/MANIFEST.MF'. Directories would be another matter.
A Spring `ApplicationContext` can do this trivially: ``` ApplicationContext context = new ClassPathXmlApplicationContext("applicationConext.xml"); Resource[] xmlResources = context.getResources("classpath:/**/*.xml"); ``` See [ResourcePatternResolver#getResources](http://static.springframework.org/spring/docs/2.5.x/api/org/springframework/core/io/support/ResourcePatternResolver.html#getResources(java.lang.String)e), or [ApplicationContext](http://static.springframework.org/spring/docs/2.5.x/api/org/springframework/context/ApplicationContext.html).
How can I discover resources in a Java jar with a wildcard name?
[ "", "java", "classpath", "" ]
What's the difference between `file` and `open` in Python? When should I use which one? (Say I'm in 2.5)
You should always use `open()`. As the [documentation](http://docs.python.org/2/library/functions.html#file "BuiltinFuncs Doc") states: > When opening a file, it's preferable > to use open() instead of invoking this > constructor directly. file is more > suited to type testing (for example, > writing "isinstance(f, file)"). Also, `file()` [has been removed](http://docs.python.org/release/3.0/whatsnew/3.0.html#builtins) since Python 3.0.
Two reasons: The python philosophy of "There ought to be one way to do it" and `file` is going away. `file` is the actual type (using e.g. `file('myfile.txt')` is calling its constructor). `open` is a factory function that will return a file object. In python 3.0 `file` is going to move from being a built-in to being implemented by multiple classes in the `io` library (somewhat similar to Java with buffered readers, etc.)
Python - When to use file vs open
[ "", "python", "file", "" ]
I have a dictionary of 200,000 items (the keys are strings and the values are integers). What is the best/most pythonic way to print the items sorted by descending value then ascending key (i.e. a 2 key sort)? ``` a={ 'keyC':1, 'keyB':2, 'keyA':1 } b = a.items() b.sort( key=lambda a:a[0]) b.sort( key=lambda a:a[1], reverse=True ) print b >>>[('keyB', 2), ('keyA', 1), ('keyC', 1)] ```
You can't sort dictionaries. You have to sort the list of items. Previous versions were wrong. When you have a numeric value, it's easy to sort in reverse order. These will do that. But this isn't general. This only works because the value is numeric. ``` a = { 'key':1, 'another':2, 'key2':1 } b= a.items() b.sort( key=lambda a:(-a[1],a[0]) ) print b ``` Here's an alternative, using an explicit function instead of a lambda and the cmp instead of the key option. ``` def valueKeyCmp( a, b ): return cmp( (-a[1], a[0]), (-b[1], b[0] ) ) b.sort( cmp= valueKeyCmp ) print b ``` The more general solution is actually two separate sorts ``` b.sort( key=lambda a:a[1], reverse=True ) b.sort( key=lambda a:a[0] ) print b ```
``` data = { 'keyC':1, 'keyB':2, 'keyA':1 } for key, value in sorted(data.items(), key=lambda x: (-1*x[1], x[0])): print key, value ```
Python 2.5 dictionary 2 key sort
[ "", "python", "" ]
I'm having an unusual problem with an IE document with contentEditable set to true. Calling select() on a range that is positioned at the end of a text node that immediately precedes a block element causes the selection to be shifted to the right one character and appear where it shouldn't. I've submitted a bug to Microsoft against IE8. If you can, please vote for this issue so that it can be fixed. <https://connect.microsoft.com/IE/feedback/ViewFeedback.aspx?FeedbackID=390995> I've written a test case to demonstrate the effect: ``` <html> <body> <iframe id="editable"> <html> <body> <div id="test"> Click to the right of this line -&gt; <p id="par">Block Element</p> </div> </body> </html> </iframe> <input id="mytrigger" type="button" value="Then Click here to Save and Restore" /> <script type="text/javascript"> window.onload = function() { var iframe = document.getElementById('editable'); var doc = iframe.contentDocument || iframe.contentWindow.document; // An IFRAME without a source points to a blank document. Here we'll // copy the content we stored in between the IFRAME tags into that // document. It's a hack to allow us to use only one HTML file for this // test. doc.body.innerHTML = iframe.textContent || iframe.innerHTML; // Marke the IFRAME as an editable document if (doc.body.contentEditable) { doc.body.contentEditable = true; } else { var mydoc = doc; doc.designMode = 'On'; } // A function to demonstrate the bug. var myhandler = function() { // Step 1 Get the current selection var selection = doc.selection || iframe.contentWindow.getSelection(); var range = selection.createRange ? selection.createRange() : selection.getRangeAt(0); // Step 2 Restore the selection if (range.select) { range.select(); } else { selection.removeAllRanges(); selection.addRange(range); doc.body.focus(); } } // Set up the button to perform the test code. var button = document.getElementById('mytrigger'); if (button.addEventListener) { button.addEventListener('click', myhandler, false); } else { button.attachEvent('onclick', myhandler); } } </script> </body> </html> ``` The problem is exposed in the myhandler function. This is all that I'm doing, there is no Step 3 in between the saving and restoring the selection, and yet the cursor moves. It doesn't seem to happen unless the selection is empty (ie. I have a blinking cursor, but no text), and it only seems to happen whenever the cursor is at the end of a text node that immediately precedes a block node. It seems that the range is still in the correct position (if I call parentElement on the range it returns the div), but if I get a new range from the current selection, the new range is inside the paragraph tag, and that is its parentElement. **How do I work around this and consistently save and restore the selection in internet explorer?**
I've figured out a few methods for dealing with IE ranges like this. If all you want to do is save where the cursor is, and then restore it, you can use the pasteHTML method to insert an empty span at the current position of the cursor, and then use the moveToElementText method to put it back at that position again: ``` // Save position of cursor range.pasteHTML('<span id="caret"></span>') ... // Create new cursor and put it in the old position var caretSpan = iframe.contentWindow.document.getElementById("caret"); var selection = iframe.contentWindow.document.selection; newRange = selection.createRange(); newRange.moveToElementText(caretSpan); ``` Alternatively, you can count how many characters precede the current cursor position and save that number: ``` var selection = iframe.contentWindow.document.selection; var range = selection.createRange().duplicate(); range.moveStart('sentence', -1000000); var cursorPosition = range.text.length; ``` To restore the cursor, you set it to the beginning and then move it that number of characters: ``` var newRange = selection.createRange(); newRange.move('sentence', -1000000); newRange.move('character', cursorPosition); ``` Hope this helps.
I've had a bit of a dig & unfortunately can't see a workaround... Although one thing I noticed while debugging the javascript, it seems like the problem is actually with the range object itself rather than with the subsequent `range.select()`. If you look at the values on the range object that `selection.createRange()` returns, yes the parent dom object may be correct, but the positioning info is already referring to the start of the next line (i.e. offsetLeft/Top, boundingLeft/Top, etc are already wrong). Based on the info [here](http://www.quirksmode.org/dom/range_intro.html), [here](http://www.quirksmode.org/dom/w3c_range.html) and [here](http://msdn.microsoft.com/en-us/library/ms535872(VS.85).aspx), I think you're out of luck with IE, since you only have access to Microsoft's TextRange object, which appears to be broken. From my experimentation, you can move the range around and position it exactly where it should be, but once you do so, the range object automatically shifts down to the next line even before you've tried to `.select()` it. For example, you can see the problem by putting this code in between your Step 1 & Step 2: ``` if (range.boundingWidth == 0) { //looks like its already at the start of the next line down... alert('default position: ' + range.offsetLeft + ', ' + range.offsetTop); //lets move the start of the range one character back //(i.e. select the last char on the line) range.moveStart("character", -1); //now the range looks good (except that its width will be one char); alert('one char back: ' + range.offsetLeft + ', ' + range.offsetTop); //calculate the true end of the line... var left = range.offsetLeft + range.boundingWidth; var top = range.offsetTop; //now we can collapse back down to 0 width range range.collapse(); //the position looks right alert('moving to: ' + left + ', ' + top); //move there. range.moveToPoint(left, top); //oops... on the next line again... stupid IE. alert('moved to: ' + range.offsetLeft + ', ' + range.offsetTop); } ``` So, unfortunately it doesn't look like there's any way to ensure that the range is in the right spot when you select it again. Obviously there's the trivial fix to your code above, by changing Step 2 it to this: ``` // Step 2 Restore the selection if (range.select) { if (range.boundingWidth > 0) { range.select(); } } else { selection.removeAllRanges(); selection.addRange(range); doc.body.focus(); } ``` But presumably, you actually want to do something between Step 1 & Step 2 in your actual which involves moving the selection, hence the need to re-set it. But just in case. :) So, the best I can do is go & vote for the bug you created... Hopefully they'll fix it.
IE TextRange select method not working properly
[ "", "javascript", "internet-explorer", "" ]
My application is preparing a cover-sheet for submitting documents by fax. I identify the batch by printing a [Code39](http://en.wikipedia.org/wiki/Code_39) on it. The incoming faxes are received as tif files and my small c# service is polling for new faxes and calling a decoding function. Currently I use a Win32 dll to recognize the barcode ([QSbar39](http://www.qsbarcode.de/)) and I am facing some problems with it - timeouts, hangs, errors etc. which are painful to handle. I'd prefer the have some free .Net component or an open source class to integrate. Whould you take a different approach? What tool do you use? Many thanks for your answers!
[BarBara](http://sourceforge.net/projects/barbara/) is an open source barcode recognition library. It certainly isn't perfect, but I have gotten it to work (if I remember it needed some twiddling to get it to compile in VS2008) pretty well.
I've used this java libarary with good results, and have gotten it to compile in .Net with minimal effort. It's been around for a while and works pretty well. It had some minor issues with EAN codes, but that has probably been resolved now. <http://barbecue.sourceforge.net/>
Fax barcode recognition software to integrate in a c# application
[ "", "c#", ".net", "barcode", "" ]
I'm trying to create a Zip file from .Net that can be read from Java code. I've used SharpZipLib to create the Zip file but also if the file generated is valid according to the CheckZip function of the #ZipLib library and can be successfully uncompressed via WinZip or WinRar I always get an error when trying to uncompress it using the Java.Utils.Zip class in Java. Problem seems to be in the wrong header written by SharpZipLib, I've also posted a question on the SharpDevelop forum but with no results (see <http://community.sharpdevelop.net/forums/t/8272.aspx> for info) but with no result. Has someone a code sample of compressing a Zip file with .Net and de-compressing it with the Java.Utils.Zip class? Regards Massimo
I have used [DotNetZip library](http://www.codeplex.com/DotNetZip) and it seems to work properly. Typical code: ``` using (ZipFile zipFile = new ZipFile()) { zipFile.AddDirectory(sourceFolderPath); zipFile.Save(archiveFolderName); } ```
I had the same problem creating zips with SharpZipLib (latest version) and extracting with java.utils.zip. Here is what fixed the problem for me. I had to force the exclusion of the zip64 usage: ``` ZipOutputStream s = new ZipOutputStream(File.Create(someZipFileName)) s.UseZip64 = UseZip64.Off; ```
Help in creating Zip files from .Net and reading them from Java
[ "", "java", ".net", "interop", "zip", "" ]
I have a products table... [alt text http://img357.imageshack.us/img357/6393/productscx5.gif](http://img357.imageshack.us/img357/6393/productscx5.gif) and a revisions table, which is supposed to track changes to product info [alt text http://img124.imageshack.us/img124/1139/revisionslz5.gif](http://img124.imageshack.us/img124/1139/revisionslz5.gif) I try to query the database for all products, with their most recent revision... ``` select * from `products` as `p` left join `revisions` as `r` on `r`.`product_id` = `p`.`product_id` group by `p`.`product_id` order by `r`.`modified` desc ``` but I always just get the first revision. I need to do this in **one** select (ie no sub queries). I can manage it in mssql, is this even possible in mysql?
Here's how I'd do it: ``` SELECT p.*, r.* FROM products AS p JOIN revisions AS r USING (product_id) LEFT OUTER JOIN revisions AS r2 ON (r.product_id = r2.product_id AND r.modified < r2.modified) WHERE r2.revision_id IS NULL; ``` In other words: find the revision for which no other revision exists with the same product\_id and a greater modified value.
Begin and end dates on your history table would make this possible.(leaving the most recent end date null and stamping end dates on the previous record as you insert a new one) Otherwise you will have to use a sub-query.
Problem joining on the highest value in mysql table
[ "", "mysql", "sql", "" ]
I'm running PHP, Apache, and Windows. I do not have a domain setup, so I would like my website's forms-based authentication to use the local user accounts database built in to Windows (I think it's called SAM). I know that if Active Directory is setup, you can use the PHP LDAP module to connect and authenticate in your script, but without AD there is no LDAP. What is the equivalent for standalone machines?
I haven't found a simple solution either. There are examples using CreateObject and the WinNT ADSI provider. But eventually they all bump into [User authentication issues with the Active Directory Service Interfaces WinNT provider](http://support.microsoft.com/kb/218497). I'm not 100% sure but I *guess* the WSH/network connect approach has the same problem. According to [How to validate user credentials on Microsoft operating systems](http://support.microsoft.com/kb/180548/) you should use LogonUser or SSPI. It also says > ``` > LogonUser Win32 API does not require TCB privilege in Microsoft Windows Server 2003, however, for downlevel compatibility, this is still the best approach. > ``` On Windows XP, it is no longer required that a process have the SE\_TCB\_NAME privilege in order to call LogonUser. Therefore, the simplest method to validate a user's credentials on Windows XP, is to call the LogonUser API.Therefore, if I were certain Win9x/2000 support isn't needed, I would write an extension that exposes LogonUser to php. You might also be interested in [User Authentication from NT Accounts](http://www.codewalkers.com/c/a/User-Management-Code/User-Authentication-from-NT-Accounts/). It uses the w32api extension, and needs a support dll ...I'd rather write that small LogonUser-extension ;-) If that's not feasible I'd probably look into the fastcgi module for IIS and how stable it is and let the IIS handle the authentication. edit: I've also tried to utilize [System.Security.Principal.WindowsIdentity](http://msdn.microsoft.com/en-us/library/system.security.principal.windowsidentity.aspx) and php's [com/.net extension](http://uk.php.net/manual/en/book.com.php). But the dotnet constructor doesn't seem to allow passing parameters to the objects constructor and my "experiment" to get the assembly (and with it CreateInstance()) from GetType() has failed with an "unknown zval" error.
Good Question! I've given this some thought... and I can't think of a good solution. What I can think of is a horrible horrible hack that just might work. After seeing that no one has posted an answer to this question for nearly a day, I figured a bad, but working answer would be ok. The SAM file is off limits while the system is running. There are some DLL Injection tricks which you may be able to get working but in the end you'll just end up with password hashes and you'd have to hash the user provided passwords to match against them anyway. What you really want is something that tries to authenticate the user against the SAM file. I think you can do this by doing something like the following. 1. Create a File Share on the server and make it so that only accounts that you want to be able to log in as are granted access to it. 2. In PHP use the system command to invoke a wsh script that: mounts the share using the username and password that the website user provides. records if it works, and then unmounts the drive if it does. 3. Collect the result somehow. The result can be returned to php either on the stdout of the script, or hopefully using the return code for the script. I know it's not pretty, but it should work. I feel dirty :| Edit: reason for invoking the external wsh script is that PHP doesn't allow you to use UNC paths (as far as I can remember).
PHP Forms-Based Authentication on Windows using Local User Accounts
[ "", "php", "windows", "apache", "authentication", "sam", "" ]
I am trying to use Difflib.SequenceMatcher to compute the similarities between two files. These two files are almost identical except that one contains some extra whitespaces, empty lines and other doesn't. I am trying to use ``` s=difflib.SequenceMatcher(isjunk,text1,text2) ratio =s.ratio() ``` for this purpose. So, the question is how to write the lambda expression for this isjunk method so the SequenceMatcher method will discount all the whitespaces, empty lines etc. I tried to use the parameter lambda x: x==" ", but the result isn't as great. For two closely similar text, the ratio is very low. This is highly counter intuitive. For testing purpose, here are the two strings that you can use on testing: > What Motivates jwovu to do your Job > Well? OK, this is an entry trying to > win $100 worth of software development > books despite the fact that I don‘t > read > > programming books. In order to win the > prize you have to write an entry and > what motivatesfggmum to do your job > well. Hence this post. First > motivation > > money. I know, this doesn‘t sound like > a great inspiration to many, and > saying that money is one of the > motivation factors might just blow my > chances away. > > As if money is a taboo in programming > world. I know there are people who > can‘t be motivated by money. Mme, on > the other hand, am living in a real > world, > > with house mortgage to pay, myself to > feed and bills to cover. So I can‘t > really exclude money from my > consideration. If I can get a large > sum of money for > > doing a good job, then definitely > boost my morale. I won‘t care whether > I am using an old workstation, or > forced to share rooms or cubicle with > other > > people, or have to put up with an > annoying boss, or whatever. The fact > that at the end of the day I will walk > off with a large pile of money itself > is enough > > for me to overcome all the obstacles, > put up with all the hard feelings and > hurt egos, tolerate a slow computer > and even endure And here's another string > What Motivates You to do your Job > Well? OK, this is an entry trying to > win $100 worth of software development > books, despite the fact that I don't > read programming books. In order to > win the prize you have to write an > entry and describes what motivates you > to do your job well. Hence this post. > > First motivation, money. I know, this > doesn't sound like a great inspiration > to many, and saying that money is one > of the motivation factors might just > blow my chances away. As if money is a > taboo in programming world. I know > there are people who can't be > motivated by money. Kudos to them. Me, > on the other hand, am living in a real > world, with house mortgage to pay, > myself to feed and bills to cover. So > I can't really exclude money from my > consideration. > > If I can get a large sum of money for > doing a good job, then thatwill > definitely boost my morale. I won't > care whether I am using an old > workstation, or forced to share rooms > or cubicle with other people, or have > to put up with an annoying boss, or > whatever. The fact that at the end of > the day I will walk off with a large > pile of money itself is enough for me > to overcome all the obstacles, put up > with all the hard feelings and hurt > egos, tolerate a slow computer and > even endure I ran the above command, and set the isjunk to lambda x:x==" ", the ratio is only 0.36.
If you match all whitespaces the similarity is better: ``` difflib.SequenceMatcher(lambda x: x in " \t\n", doc1, doc2).ratio() ``` However, difflib is not ideal to such a problem because these are two nearly identical documents, but typos and such produce differences for difflib where a human wouldn't see many. Try reading up on [tf-idf](http://en.wikipedia.org/wiki/Tf-idf), [Bayesian probability](http://en.wikipedia.org/wiki/Bayesian_probability), [Vector space Models](http://en.wikipedia.org/wiki/Vector_space_model) and [w-shingling](http://en.wikipedia.org/wiki/W-shingling) I have written a an [implementation of tf-idf](http://hg.codeflow.org/tfclassify) applying it to a vector space and using the dot product as a distance measure to classify documents.
Using your sample strings: ``` >>> s=difflib.SequenceMatcher(lambda x: x == '\n', s1, s2) >>> s.ratio() 0.94669848846459825 ``` Interestingly if ' ' is also included as junk: ``` >>> s=difflib.SequenceMatcher(lambda x: x in ' \n', s1, s2) >>> s.ratio() 0.7653142402545744 ``` Looks like the new lines are having a much greater affect than the spaces.
Difflib.SequenceMatcher isjunk optional parameter query: how to ignore whitespaces, tabs, empty lines?
[ "", "python", "lambda", "difflib", "" ]
I started using subversion for one of my projects and it would be absolutely amazing if I could just export the latest version from the repository on my production server by for example running a php or perl script. The production site is hosted with a shared hosting provider who doesn't allow shell access or for example the php [`exec()`](http://www.php.net/manual/en/function.exec.php) function. (I don't know much about perl; I only know that my hoster allows perl and custom cgi scripts). Is it possible to perform a SVN export in this environment?
As far as I know there is no SVN client fully written in PHP or Perl. SO without exec you're out of luck. Workarounds: * Depending on your own OS and what methods you have to access your web space you might be able to mount the web space in your local file system and just use your system's SVN client for checking out/updating. * Again depending on your access methods (I'm guessing ftp or sftp) you might update a local checkout and sync any changes up onto the web space.
SVN supports access over WebDAV (i.e. HTTPS). This means for simple read access you don't actually need an SVN client to access an SVN repository. You can even use a web browser, or in your case any PHP function that accepts a URL as its argument. SVN has to be set up on the server side to work with apache, for more info check out the [svn red book](http://svnbook.red-bean.com/en/1.5/svn.serverconfig.html)
Is it possible to do a SVN export without shell access?
[ "", "php", "svn", "export", "" ]
I have an Open Source app and I currently only post the binary for the Windows build. At this point Linux users have to get the source and compile it. Is there a standard way for posting a Linux binary? My app is in c / c++ and compiled with gcc, the only external Linux code I use is X Windows and CUPS.
The most common way would be to package it in a [.rpm file](http://en.wikipedia.org/wiki/RPM_Package_Manager) for [RedHat](http://www.redhat.com/)-based distros like [Fedora](http://fedoraproject.org/), or a [.deb file](http://en.wikipedia.org/wiki/Deb_(file_format)) for [Debian](http://www.debian.org/)-based distros like [Ubuntu](http://www.ubuntu.com/).
Find someone skilled with Debian and get their help to set up a build process to build .deb packages for Debian and Ubuntu.
How to package a Linux binary for my Open Source application?
[ "", "c++", "linux", "binary", "publish", "" ]
I have a bunch a values I would like to add together which are entered into a form. Right now, the form has 11 lines but it could get larger in the future. I can easily add all the values together with something like: ``` $total = $value1 + $value2 + ... + $value11; ``` All the values I want to add together are coming from an `HTML` form. I want to avoid javascript. But, I want to avoid having to manually do it, especially if it grows much larger. This is my attempt at adding all the values together using a loop but it returns an "undefined variable" error (it is just some test code to try out the idea): ``` <?php $tempTotal = 0; $pBalance1 = 5; $pBalance2 = 5; $pBalance3 = 5; for ($i = 1 ; $i <= 3 ; $i++){ $tempTotal = $tempTotal + $pBalance.$i; } echo $tempTotal; ?> ``` Is what I want to do possible in PHP?
``` for ($i = 1 ; $i <= 3 ; $i++){ $varName = "pBalance".$i; $tempTotal += $$varName; } ``` This will do what you want. However you might indeed consider using an array for this kind of thing.
I would use @unexist's solution.. give the input fields names like: ``` <input name="myInput[]" /> <input name="myInput[]" /> <input name="myInput[]" /> ... ``` Then in your PHP get the sum like this: ``` $total = array_sum($_REQUEST['myInput']); ``` Because of the '[]' at the end of each input name, PHP will make $\_REQUEST['myInput'] automatically be an array. A handy feature of PHP!
Can I use a generated variable name in PHP?
[ "", "php", "" ]
Is it possible, in Java, to make a `JPanel` skip drawing its background thus being transparent except for the components on it?
`setOpaque(false)` It'll pass off painting the background to its parent, which may draw its own background. You can do a screen capture and then use that to paint the background of the panel.
This article seems to have some handy info on how to create shaped and transparent windows in Java: <https://docs.oracle.com/javase/tutorial/uiswing/misc/trans_shaped_windows.html>
Make a JPanel not draw its background (Transparent)
[ "", "java", "user-interface", "" ]
How to do paging in Pervasive SQL (version 9.1)? I need to do something similar like: ``` //MySQL SELECT foo FROM table LIMIT 10, 10 ``` But I can't find a way to define offset.
I ended up doing the paging in code. I just skip the first records in loop. I thought I made up an easy way for doing the paging, but it seems that pervasive sql doesn't allow order clauses in subqueries. But this should work on other DBs (I tested it on firebird) ``` select * from (select top [rows] * from (select top [rows * pagenumber] * from mytable order by id) order by id desc) order by id ```
Tested query in PSQL: ``` select top n * from tablename where id not in( select top k id from tablename ) ``` for all n = no.of records u need to fetch at a time. and k = multiples of n(eg. n=5; k=0,5,10,15,....)
Paging in Pervasive SQL
[ "", "sql", "pervasive", "" ]
How come this doesn't work (operating on an empty select list `<select id="requestTypes"></select>` ``` $(function() { $.getJSON("/RequestX/GetRequestTypes/", showRequestTypes); } ); function showRequestTypes(data, textStatus) { $.each(data, function() { var option = new Option(this.RequestTypeName, this.RequestTypeID); // Use Jquery to get select list element var dropdownList = $("#requestTypes"); if ($.browser.msie) { dropdownList.add(option); } else { dropdownList.add(option, null); } } ); } ``` But this does: * Replace: `var dropdownList = $("#requestTypes");` * With plain old javascript: `var dropdownList = document.getElementById("requestTypes");`
`$("#requestTypes")` returns a jQuery object that contains all the selected elements. You are attempting to call the `add()` method of an individual element, but instead you are calling the `add()` method of the jQuery object, which does something very different. In order to access the DOM element itself, you need to treat the jQuery object as an array and get the first item out of it, by using `$("#requestTypes")[0]`.
By default, jQuery selectors return the jQuery object. Add this to get the DOM element returned: ``` var dropdownList = $("#requestTypes")[0]; ```
jQuery create select list options from JSON, not happening as advertised?
[ "", "javascript", "jquery", "drop-down-menu", "html-select", "" ]
**C#6 Update** In [C#6 `?.` is now a language feature](https://msdn.microsoft.com/en-us/magazine/dn802602.aspx): ``` // C#1-5 propertyValue1 = myObject != null ? myObject.StringProperty : null; // C#6 propertyValue1 = myObject?.StringProperty; ``` The question below still applies to older versions, but if developing a new application using the new `?.` operator is far better practice. **Original Question:** I regularly want to access properties on possibly null objects: ``` string propertyValue1 = null; if( myObject1 != null ) propertyValue1 = myObject1.StringProperty; int propertyValue2 = 0; if( myObject2 != null ) propertyValue2 = myObject2.IntProperty; ``` And so on... I use this so often that I have a snippet for it. You can shorten this to some extent with an inline if: ``` propertyValue1 = myObject != null ? myObject.StringProperty : null; ``` However this is a little clunky, especially if setting lots of properties or if more than one level can be null, for instance: ``` propertyValue1 = myObject != null ? (myObject.ObjectProp != null ? myObject.ObjectProp.StringProperty) : null : null; ``` What I really want is `??` style syntax, which works great for directly null types: ``` int? i = SomeFunctionWhichMightReturnNull(); propertyValue2 = i ?? 0; ``` So I came up with the following: ``` public static TResult IfNotNull<T, TResult>( this T input, Func<T, TResult> action, TResult valueIfNull ) where T : class { if ( input != null ) return action( input ); else return valueIfNull; } //lets us have a null default if the type is nullable public static TResult IfNotNull<T, TResult>( this T input, Func<T, TResult> action ) where T : class where TResult : class { return input.IfNotNull( action, null ); } ``` This lets me us this syntax: ``` propertyValue1 = myObject1.IfNotNull( x => x.StringProperty ); propertyValue2 = myObject2.IfNotNull( x => x.IntProperty, 0); //or one with multiple levels propertyValue1 = myObject.IfNotNull( o => o.ObjectProp.IfNotNull( p => p.StringProperty ) ); ``` This simplifies these calls, but I'm not sure about checking this sort of extension method in - it does make the code a little easier to read, but at the cost of extending object. This would appear on everything, although I could put it in a specifically referenced namespace. This example is a rather simple one, a slightly more complex one would be comparing two nullable object properties: ``` if( ( obj1 == null && obj2 == null ) || ( obj1 != null && obj2 != null && obj1.Property == obj2.Property ) ) ... //becomes if( obj1.NullCompare( obj2, (x,y) => x.Property == y.Property ) ... ``` What are the pitfalls of using extensions in this way? Are other coders likely to be confused? Is this just abuse of extensions? --- I guess what I really want here is a compiler/language extension: ``` propertyValue1 = myObject != null ? myObject.StringProperty : null; //becomes propertyValue1 = myObject?StringProperty; ``` This would make the complex case far easier: ``` propertyValue1 = myObject != null ? (myObject.ObjectProp != null ? myObject.ObjectProp.StringProperty) : null //becomes propertyValue1 = myObject?ObjectProp?StringProperty; ``` This would only work for value types, but you could return nullable equivalents: ``` int? propertyValue2 = myObject?ObjectProp?IntProperty; //or int propertyValue3 = myObject?ObjectProp?IntProperty ?? 0; ```
We independently came up with the exact same extension method name and implementation: [Null-propagating extension method](http://code.logos.com/blog/2008/01/nullpropagating_extension_meth.html). So we don't think it's confusing or an abuse of extension methods. I would write your "multiple levels" example with chaining as follows: ``` propertyValue1 = myObject.IfNotNull(o => o.ObjectProp).IfNotNull(p => p.StringProperty); ``` There's a [now-closed bug on Microsoft Connect](https://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=192177) that proposed "?." as a new C# operator that would perform this null propagation. Mads Torgersen (from the C# language team) briefly explained why they won't implement it.
Here's another solution, for chained members, including extension methods: ``` public static U PropagateNulls<T,U> ( this T obj ,Expression<Func<T,U>> expr) { if (obj==null) return default(U); //uses a stack to reverse Member1(Member2(obj)) to obj.Member1.Member2 var members = new Stack<MemberInfo>(); bool searchingForMembers = true; Expression currentExpression = expr.Body; while (searchingForMembers) switch (currentExpression.NodeType) { case ExpressionType.Parameter: searchingForMembers = false; break; case ExpressionType.MemberAccess: { var ma= (MemberExpression) currentExpression; members.Push(ma.Member); currentExpression = ma.Expression; } break; case ExpressionType.Call: { var mc = (MethodCallExpression) currentExpression; members.Push(mc.Method); //only supports 1-arg static methods and 0-arg instance methods if ( (mc.Method.IsStatic && mc.Arguments.Count == 1) || (mc.Arguments.Count == 0)) { currentExpression = mc.Method.IsStatic ? mc.Arguments[0] : mc.Object; break; } throw new NotSupportedException(mc.Method+" is not supported"); } default: throw new NotSupportedException (currentExpression.GetType()+" not supported"); } object currValue = obj; while(members.Count > 0) { var m = members.Pop(); switch(m.MemberType) { case MemberTypes.Field: currValue = ((FieldInfo) m).GetValue(currValue); break; case MemberTypes.Method: var method = (MethodBase) m; currValue = method.IsStatic ? method.Invoke(null,new[]{currValue}) : method.Invoke(currValue,null); break; case MemberTypes.Property: var method = ((PropertyInfo) m).GetGetMethod(true); currValue = method.Invoke(currValue,null); break; } if (currValue==null) return default(U); } return (U) currValue; } ``` Then you can do this where any can be null, or none: ``` foo.PropagateNulls(x => x.ExtensionMethod().Property.Field.Method()); ```
Possible pitfalls of using this (extension method based) shorthand
[ "", "c#", ".net", "extension-methods", "" ]
I would like to code a little program which visually illustrates the behavior of the `volatile` keyword. Ideally, it should be a program which performs concurrent access to a non volatile static field and which gets incorrect behavior because of that. Adding the volatile keyword in the same program should fix the problem. That something I didn't manage to achieve. Even trying several times, enabling optimization, etc., I always get a correct behavior without the 'volatile' keyword. Do you have any idea about this topic? Do you know how to simulate such a problem in a simple demo app? Does it depend on hardware?
I've achieved a working example! The main idea received from wiki, but with some changes for C#. The wiki article demonstrates this for static field of C++, it is looks like C# always carefully compile requests to static fields... and i make example with non static one: If you run this example in **Release** mode and **without debugger** (i.e. using Ctrl+F5) then the line `while (test.foo != 255)` will be optimized to 'while(true)' and this program never returns. But after adding `volatile` keyword, you always get 'OK'. ``` class Test { /*volatile*/ int foo; static void Main() { var test = new Test(); new Thread(delegate() { Thread.Sleep(500); test.foo = 255; }).Start(); while (test.foo != 255) ; Console.WriteLine("OK"); } } ```
Yes, it's hardware dependent (you are unlikely to see the problem without multiple processors), but it's also implementation dependent. The memory model specifications in the CLR spec permit things which the Microsoft implementation of the CLR do not necessarily do.
Illustrating usage of the volatile keyword in C#
[ "", "c#", ".net", "volatile", "" ]
I have a *JComboBox* and would like to have a separator in the list of elements. How do I do this in Java? A sample scenario where this would come in handy is when making a combobox for font-family-selection; similar to the font-family-selection-control in Word and Excel. In this case I would like to show the most-used-fonts at the top, then a separator and finally all font-families below the separator in alphabetical order. Can anyone help me with how to do this or is this not possible in Java?
There is a pretty short tutorial with an example that shows how to use a custom ListCellRenderer on java2s <http://www.java2s.com/Code/Java/Swing-Components/BlockComboBoxExample.htm> Basically it involves inserting a known placeholder in your list model and when you detect the placeholder in the ListCellRenderer you return an instance of 'new JSeparator(JSeparator.HORIZONTAL)'
By the time I wrote and tested the code below, you probably got lot of better answers... I don't mind as I enjoyed the experiment/learning (still a bit green on the Swing front). [EDIT] Three years later, I am a bit less green, and I took in account the valid remarks of bobndrew. I have no problem with the key navigation that just works (perhaps it was a JVM version issue?). I improved the renderer to show highlight, though. And I use a better demo code. The accepted answer is probably better (more standard), mine is probably more flexible if you want a custom separator... The base idea is to use a renderer for the items of the combo box. For most items, it is a simple JLabel with the text of the item. For the last recent/most used item, I decorate the JLabel with a custom border drawing a line on its bottom. ``` import java.awt.*; import javax.swing.*; @SuppressWarnings("serial") public class TwoPartsComboBox extends JComboBox { private int m_lastFirstPartIndex; public TwoPartsComboBox(String[] itemsFirstPart, String[] itemsSecondPart) { super(itemsFirstPart); m_lastFirstPartIndex = itemsFirstPart.length - 1; for (int i = 0; i < itemsSecondPart.length; i++) { insertItemAt(itemsSecondPart[i], i); } setRenderer(new JLRenderer()); } protected class JLRenderer extends JLabel implements ListCellRenderer { private JLabel m_lastFirstPart; public JLRenderer() { m_lastFirstPart = new JLabel(); m_lastFirstPart.setBorder(new BottomLineBorder()); // m_lastFirstPart.setBorder(new BottomLineBorder(10, Color.BLUE)); } @Override public Component getListCellRendererComponent( JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { if (value == null) { value = "Select an option"; } JLabel label = this; if (index == m_lastFirstPartIndex) { label = m_lastFirstPart; } label.setText(value.toString()); label.setBackground(isSelected ? list.getSelectionBackground() : list.getBackground()); label.setForeground(isSelected ? list.getSelectionForeground() : list.getForeground()); label.setOpaque(true); return label; } } } ``` Separator class, can be thick, with custom color, etc. ``` import java.awt.*; import javax.swing.border.AbstractBorder; /** * Draws a line at the bottom only. * Useful for making a separator in combo box, for example. */ @SuppressWarnings("serial") class BottomLineBorder extends AbstractBorder { private int m_thickness; private Color m_color; BottomLineBorder() { this(1, Color.BLACK); } BottomLineBorder(Color color) { this(1, color); } BottomLineBorder(int thickness, Color color) { m_thickness = thickness; m_color = color; } @Override public void paintBorder(Component c, Graphics g, int x, int y, int width, int height) { Graphics copy = g.create(); if (copy != null) { try { copy.translate(x, y); copy.setColor(m_color); copy.fillRect(0, height - m_thickness, width - 1, height - 1); } finally { copy.dispose(); } } } @Override public boolean isBorderOpaque() { return true; } @Override public Insets getBorderInsets(Component c) { return new Insets(0, 0, m_thickness, 0); } @Override public Insets getBorderInsets(Component c, Insets i) { i.left = i.top = i.right = 0; i.bottom = m_thickness; return i; } } ``` Test class: ``` import java.awt.*; import java.awt.event.*; import javax.swing.*; @SuppressWarnings("serial") public class TwoPartsComboBoxDemo extends JFrame { private TwoPartsComboBox m_combo; public TwoPartsComboBoxDemo() { Container cont = getContentPane(); cont.setLayout(new FlowLayout()); cont.add(new JLabel("Data: ")) ; String[] itemsRecent = new String[] { "ichi", "ni", "san" }; String[] itemsOther = new String[] { "one", "two", "three" }; m_combo = new TwoPartsComboBox(itemsRecent, itemsOther); m_combo.setSelectedIndex(-1); cont.add(m_combo); m_combo.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ae) { String si = (String) m_combo.getSelectedItem(); System.out.println(si == null ? "No item selected" : si.toString()); } }); // Reference, to check we have similar behavior to standard combo JComboBox combo = new JComboBox(itemsRecent); cont.add(combo); } /** * Start the demo. * * @param args the command line arguments */ public static void main(String[] args) { // turn bold fonts off in metal UIManager.put("swing.boldMetal", Boolean.FALSE); SwingUtilities.invokeLater(new Runnable() { public void run() { JFrame demoFrame = new TwoPartsComboBoxDemo(); demoFrame.setTitle("Test GUI"); demoFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); demoFrame.setSize(400, 100); demoFrame.setVisible(true); } }); } } ```
How do I add a separator to a JComboBox in Java?
[ "", "java", "swing", "jcombobox", "jseparator", "" ]
It is much more convenient and cleaner to use a single statement like ``` import java.awt.*; ``` than to import a bunch of individual classes ``` import java.awt.Panel; import java.awt.Graphics; import java.awt.Canvas; ... ``` What is wrong with using a wildcard in the `import` statement?
The only problem with it is that it clutters your local namespace. For example, let's say that you're writing a Swing app, and so need `java.awt.Event`, and are also interfacing with the company's calendaring system, which has `com.mycompany.calendar.Event`. If you import both using the wildcard method, one of these three things happens: 1. You have an outright naming conflict between `java.awt.Event` and `com.mycompany.calendar.Event`, and so you can't even compile. 2. You actually manage only to import one (only one of your two imports does `.*`), but it's the wrong one, and you struggle to figure out why your code is claiming the type is wrong. 3. When you compile your code, there is no `com.mycompany.calendar.Event`, but when they later add one, your previously valid code suddenly stops compiling. The advantage of explicitly listing all imports is that I can tell at a glance which class you meant to use, which simply makes reading the code much easier. If you're just doing a quick one-off thing, there's nothing explicitly *wrong*, but future maintainers will thank you for your clarity otherwise.
Here's a vote **for** star imports. An import statement is intended to import a *package*, not a class. It is much cleaner to import entire packages; the issues identified here (e.g. `java.sql.Date` vs `java.util.Date`) are easily remedied by other means, not **really** addressed by specific imports and certainly do not justify insanely pedantic imports on all classes. There is nothing more disconcerting than opening a source file and having to page through 100 import statements. Doing specific imports makes refactoring more difficult; if you remove/rename a class, you need to remove **all** of its specific imports. If you switch an implementation to a different class in the same package, you have to go fix the imports. While these extra steps can be automated, they are really productivity hits for no real gain. If Eclipse didn't do specific class imports by default, everyone would still be doing star imports. I'm sorry, but there's really no rational justification for doing specific imports. Here's how to deal with class conflicts: ``` import java.sql.*; import java.util.*; import java.sql.Date; ```
Why is using a wild card with a Java import statement bad?
[ "", "java", "import", "wildcard", "" ]
In new C++ code, I tend to use the C++ iostream library instead of the C stdio library. I've noticed some programmers seem to stick to stdio, insisting that it's more portable. Is this really the case? What is better to use?
To answer the original question: Anything that can be done using stdio can be done using the iostream library. ``` Disadvantages of iostreams: verbose Advantages of iostreams: easy to extend for new non POD types. ``` The step forward the C++ made over C was type safety. * iostreams was designed to be explicitly type safe. Thus assignment to an object explicitly checked the type (at compiler time) of the object being assigned too (generating an compile time error if required). Thus prevent run-time memory over-runs or writing a float value to a char object etc. * scanf()/printf() and family on the other hand rely on the programmer getting the format string correct and there was no type checking (I believe gcc has an extension that helps). As a result it was the source of many bugs (as programmers are less perfect in their analysis than compilers [not going to say compilers are perfect just better than humans]). Just to clarify comments from Colin Jensen. * The iostream libraries have been stable since the release of the last standard (I forget the actual year but about 10 years ago). To clarify comments by Mikael Jansson. * The other languages that he mentions that use the format style have explicit safeguards to prevent the dangerous side effects of the C stdio library that can (in C but not the mentioned languages) cause a run-time crash. **N.B.** I agree that the iostream library is a bit on the verbose side. But I am willing to put up with the verboseness to ensure runtime safety. But we can mitigate the verbosity by using [Boost Format Library](http://www.boost.org/doc/libs/1_36_0/libs/format/doc/format.html). ``` #include <iostream> #include <iomanip> #include <boost/format.hpp> struct X { // this structure reverse engineered from // example provided by 'Mikael Jansson' in order to make this a running example char* name; double mean; int sample_count; }; int main() { X stats[] = {{"Plop",5.6,2}}; // nonsense output, just to exemplify // stdio version fprintf(stderr, "at %p/%s: mean value %.3f of %4d samples\n", stats, stats->name, stats->mean, stats->sample_count); // iostream std::cerr << "at " << (void*)stats << "/" << stats->name << ": mean value " << std::fixed << std::setprecision(3) << stats->mean << " of " << std::setw(4) << std::setfill(' ') << stats->sample_count << " samples\n"; // iostream with boost::format std::cerr << boost::format("at %p/%s: mean value %.3f of %4d samples\n") % stats % stats->name % stats->mean % stats->sample_count; } ```
It's just too verbose. Ponder the iostream construct for doing the following (similarly for scanf): ``` // nonsense output, just to examplify fprintf(stderr, "at %p/%s: mean value %.3f of %4d samples\n", stats, stats->name, stats->mean, stats->sample_count); ``` That would requires something like: ``` std::cerr << "at " << static_cast<void*>(stats) << "/" << stats->name << ": mean value " << std::precision(3) << stats->mean << " of " << std::width(4) << std::fill(' ') << stats->sample_count << " samples " << std::endl; ``` String formatting is a case where object-orientedness can, and should be, sidestepped in favour of a formatting DSL embedded in strings. Consider Lisp's `format`, Python's printf-style formatting, or PHP, Bash, Perl, Ruby and their string intrapolation. `iostream` for that use case is misguided, at best.
Which C I/O library should be used in C++ code?
[ "", "c++", "iostream", "stdio", "" ]
The Python list comprehension syntax makes it easy to filter values within a comprehension. For example: ``` result = [x**2 for x in mylist if type(x) is int] ``` Will return a list of the squares of integers in mylist. However, what if the test involves some (costly) computation and you want to filter on the result? One option is: ``` result = [expensive(x) for x in mylist if expensive(x)] ``` This will result in a list of non-"false" expensive(x) values, however expensive() is called twice for each x. Is there a comprehension syntax that allows you to do this test while only calling expensive once per x?
If the calculations are already nicely bundled into functions, how about using `filter` and `map`? ``` result = filter (None, map (expensive, mylist)) ``` You can use `itertools.imap` if the list is very large.
Came up with my own answer after a minute of thought. It can be done with nested comprehensions: ``` result = [y for y in (expensive(x) for x in mylist) if y] ``` I guess that works, though I find nested comprehensions are only marginally readable
How do I efficiently filter computed values within a Python list comprehension?
[ "", "python", "list-comprehension", "" ]
[PMD](https://pmd.github.io/) would report a violation for: ``` ArrayList<Object> list = new ArrayList<Object>(); ``` The violation was "Avoid using implementation types like 'ArrayList'; use the interface instead". The following line would correct the violation: ``` List<Object> list = new ArrayList<Object>(); ``` Why should the latter with `List` be used instead of `ArrayList`?
Using interfaces over concrete types is the key for good encapsulation and for loose coupling your code. It's even a good idea to follow this practice when writing your own APIs. If you do, you'll find later that it's easier to add unit tests to your code (using Mocking techniques), and to change the underlying implementation if needed in the future. Here's a [good article](https://web.archive.org/web/20130816024910/http://www.javaworld.com/javaworld/jw-08-2003/jw-0801-toolbox.html) on the subject. Hope it helps!
This is preferred because you decouple your code from the implementation of the list. Using the interface lets you easily change the implementation, ArrayList in this case, to another list implementation without changing any of the rest of the code as long as it only uses methods defined in List.
Why should the interface for a Java class be preferred?
[ "", "java", "collections", "interface", "" ]
Given this data: ``` CREATE TABLE tmpTable( fldField varchar(10) null); INSERT INTO tmpTable SELECT 'XXX' UNION ALL SELECT 'XXX' UNION ALL SELECT 'ZZZ' UNION ALL SELECT 'ZZZ' UNION ALL SELECT 'YYY' SELECT CASE WHEN fldField like 'YYY' THEN 'OTH' ELSE 'XXX' END AS newField FROM tmpTable ``` The expected resultset is: XXX XXX XXX XXX OTH What situation would casue SQL server 2000 to NOT find 'YYY'? And return the following as the resultset: XXX XXX XXX XXX XXX The problem is with the like 'YYY', I have found other ways to write this to get it to work, but I want to know why this exact method doesn't work. Another difficulty is that it works in most of my SQL Server 2000 environments. I need to find out what is different between them to cause this. Thanks for your help.
Check your service pack. After upgrading my SQL 2000 box to SP4 I now get the correct values for your situation. I'm still getting the swapped data that I reported in my earlier post though :( If you do `SELECT @@version` you should get 8.00.2039. Any version number less than that and you should install SP4.
I ran the code on a SQL 2000 box and got identical results. Not only that, but when I ran some additional code to test I got some VERY bizarre results: ``` CREATE TABLE dbo.TestLike ( my_field varchar(10) null); GO CREATE CLUSTERED INDEX IDX_TestLike ON dbo.TestLike (my_field) GO INSERT INTO dbo.TestLike (my_field) VALUES ('XXX') INSERT INTO dbo.TestLike (my_field) VALUES ('XXX') INSERT INTO dbo.TestLike (my_field) VALUES ('ZZZ') INSERT INTO dbo.TestLike (my_field) VALUES ('ZZZ') INSERT INTO dbo.TestLike (my_field) VALUES ('YYY') GO SELECT my_field, case my_field when 'YYY' THEN 'Y' ELSE 'N' END AS C2, case when my_field like 'YYY' THEN 'Y' ELSE 'N' END AS C3, my_field FROM dbo.TestLike GO ``` My results: ``` my_field C2 C3 my_field ---------- ---- ---- ---------- N XXX N XXX N XXX N XXX Y YYY N YYY N ZZZ N ZZZ N ZZZ N ZZZ ``` Notice how my\_field has two different values in the same row? I've asked some others at the office here to give it a quick test. Looks like a bug to me.
Like in CASE statement not evaluating as expected
[ "", "sql", "sql-server", "" ]
I have a server that sends data via a socket, the data is a wav 'file'. I can easily write the data to disk and then play it in WMP, but I have no idea how I can play it as I read it from the socket. Is it possible? Bonus question: how would I do it if the stream was in mp3 or other format? This is for windows in native C++.
Because you've said WMP, I'm assuming the question applies to trying to play a wav file on a windows machine. If not, this answer isn't relevant. What you want to do isn't trivial. There is a good article [here](http://www.codeproject.com/KB/audio-video/wavefiles.aspx) on code project that describes the windows audio model. It describes how to set up the audio device and how to stream data into the device for playback. You "simply" need to supply data coming in from your socket as data for the playback buffers. But that's where all of the tricky work is. You have to be sure that * You have enough data to begin a playback * Handle the case when your socket is starved for data and you have nothing to send to the playback buffer * You are able to read data off of the socket with enough speed to keep the playback buffers full It's an interesting exercise. But tricky.
Mark is right about this being a tricky problem. It may be less tricky if you use DirectSound instead of waveOut. [Here's an article](http://www.gamedev.net/reference/articles/article710.asp) on streaming wave files from disk: streaming from the network is essentially the same process. Make sure you collect enough data from the network before you start - you'll want more than the 2 buffers the article mentions. Even less tricky would be [FMOD](http://www.fmod.org/). From the [FAQ](http://www.fmod.org/fmodfeatures.html): **Enhanced Internet features** * Internet audio streaming. Custom internet streaming code is included, which allows for seamless SHOUTcast, Icecast and http streaming support. * Download capability. A side effect of FMOD’s modular file system which supports network files, even static samples can be loaded off the internet. **File format support**: FMOD currently supports a wide range of audio file formats. *partial list*: * MP3 - (MPEG I/II Layer 3, including VBR support) * OGG - (Ogg Vorbis format) * WAV - (Microsoft Wave files, inlcluding compressed wavs. PCM, MP3 and IMA ADPCM compressed wav
streaming wav files
[ "", "c++", "stream", "wav", "" ]
**Update**: Looks like the query does not throw any timeout. The connection is timing out. This is a sample code for executing a query. Sometimes, while executing time consuming queries, it throws a timeout exception. I **cannot** use any of these techniques: 1) Increase timeout. 2) Run it asynchronously with a callback. This needs to run in a synchronous manner. please suggest any other techinques to keep the connection alive while executing a time consuming query? ``` private static void CreateCommand(string queryString, string connectionString) { using (SqlConnection connection = new SqlConnection( connectionString)) { SqlCommand command = new SqlCommand(queryString, connection); command.Connection.Open(); command.ExecuteNonQuery(); } } ```
Since you are using ExecuteNonQuery which does not return any rows, you can try this polling based approach. It executes the query in an asyc manner (without callback) but the application will wait (inside a while loop) until the query is complete. From [MSDN](http://msdn.microsoft.com/en-us/library/ca56w9se(VS.80).aspx). This should solve the timeout problem. Please try it out. But, I agree with others that you should think more about optimizing the query to perform under 30 seconds. ``` IAsyncResult result = command.BeginExecuteNonQuery(); int count = 0; while (!result.IsCompleted) { Console.WriteLine("Waiting ({0})", count++); System.Threading.Thread.Sleep(1000); } Console.WriteLine("Command complete. Affected {0} rows.", command.EndExecuteNonQuery(result)); ```
You should first check your query to see if it's optimized and it isn't somehow running on missing indexes. **30 seconds is allot for most queries**, even on large databases if they are properly tuned. If you have solid proof using the query plan that the query can't be executed any faster than that, then you should increase the timeout, there's no other way to keep the connection, that's the purpose of the timeout to terminate the connection if the query doesn't complete in that time frame.
Connection Timeout exception for a query using ADO.Net
[ "", "c#", ".net", "ado.net", "timeout", "" ]
I have to work on an old 1.3 JVM and I'm asked to create a secure connection to another server. Unfortunately the HttpsURLConnection only appears sinc JVM 1.4. Is there another way to create a secure connection? Is there a library that I could you to add this fonctionnality?
You need to install the Java Secure Socket Extension (JSSE), which used to be required because Sun wouldn't ship it with the JDK because of comedy export restrictions. I had a look on Sun's web site, but the JDK 1.3 instructions are preving elusive. Bear in mind that JDK 1.3 is now end-of-lifed by Sun, so they may not have any information any more. <http://hc.apache.org/httpclient-3.x/sslguide.html>
Check out the [BouncyCastle](http://www.bouncycastle.org/java.html) implementation. It works all the way down to Java 1.1 and J2ME.
Is there a way to establish a HTTPS Connection with Java 1.3?
[ "", "java", "https", "" ]
I have a `Dictionary<string, someobject>`. EDIT: It was pointed out to me, that my example was bad. My whole intention was not to update the references in a loop but to update different values based on differnt threads need to update/get the data. I changed the loop to a method. I need to update items in my dictionary - one key at a time and i was wondering if there are any problems in using the lock on the .key value of my Dictionary object? ``` private static Dictionary<string, MatrixElement> matrixElements = new Dictionary<string, MatrixElement>(); //Pseudo-code public static void UpdateValue(string key) { KeyValuePair<string, MatrixElement> keyValuePair = matrixElements[key]; lock (keyValuePair.Key) { keyValuePair.Value = SomeMeanMethod(); } } ``` Would that hold up in court or fail? I just want each value in the dictionary to be locked independantly so locking (and updating) one value does not lock the others. Also i'm aware the locking will be holding for a long time - but the data will be invalid untill updated fully.
Locking on an object that is accessible outside of the code locking it is a big risk. If any other code (anywhere) ever locks that object you could be in for some deadlocks that are hard to debug. Also note that you lock the *object*, not the reference, so if I gave you a dictionary, I may still hold references to the keys and lock on them - causing us to lock on the same object. *If* you completely encapsulate the dictionary, and generate the keys yourself (they aren't ever passed in, then you may be safe. However, try to stick to one rule - limit the visibility of the objects you lock on to the locking code itself whenever possible. That's why you see this: ``` public class Something { private readonly object lockObj = new object(); public SomethingReentrant() { lock(lockObj) // Line A { // ... } } } ``` rather than seeing line A above replaced by ``` lock(this) ``` That way, a separate object is locked on, and the visibility is limited. **Edit** [Jon Skeet](https://stackoverflow.com/users/22656/jon-skeet) correctly observed that lockObj above should be readonly.
No, this would not work. The reason is [string interning](http://en.wikipedia.org/wiki/String_intern_pool). This means that: ``` string a = "Something"; string b = "Something"; ``` are both the same object! Therefore, you should never lock on strings because if some other part of the program (e.g. another instance of this same object) also wants to lock on the same string, you could accidentally create lock contention where there is no need for it; possibly even a deadlock. Feel free to do this with non-strings, though. For best clarity, I make it a personal habit to always create a separate lock object: ``` class Something { bool threadSafeBool = true; object threadSafeBoolLock = new object(); // Always lock this to use threadSafeBool } ``` I recommend you do the same. Create a Dictionary with the lock objects for every matrix cell. Then, lock these objects when needed. PS. Changing the collection you are iterating over is not considered very nice. It will even throw an exception with most collection types. Try to refactor this - e.g. iterate over a list of keys, if it will always be constant, not the pairs.
Using lock on the key of a Dictionary<string, object>
[ "", "c#", "dictionary", "locking", "" ]
I'm trying to create a new Excel file using jxl, but am having a hard time finding examples in their API documentation and online.
After messing around awhile longer I finally found something that worked and saw there still wasn't a solution posted here yet, so here's what I found: ``` try { String fileName = "file.xls"; WritableWorkbook workbook = Workbook.createWorkbook(new File(fileName)); workbook.createSheet("Sheet1", 0); workbook.createSheet("Sheet2", 1); workbook.createSheet("Sheet3", 2); workbook.write(); workbook.close(); } catch (WriteException e) { } ```
I know that it's a very old question. However, I think I can contribute with an example that also adds the cell values: ``` /** * * @author Almir Campos */ public class Write01 { public void test01() throws IOException, WriteException { // Initial settings File file = new File( "c:/tmp/genexcel.xls" ); WorkbookSettings wbs = new WorkbookSettings(); wbs.setLocale( new Locale( "en", "EN" ) ); // Creates the workbook WritableWorkbook wwb = Workbook.createWorkbook( file, wbs ); // Creates the sheet inside the workbook wwb.createSheet( "Report", 0 ); // Makes the sheet writable WritableSheet ws = wwb.getSheet( 0 ); // Creates a cell inside the sheet //CellView cv = new CellView(); Number n; Label l; Formula f; for ( int i = 0; i < 10; i++ ) { // A n = new Number( 0, i, i ); ws.addCell( n ); // B l = new Label( 1, i, "by" ); ws.addCell( l ); // C n = new Number( 2, i, i + 1 ); ws.addCell( n ); // D l = new Label( 3, i, "is" ); ws.addCell( l ); // E f = new Formula(4, i, "A" + (i+1) + "*C" + (i+1) ); ws.addCell( f ); } wwb.write(); wwb.close(); } } ```
How Do I Create a New Excel File Using JXL?
[ "", "java", "jxl", "" ]
This is along similar lines as these recent questions: [Best Java Obfuscation Application For Size Reduction](https://stackoverflow.com/questions/93290/best-java-obfuscation-application-for-size-reduction) [Creating non-reverse-engineerable Java programs](https://stackoverflow.com/questions/149937/creating-non-reverse-engineerable-java-programs) However, one ends up recommending yGuard and the other ProGuard but neither mention both. I wonder if we could get a comparison of each one and hear peoples experiences from both sides of the fence. Looking at this [comparison chart](http://proguard.sourceforge.net/alternatives.html) on the ProGuard website its clearly angled towards ProGuard. But what about real-world experience of each - which one produces smaller output? which one is harder to decompile from? what Java versions are supported by each? Personally I'm particularly interested from a J2ME point of view but please don't limit the discussion to that.
Proguard is a better product; especially if you take the time to go through the settings for J2ME. Specifically for J2ME there is a far better (commercial) product called [mBooster](http://www.innaworks.com/mBooster.html) I've been getting around 25% improvement in size on my application *after* its been through Proguard. This is mainly to do with the better Zip compression on the Jar file and comprehensive support for class merging and preverification.
Results for my project. * **Obfuscation** - both fine. * **Optimisation** - ProGuard produced 20% faster code (for the measured app bottleneck). * **Compactness** - ProGuard about 5% smaller. * **Configuration / Ant** - YGuard is much easier to configure. So, I'd advise ProGuard - but configuration and ant integration could definitely be improved.
Java obfuscation - ProGuard/yGuard/other?
[ "", "java", "java-me", "obfuscation", "proguard", "yguard", "" ]
I've got a XmlNodeList which I need to have it in a format that I can then re-use within a XSLT stylesheet by calling it from a C# extension method. Can anyone help? I have read that it might have something to do with using a XPathNavigator but I'm still a bit stuck.
I had to solve this issue myself a couple of years ago. The only way I managed it was to create an XML fragment containing the nodes in the node list and then passing in the children of the fragment. ``` XsltArgumentList arguments = new XsltArgumentList(); XmlNodeList nodelist; XmlDocument nodesFrament = new XmlDocument(); XmlNode root = nodesFragment.CreateElement("root"); foreach (XmlNode node in nodeList) { root.AppendChild(node); } nodesFragment.AppendChild(root); arguments.AddParam("argumentname", string.Empty, nodesFragment.CreateNavigator().SelectChildren(XPathNodeType.All)); ``` Then you need to make sure you have the corresponding argument in your XSLT, of course. Note that you probably don't need the additional XmlDocument. You could just call CreateNavigator() on the root XmlNode instance and use your existing XmlDocument for creating the element (I wrote this code some time ago and I've learned more since then - but I know the code above works, I haven't tried any alternatives).
The note at the end was the most useful, I had infact transformed the XmlNodeList into a XmlDocument already so could just use the Navigator on there and create it as a XPathNodeIterator. Thanks for you help!
How do I convert an XmlNodeList into a NodeSet to use within XSLT?
[ "", "c#", "xml", "xslt", "" ]
In VB.Net, I can declare a variable in a function as Static, like this: ``` Function EncodeForXml(ByVal data As String) As String Static badAmpersand As Regex = new Regex("&(?![a-zA-Z]{2,6};|#[0-9]{2,4};)") data = badAmpersand.Replace(data, "&amp;") ''// more processing return data End Function ``` Note that I need to use the keyword `Static`, rather than `Shared`, which is the normal way to express this in VB.Net. How can I do this in C#? I can't find its equivalent.
Ha! In posting the question, I found the answer! Rather than googling for C# I should have been looking for details on how VB.Net implements it, and typing up the question made that apparent to me. After applying that insight, I found this: <http://weblogs.asp.net/psteele/articles/7717.aspx> That article explains that it's not really supported by the CLR, and the VB compiler creates a static (shared) variable "under the hood" in the method's class. To do the same in C#, I have to create the variable myself. More than that, it uses the `Monitor` class to make sure the static member is thread-safe as well. Nice. As a side note: I'd expect to see this in C# sometime soon. The general tactic I've observed from MS is that it doesn't like VB.Net and C# to get too far apart feature-wise. If one language has a feature not supported by the other it tends to become a priority for the language team for the next version.
Personally I'm glad that C# *doesn't* have this. Logically, methods don't have state: types and instances do. C# makes that logical model clearer, IMO.
C# functions with static data
[ "", "c#", ".net", "vb.net", "" ]
Given a string with a module name, how do you import everything in the module as if you had called: ``` from module import * ``` i.e. given string S="module", how does one get the equivalent of the following: ``` __import__(S, fromlist="*") ``` This doesn't seem to perform as expected (as it doesn't import anything).
Please reconsider. The only thing worse than `import *` is *magic* `import *`. If you really want to: ``` m = __import__ (S) try: attrlist = m.__all__ except AttributeError: attrlist = dir (m) for attr in attrlist: globals()[attr] = getattr (m, attr) ```
Here's my solution for dynamic naming of local settings files for Django. Note the addition below of a check to not include attributes containing '\_\_' from the imported file. The `__name__` global was being overwritten with the module name of the local settings file, which caused `setup_environ()`, used in manage.py, to have problems. ``` try: import socket HOSTNAME = socket.gethostname().replace('.','_') # See http://docs.python.org/library/functions.html#__import__ m = __import__(name="settings_%s" % HOSTNAME, globals=globals(), locals=locals(), fromlist="*") try: attrlist = m.__all__ except AttributeError: attrlist = dir(m) for attr in [a for a in attrlist if '__' not in a]: globals()[attr] = getattr(m, attr) except ImportError, e: sys.stderr.write('Unable to read settings_%s.py\n' % HOSTNAME) sys.exit(1) ```
How does one do the equivalent of "import * from module" with Python's __import__ function?
[ "", "python", "python-import", "" ]
I am working on a ASP.net application written in C# with Sql Server 2000 database. We have several PDF reports which clients use for their business needs. The problem is these reports take a while to generate (> 3 minutes). What usually ends up happening is when the user requests the report the request timeout kills the request before the web server has time to finish generating the report, so the user never gets a chance to download the file. Then the user will refresh the page and try again, which starts the entire report generation process over and still ends up timing out. (No we aren't caching reports right now; that is something I am pushing hard for...). How do you handle these scenarios? I have an idea in my head which involves making an aysnchronous request to start the report generating and then have some javascript to periodically check the status. Once the status indicates the report is finished then make a separate request for the actual file. Is there a simpler way that I am not seeing?
Using the filesystem here is probably a good bet. Have a request that immediately returns a url to the report pdf location. Your server can then either kick off an external process or send a request to itself to perform the reporting. The client can poll the server (using http HEAD) for the PDF at the supplied url. If you make the filename of the PDF derive from the report parameters, either by using a hash or directly putting the parameters into the name you will get instant server side caching too.
I would consider making this report somehow a little bit more offline from the processing point of view. Like creating a queue to put report requests into, process the reports from there and after finish, it can send a message to the user. Maybe I would even create a separate Windows Service for the queue handling. **Update:** sending to the user can be email or they can have a 'reports' page, where they can check their reports' status and download them if they are ready.
Handling Long Running Reports
[ "", "c#", "asp.net", "ajax", "reporting", "" ]
On a JSTL/JSP page, I have a java.util.Date object from my application. I need to find the day *after* the day specified by that object. I can use <jsp:scriptlet> to drop into Java and use java.util.Calendar to do the necessary calculations, but this feels clumsy and inelegant to me. Is there some way to use JSP or JSTL tags to achieve this end without having to switch into full-on Java, or is the latter the only way to accomplish this?
I'm not a fan of putting java code in your jsp. I'd use a static method and a taglib to accomplish this. Just my idea though. There are many ways to solve this problem. ``` public static Date addDay(Date date){ //TODO you may want to check for a null date and handle it. Calendar cal = Calendar.getInstance(); cal.setTime (date); cal.add (Calendar.DATE, 1); return cal.getTime(); } ``` functions.tld ``` <?xml version="1.0" encoding="UTF-8" ?> <taglib xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-jsptaglibrary_2_0.xsd" version="2.0"> <description>functions library</description> <display-name>functions</display-name> <tlib-version>1.1</tlib-version> <short-name>xfn</short-name> <uri>http://yourdomain/functions.tld</uri> <function> <description> Adds 1 day to a date. </description> <name>addDay</name> <function-class>Functions</function-class> <function-signature>java.util.Date addDay(java.util.Date)</function-signature> <example> ${xfn:addDay(date)} </example> </function> </taglib> ```
While this does not answer your initial question, you could perhaps eliminate the hassle of going through java.util.Calendar by doing this: ``` // Date d given d.setTime(d.getTime()+86400000); ```
In JSTL/JSP, given a java.util.Date, how do I find the next day?
[ "", "java", "jsp", "jstl", "" ]
Do you know any libraries similar to java.util.Properties that support more advanced features like grouping properties, storing arrays, etc? I am not looking for some heavy super-advanced solution, just something light and useful for any project. Thanks.
[Commons Configuration](http://commons.apache.org/configuration/) from the apache group sounds a lot like what you're looking for.
I've used [`java.util.prefs`](http://java.sun.com/javase/6/docs/api/java/util/prefs/package-summary.html) before, and it seems to do the trick for me. Your mileage may vary.
Can you suggest something a little more advanced than java.util.Properties?
[ "", "java", "configuration", "properties", "" ]
I have an Xtext/Xpand (oAW 4.3, Eclipse 3.4) generator plug-in, which I run together with the editor plug-in in a second workbench. There, I'd like to run Xpand workflows programmatically on the model file I create. If I set the model file using the absolute path of the IFile I have, e.g. with: ``` String dslFile = file.getLocation().makeAbsolute().toOSString(); ``` Or if I use a file URI retrieved with: ``` String dslFile = file.getLocationURI().toString(); ``` The file is not found: ``` org.eclipse.emf.ecore.resource.Resource$IOWrappedException: Resource '/absolute/path/to/my/existing/dsl.file' does not exist. at org.openarchitectureware.xtext.parser.impl.AbstractParserComponent.invokeInternal(AbstractParserComponent.java:55) ``` To what value should I set the model file attribute (dslFile) in the map I hand to the WorkflowRunner: ``` Map properties = new HashMap(); properties.put("modelFile", dslFile); ``` I also tried leaving the properties empty and referencing the model file relative to the workflow file (inside the workflow file), but that yields a FileNotFoundException. Running all of this in a normal app (not in a second workbench) works fine.
I found help at the [openArchitectureWare forum](http://openarchitectureware.org/forum/viewtopic.php?showtopic=10197). Basically using ``` properties.put("modelFile", file.getLocation().makeAbsolute().toOSString()); ``` works, but you need to specify looking it up via URI in the workflow you are calling: ``` <component class="org.eclipse.mwe.emf.Reader"> <uri value='${modelFile}'/> <modelSlot value='theModel'/> </component> ```
2 important things for people looking in here...the TE used a IFLE for the "file.get....", and the correct syntax for paths is "file:/c:/myOSbla".
How to programmatically run an Xpand workflow on a model in a second workbench?
[ "", "java", "eclipse", "xtext", "xpand", "oaw", "" ]
I have a JavaScript widget which provides standard extension points. One of them is the `beforecreate` function. It should return `false` to prevent an item from being created. I've added an Ajax call into this function using jQuery: ``` beforecreate: function (node, targetNode, type, to) { jQuery.get('http://example.com/catalog/create/' + targetNode.id + '?name=' + encode(to.inp[0].value), function (result) { if (result.isOk == false) alert(result.message); }); } ``` But I want to prevent my widget from creating the item, so I should return `false` in the mother-function, not in the callback. Is there a way to perform a synchronous AJAX request using jQuery or any other in-browser API?
From the [jQuery documentation](https://api.jquery.com/jquery.ajax/): you specify the **asynchronous** option to be **false** to get a synchronous Ajax request. Then your callback can set some data before your mother function proceeds. Here's what your code would look like if changed as suggested: ``` beforecreate: function (node, targetNode, type, to) { jQuery.ajax({ url: 'http://example.com/catalog/create/' + targetNode.id + '?name=' + encode(to.inp[0].value), success: function (result) { if (result.isOk == false) alert(result.message); }, async: false }); } ```
You can put the jQuery's Ajax setup in synchronous mode by calling ``` jQuery.ajaxSetup({async:false}); ``` And then perform your Ajax calls using `jQuery.get( ... );` Then just turning it on again once ``` jQuery.ajaxSetup({async:true}); ``` I guess it works out the same thing as suggested by @Adam, but it might be helpful to someone that does want to reconfigure their `jQuery.get()` or `jQuery.post()` to the more elaborate `jQuery.ajax()` syntax.
How can I get jQuery to perform a synchronous, rather than asynchronous, Ajax request?
[ "", "javascript", "jquery", "ajax", "asynchronous", "" ]
I'm trying to design some tables to store some data, which has to be converted to different languages later. Can anybody provide some "best practices" or guidelines for this? Thanks
Let's say you have a products table that looks like this: ``` Products ---------- id price Products_Translations ---------------------- product_id locale name description ``` Then you just join on product\_id = product.id and where locale='en-US' of course this has an impact on performance, since you now need a join to get the name and description, but it allows any number of locales later on.
Can you describe the nature of the 'dynamic data'? One way to implement this would be to have 3 different tables: * Language Table + This table would store the language and a key : ``` [1, English], [2, Spanish] ``` * Data Definition Table + When dynamic data is first entered make a record in this table with and identifier to the data: ``` [1, 'Data1'], [2, 'Data2'] ``` * Data\_Language Table + This table will link the language, data definition and translation ``` So: [Data_Language, Data_Definition, Language, Translation] [1, 1, 1, 'Red'] [2, 1, 2, 'Rojo'] [3, 2, 1, 'Green'] [4, 2, 2, 'Verde'] etc ... ``` When the dynamic data is entered create the default 'English' record and then translate at your leisure.
Good database table design for storing localized versions of data
[ "", "sql", "sql-server", "database-design", "localization", "" ]
I've just solved another \*I-though-I-was-using-this-version-of-a-library-but-apparently-my-app-server-has-already-loaded-an-older-version-of-this-library-\*issue (sigh). Does anybody know a good way to verify (or monitor) whether your application has access to all the appropriate jar-files, or loaded class-versions? Thanks in advance! [P.S. A very good reason to start using the [OSGi module architecture](http://en.wikipedia.org/wiki/OSGi#Architecture) in my view!] **Update**: [This](http://www.jboss.org/community/docs/DOC-9697) article helped as well! It gave me insight which classes JBoss' classloader loaded by writing it to a log file.
If you happen to be using JBoss, there is an MBean (the class loader repository iirc) where you can ask for all classloaders that have loaded a certain class. If all else fails, there's always `java -verbose:class` which will print the location of the jar for every class file that is being loaded.
If you've got appropriate versions info in a jar manifest, there are methods to retrieve and test the version. No need to manually read the manifest. [java.lang.Package](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/lang/Package.html).getImplementationVersion() and getSpecificationVersion() and isCompatibleWith() sound like they'd do what you're looking for. You can get the Package with this.getClass().getPackage() among other ways. The javadoc for java.lang.Package doesn't give the specific manifest attribute names for these attributes. A quick google search turned it up at <http://java.sun.com/docs/books/tutorial/deployment/jar/packageman.html>
Classloader issues - How to determine which library versions (jar-files) are loaded
[ "", "java", "jar", "classloader", "" ]
I am making my switch from coding in C++ to C#. I need to replace my C++ error logging/reporting macro system with something similar in C#. In my C++ source I can write LOGERR("Some error"); or LOGERR("Error with inputs %s and %d", stringvar, intvar); The macro & supporting library code then passes the (possibly varargs) formatted message into a database along with the source file, source line, user name, and time. The same data is also stuffed into a data structure for later reporting to the user. Does anybody have C# code snippets or pointers to examples that do this basic error reporting/logging? **Edit:** At the time I asked this question I was really new to .NET and was unaware of System.Diagnostics.Trace. System.Diagnostics.Trace was what I needed at that time. Since then I have used log4net on projects where the logging requirements were larger and more complex. Just edit that 500 line XML configuration file and log4net will do everything you will ever need :)
Lots of log4net advocates here so I'm sure this will be ignored, but I'll add my own preference: ``` System.Diagnostics.Trace ``` This includes listeners that listen for your `Trace()` methods, and then write to a log file/output window/event log, ones in the framework that are included are `DefaultTraceListener`, `TextWriterTraceListener` and the `EventLogTraceListener`. It allows you to specify levels (Warning,Error,Info) and categories. [Trace class on MSDN](http://msdn.microsoft.com/en-us/library/system.diagnostics.trace.aspx) [Writing to the Event Log in a Web Application](https://stackoverflow.com/questions/286060/what-do-i-need-to-change-to-alllow-my-iis7-asp-net-3-5-application-to-create-an/7848414#7848414) [UdpTraceListener - write log4net compatible XML messages to a log viewer such as log2console](http://www.anotherchris.net/log4net/udptracelistener-a-udp-tracelistener-compatible-with-log4netlog4j/)
I would highly recommend looking at [log4Net](http://logging.apache.org/log4net/). This [post](https://mitchwheat.com/2007/04/29/log4net-net-logging-tool/) covers the majority of what you need to get started.
Error logging in C#
[ "", "c#", "error-reporting", "error-logging", "" ]
I have a pretty basic windows form app in .Net. All the code is C#. I'd like to turn it into an Asp.net web app. How can I easily do this? I think there's an easy way since the controls I drag/drop onto the windows form designer are pretty much the same that I drag/drop onto the aspx design page. Note: the windows form app doesn't make any network requests or anything... just reads some text files from the local machine.
There are two big problems here; first - they might look the same, but they are implemented completely differently - all of the UI work will need to be redone, largely from scratch. You will probably be able to re-use your actual "doing" code, though (i.e. the logic that manipulates the files). Second - define "local machine". For an ASP.NET application, this is usually the server, which might not be what you want. You can do some things clientside via javascript, but the sandbox security model will prevent you doing much file IO. I would suggest perhaps looking at Silverlight, which is somewhere between the two - or perhaps just use ClickOnce to deploy your existing winform exe to remote clients.
You'll likely have issues reading files from the local machine via ASP.Net: for an ASP.Net app, the local machine is the web server, not the computer where the user is sitting. Also, there's a lot more to it than you'd think. odds are somewhere in your app you're relying on the fact the a windows forms app is inherently stateful, and moving to ASP.Net will be a rude awakening in that respect.
How can I easily turn a .Net Windows Form app into an Asp.net app using Visual Studio 2005?
[ "", "c#", "asp.net", "winforms", "" ]
I am trying to pass a member function within a class to a function that takes a member function class pointer. The problem I am having is that I am not sure how to properly do this within the class using the this pointer. Does anyone have suggestions? Here is a copy of the class that is passing the member function: ``` class testMenu : public MenuScreen{ public: bool draw; MenuButton<testMenu> x; testMenu():MenuScreen("testMenu"){ x.SetButton(100,100,TEXT("buttonNormal.png"),TEXT("buttonHover.png"),TEXT("buttonPressed.png"),100,40,&this->test2); draw = false; } void test2(){ draw = true; } }; ``` The function x.SetButton(...) is contained in another class, where "object" is a template. ``` void SetButton(int xPos, int yPos, LPCWSTR normalFilePath, LPCWSTR hoverFilePath, LPCWSTR pressedFilePath, int Width, int Height, void (object::*ButtonFunc)()) { BUTTON::SetButton(xPos, yPos, normalFilePath, hoverFilePath, pressedFilePath, Width, Height); this->ButtonFunc = &ButtonFunc; } ``` If anyone has any advice on how I can properly send this function so that I can use it later.
To call a member function by pointer, you need two things: A pointer to the object and a pointer to the function. You need both in `MenuButton::SetButton()` ``` template <class object> void MenuButton::SetButton(int xPos, int yPos, LPCWSTR normalFilePath, LPCWSTR hoverFilePath, LPCWSTR pressedFilePath, int Width, int Height, object *ButtonObj, void (object::*ButtonFunc)()) { BUTTON::SetButton(xPos, yPos, normalFilePath, hoverFilePath, pressedFilePath, Width, Height); this->ButtonObj = ButtonObj; this->ButtonFunc = ButtonFunc; } ``` Then you can invoke the function using both pointers: ``` ((ButtonObj)->*(ButtonFunc))(); ``` Don't forget to pass the pointer to your object to `MenuButton::SetButton()`: ``` testMenu::testMenu() :MenuScreen("testMenu") { x.SetButton(100,100,TEXT("buttonNormal.png"), TEXT("buttonHover.png"), TEXT("buttonPressed.png"), 100, 40, this, test2); draw = false; } ```
I'd strongly recommend `boost::bind` and `boost::function` for anything like this. See [Pass and call a member function (boost::bind / boost::function?)](https://stackoverflow.com/questions/5245072/pass-and-call-a-member-function-boostbind-boostfunction)
How do you pass a member function pointer?
[ "", "c++", "class", "function", "pointers", "member", "" ]
I am currently suffering a brain fart. I've done this before but I can't remember the exact syntax and I can't look at the code I wrote because I was working at another company at the time. I have this arrangement: ``` class P { // stuff }; class PW : public P { // more stuff }; class PR : public P { // more stuff }; class C { public: P GetP() const { return p; } private: P p; }; // ... P p = c.GetP( ); // valid PW p = c.GetP( ); // invalid PR p = c.GetP( ); // invalid // ... ``` Now I would like to make P interchangeable with PW and PR (and thus PW and PR can be interchanged). I could probably get away with casts but this code change has occurred quite a few times in this module alone. I am pretty sure it is a operator but for the life of me I can't remember what. **How do I make P interchangeable with PW and PR with minimal amount of code?** **Update:** To give a bit more clarification. P stands for Project and the R and W stands for Reader and Writer respectively. All the Reader has is the code for loading - no variables, and the writer has code for simply Writing. It needs to be separate because the Reading and Writing sections has various manager classes and dialogs which is none of Projects real concern which is the manipulation of project files. **Update:** I also need to be able to call the methods of P and PW. So if P has a method a() and PW as a method call b() then I could : ``` PW p = c.GetP(); p.a(); p.b(); ``` It's basically to make the conversion transparent.
If you want to get this part to compile: ``` // ... P p = c.GetP( ); // valid PW p = c.GetP( ); // invalid PR p = c.GetP( ); // invalid // ... ``` You need to be able to construct/convert a P into a PW or a PR. You need to do something like this: ``` class PW : public P { PW(const P &); // more stuff }; class PR : public P { PR(const P &); // more stuff }; ``` Or did you mean something more like: ``` class P { operator PW() const; operator PR() const; // stuff }; ```
You're trying to coerce actual variables, rather than pointers. To do that would require a cast. However, if your class definition looked like this: ``` class C { public: P* GetP() const { return p; } private: P* p; } ``` Then, whether p was a pointer to a P, a PW, or a PR, your function wouldn't change, and any (virtual) functions called on the P\* returned by the function would use the implementation from P, PW or PR depending on what the member p was.. I guess the key thing to remember is the [Liskov Substitution Principle](http://en.wikipedia.org/wiki/Liskov_substitution_principle). Since PW and PR are subclasses of P, they can be treated as if they were Ps. However, PWs cannot be treated as PRs, and vice versa.
Automatic casts
[ "", "c++", "casting", "" ]
I have an ext combobox which uses a store to suggest values to a user as they type. An example of which can be found here: [combobox example](http://extjs.com/deploy/ext/examples/form/combos.html) Is there a way of making it so the **suggested text list** is rendered to an element in the DOM. Please note I do not mean the "applyTo" config option, as this would render the whole control, including the textbox to the DOM element.
You can use plugin for this, since you can call or even override private methods from within the plugin: ``` var suggested_text_plugin = { init: function(o) { o.onTypeAhead = function() { // Original code from the sources goes here: if(this.store.getCount() > 0){ var r = this.store.getAt(0); var newValue = r.data[this.displayField]; var len = newValue.length; var selStart = this.getRawValue().length; if(selStart != len){ this.setRawValue(newValue); this.selectText(selStart, newValue.length); } } // Your code to display newValue in DOM ......myDom.getEl().update(newValue); }; } }; // in combobox code: var cb = new Ext.form.ComboBox({ .... plugins: suggested_text_plugin, .... }); ``` I think it's even possible to create a whole chain of methods, calling original method before or after yours, but I haven't tried this yet. Also, please don't push me hard for using non-standard plugin definition and invocation methodics (undocumented). It's just my way of seeing things. EDIT: I think the method chain could be implemented something like that (untested): ``` .... o.origTypeAhead = new Function(this.onTypeAhead.toSource()); // or just o.origTypeAhead = this.onTypeAhead; .... o.onTypeAhead = function() { // Call original this.origTypeAhead(); // Display value into your DOM element ...myDom.... }; ```
@qui Another thing to consider is that initList is not part of the API. That method could disappear or the behavior could change significantly in future releases of Ext. If you never plan on upgrading, then you don't need to worry.
Rendering suggested values from an ext Combobox to an element in the DOM
[ "", "javascript", "extjs", "" ]
I code C++ using MS Dev Studio and I work from home two days per week. I use CVS to keep my sources synchronized between the two computers but there are difference between the environments the machines are in. Can anyone suggest a way I can conditionally modify constants in my code depending on whether I am compiling on my home box or not ? What I am after is a way of defining a symbol, let's call it \_ATHOME, automatically so I can do this: ``` #ifdef _ATHOME # define TEST_FILES "E:\\Test" # define TEST_SERVER "192.168.0.1" #else # define TEST_FILE "Z:\\Project\\Blah\\Test" # define TEST_SERVER "212.45.68.43" #endif ``` *NB: This is for development and debugging purposes of course, I would never release software with hard coded constants like this.*
On your home and work machines, set an environment variable `LOCATION` that is either "1" for home or "2" for work. Then in the preprocessor options, add a preprocessor define /DLOCATION=$(LOCATION). This will evaluate to either the "home" or "work" string that you set in the environment variable. Then in your code: ``` #if LOCATION==1 // home #else // work #endif ```
If the only difference between work and home is where the test files are located... then (IMHO) you shouldn't pollute your build files with a bunch of static paths & IPs. For the example you showed, I would simply map drives on both work and home. I.e. at work map a drive T: that points to \\212.45.68.43\Project\Blah\Test, at home map a drive T: that points to \\192.168.0.1\Test. Then your build process uses the path "T:\" to refer to where tests reside. Of course, if you need to change something more drastic, setting environment variables is probably the best way to go.
Conditional compilation for working at home
[ "", "c++", "" ]
``` class someclass {}; class base { int a; int *pint; someclass objsomeclass; someclass* psomeclass; public: base() { objsomeclass = someclass(); psomeclass = new someclass(); pint = new int(); throw "constructor failed"; a = 43; } } int main() { base temp(); } ``` In the above code, the constructor throws. Which objects will be leaked, and how can the memory leaks be avoided? ``` int main() { base *temp = new base(); } ``` How about in the above code? How can the memory leaks be avoided after the constructor throws?
Yes it will leak memory. When the constructor throws, no destructor will be called (in this case you don't show a destructor that frees the dynamically allocated objects, but lets assume you had one). This is a major reason to use smart pointers - since the smart poitners are full fledged objects, they will get destructors called during the exception's stack unwind and have the opportunity to free the memory. If you use something like Boost's scoped\_ptr<> template, your class could look more like: ``` class base{ int a; scoped_ptr<int> pint; someclass objsomeclass; scoped_ptr<someclass> psomeclass; base() : pint( new int), objsomeclass( someclass()), psomeclass( new someclass()) { throw "constructor failed"; a = 43; } } ``` And you would have no memory leaks (and the default dtor would also clean up the dynamic memory allocations). --- To sum up (and hopefully this also answers the question about the ``` base* temp = new base(); ``` statement): When an exception is thrown inside a constructor there are several things that you should take note of in terms of properly handling resource allocations that may have occured in the aborted construction of the object: 1. the destructor for the object being constructed will **not** be called. 2. destructors for member objects contained in that object's class will be called 3. the memory for the object that was being constructed will be freed. This means that if your object owns resources, you have 2 methods available to clean up those resources that might have already been acquired when the constructor throws: 1. catch the exception, release the resources, then rethrow. This can be difficult to get correct and can become a maintenance problem. 2. use objects to manage the resource lifetimes (RAII) and use those objects as the members. When the constructor for your object throws an exception, the member objects will have desctructors called and will have an opportunity to free the resource whose lifetimes they are responsible for.
Both new's will be leaked. Assign the address of the heap created objects to **named** smart pointers so that it will be deleted inside the smart pointers destructor that get call when the exception is thrown - ([RAII](http://en.wikipedia.org/wiki/RAII)). ``` class base { int a; boost::shared_ptr<int> pint; someclass objsomeclass; boost::shared_ptr<someclass> psomeclass; base() : objsomeclass( someclass() ), boost::shared_ptr<someclass> psomeclass( new someclass() ), boost::shared_ptr<int> pint( new int() ) { throw "constructor failed"; a = 43; } }; ``` Now *psomeclass* & *pint* destructors will be called when the stack unwind when the exception is thrown in the constructor, and those destructors will deallocate the allocated memory. ``` int main(){ base *temp = new base(); } ``` For ordinary memory allocation using (non-plcaement) new, memory allocated by the operator new is freed automatically if the constructor throws an exception. In terms of why bother freeing individual members (in response to comments to Mike B's answer), the automatic freeing only applies when an exception is thrown in a constructor of an object being new'ly allocated, not in other cases. Also, the memory that is freed is those allocated for the object members, not any memory you might have allocated say inside the constructor. i.e. It would free the memory for the member variables *a*, *pint*, *objsomeclass*, and *psomeclass*, but not the memory allocated from *new someclass()* and *new int()*.
Will the below code cause memory leak in c++
[ "", "c++", "exception", "memory-leaks", "constructor", "" ]
is there an alternative for `mysql_insert_id()` php function for PostgreSQL? Most of the frameworks are solving the problem partially by finding the current value of the sequence used in the ID. However, there are times that the primary key is not a serial column....
From the PostgreSQL point of view, in pseudo-code: ``` * $insert_id = INSERT...RETURNING foo_id;-- only works for PostgreSQL >= 8.2. * INSERT...; $insert_id = SELECT lastval(); -- works for PostgreSQL >= 8.1 * $insert_id = SELECT nextval('foo_seq'); INSERT INTO table (foo...) values ($insert_id...) for older PostgreSQL (and newer PostgreSQL) ``` `pg_last_oid()` only works where you have OIDs. OIDs have been off by default since PostgreSQL 8.1. So, depending on which PostgreSQL version you have, you should pick one of the above method. Ideally, of course, use a database abstraction library which abstracts away the above. Otherwise, in low level code, it looks like: # Method one: INSERT... RETURNING ``` // yes, we're not using pg_insert() $result = pg_query($db, "INSERT INTO foo (bar) VALUES (123) RETURNING foo_id"); $insert_row = pg_fetch_row($result); $insert_id = $insert_row[0]; ``` # Method two: INSERT; lastval() ``` $result = pg_execute($db, "INSERT INTO foo (bar) values (123);"); $insert_query = pg_query("SELECT lastval();"); $insert_row = pg_fetch_row($insert_query); $insert_id = $insert_row[0]; ``` # Method three: nextval(); INSERT ``` $insert_query = pg_query($db, "SELECT nextval('foo_seq');"); $insert_row = pg_fetch_row($insert_query); $insert_id = $insert_row[0]; $result = pg_execute($db, "INSERT INTO foo (foo_id, bar) VALUES ($insert_id, 123);"); ``` The safest bet would be the third method, but it's unwieldy. The cleanest is the first, but you'd need to run a recent PostgreSQL. Most db abstraction libraries don't yet use the first method though.
You also can use: ``` $result = pg_query($db, "INSERT INTO foo (bar) VALUES (123) RETURNING foo_id"); $insert_row = pg_fetch_result($result, 0, 'foo_id'); ``` You have to specify in pg\_fetch\_result the number of the row and the name of the field that you are looking for, this is a more precise way to get the data that you need, but I don't know if this has some penalty in the performance of the query. Remember that this method is for PostgreSQL versions 8.2 and up.
mysql_insert_id alternative for postgresql
[ "", "php", "postgresql", "insert-id", "" ]
I am writing a C# control that wraps DirectX 9 and provides a simplified interface to perform 2D pixel level drawing. .NET requires that I wrap this code in an unsafe code block and compile with the allow unsafe code option. I'm locking the entire surface which then returns a pointer to the locked area of memory. I can then write pixel data directly using "simple" pointer arithmetic. I have performance tested this and found a substantial speed improvement over other "safe" methods I know of. Is this the fastest way to manipulate individual pixels in a C# .NET application? Is there a better, safer way? If there was an equally fast approach that does not require pointer manipulation it would be my preference to use that. (I know this is 2008 and we should all be using DirectX 3D, [OpenGL](http://en.wikipedia.org/wiki/OpenGL), etc., however this control is to be used exclusively for 2D pixel rendering and simply does not require 3D rendering.)
Using unsafe pointers is the fastest way to do direct memory manipulation in C# (definitely faster than using the Marshal wrapper functions). Just out of curiosity, what sort of 2D drawing operations are you trying to perform? I ask because locking a DirectX surface to do pixel level manipulations will defeat most of the hardware acceleration benefits that you would hope to gain from using DirectX. Also, the DirectX device will fail to initialize when used over terminal services (remote desktop), so the control will be unusable in that scenario (this may not matter to you). DirectX will be a big win when drawing large triangles and transforming images (texture mapped onto a quad), but it won't really perform that great with single pixel manipulation. Staying in .NET land, one alternative is to keep around a Bitmap object to act as your surface, using LockBits and directly accessing the pixels through the unsafe pointer in the returned BitmapData object.
Yes, that is probably the fastest way. A few years ago I had to compare two 1024x1024 images at the pixel level; the get-pixel methods took 2 minutes, and the unsafe scan took 0.01 seconds.
Unsafe C# and pointers for 2D rendering, good or bad?
[ "", "c#", "graphics", "pointers", "" ]
Why does the `sizeof` operator return a size larger for a structure than the total sizes of the structure's members?
This is because of padding added to satisfy alignment constraints. [Data structure alignment](http://en.wikipedia.org/wiki/Data_structure_alignment) impacts both performance and correctness of programs: * Mis-aligned access might be a hard error (often `SIGBUS`). * Mis-aligned access might be a soft error. + Either corrected in hardware, for a modest performance-degradation. + Or corrected by emulation in software, for a severe performance-degradation. + In addition, atomicity and other concurrency-guarantees might be broken, leading to subtle errors. Here's an example using typical settings for an x86 processor (all used 32 and 64 bit modes): ``` struct X { short s; /* 2 bytes */ /* 2 padding bytes */ int i; /* 4 bytes */ char c; /* 1 byte */ /* 3 padding bytes */ }; struct Y { int i; /* 4 bytes */ char c; /* 1 byte */ /* 1 padding byte */ short s; /* 2 bytes */ }; struct Z { int i; /* 4 bytes */ short s; /* 2 bytes */ char c; /* 1 byte */ /* 1 padding byte */ }; const int sizeX = sizeof(struct X); /* = 12 */ const int sizeY = sizeof(struct Y); /* = 8 */ const int sizeZ = sizeof(struct Z); /* = 8 */ ``` One can minimize the size of structures by sorting members by alignment (sorting by size suffices for that in basic types) (like structure `Z` in the example above). IMPORTANT NOTE: Both the C and C++ standards state that structure alignment is implementation-defined. Therefore each compiler may choose to align data differently, resulting in different and incompatible data layouts. For this reason, when dealing with libraries that will be used by different compilers, it is important to understand how the compilers align data. Some compilers have command-line settings and/or special `#pragma` statements to change the structure alignment settings.
Packing and byte alignment, as described in the C FAQ [here](http://www.c-faq.com/struct/align.html): > It's for alignment. Many processors can't access 2- and 4-byte > quantities (e.g. ints and long ints) if they're crammed in > every-which-way. > > Suppose you have this structure: > > ``` > struct { > char a[3]; > short int b; > long int c; > char d[3]; > }; > ``` > > Now, you might think that it ought to be possible to pack this > structure into memory like this: > > ``` > +-------+-------+-------+-------+ > | a | b | > +-------+-------+-------+-------+ > | b | c | > +-------+-------+-------+-------+ > | c | d | > +-------+-------+-------+-------+ > ``` > > But it's much, much easier on the processor if the compiler arranges > it like this: > > ``` > +-------+-------+-------+ > | a | > +-------+-------+-------+ > | b | > +-------+-------+-------+-------+ > | c | > +-------+-------+-------+-------+ > | d | > +-------+-------+-------+ > ``` > > In the packed version, notice how it's at least a little bit hard for > you and me to see how the b and c fields wrap around? In a nutshell, > it's hard for the processor, too. Therefore, most compilers will pad > the structure (as if with extra, invisible fields) like this: > > ``` > +-------+-------+-------+-------+ > | a | pad1 | > +-------+-------+-------+-------+ > | b | pad2 | > +-------+-------+-------+-------+ > | c | > +-------+-------+-------+-------+ > | d | pad3 | > +-------+-------+-------+-------+ > ```
Why isn't sizeof for a struct equal to the sum of sizeof of each member?
[ "", "c++", "c", "struct", "sizeof", "c++-faq", "" ]
How do I get the caller's IP address in a WebMethod? ``` [WebMethod] public void Foo() { // HttpRequest... ? - Not giving me any options through intellisense... } ``` using C# and ASP.NET
[HttpContext.Current.Request.UserHostAddress](http://msdn.microsoft.com/en-us/library/system.web.httprequest.userhostaddress.aspx) is what you want.
Just a caution. IP addresses can't be used to uniquely identify clients. NAT Firewalls and corporate proxies are everywhere, and hide many users behind a single IP.
How do I get the caller's IP address in a WebMethod?
[ "", "c#", "asp.net", "web-services", "" ]
I've been working on a project where I need to iterate through a collection of data and remove entries where the "primary key" is duplicated. I have tried using a ``` List<int> ``` and ``` Dictionary<int, bool> ``` With the dictionary I found slightly better performance, even though I never need the Boolean tagged with each entry. My expectation is that this is because a List allows for indexed access and a Dictionary does not. What I was wondering is, is there a better solution to this problem. I do not need to access the entries again, I only need to track what "primary keys" I have seen and make sure I only perform addition work on entries that have a new primary key. I'm using C# and .NET 2.0. And I have no control over fixing the input data to remove the duplicates from the source (unfortunately!). And so you can have a feel for scaling, overall I'm checking for duplicates about 1,000,000 times in the application, but in subsets of no more than about 64,000 that need to be unique.
They have added the HashSet class in .NET 3.5. But I guess it will be on par with the Dictionary. If you have less than say a 100 elements a List will probably perform better.
**Edit: Nevermind my comment. I thought you're talking about C++. I have no idea if my post is relevant in the C# world..** A hash-table could be a tad faster. Binary trees (that's what used in the dictionary) tend to be relative slow because of the way the memory gets accessed. This is especially true if your tree becomes very large. However, before you change your data-structure, have you tried to use a custom pool allocator for your dictionary? I bet the time is not spent traversing the tree itself but in the millions of allocations and deallocations the dictionary will do for you. You may see a factor 10 speed-boost just plugging a simple pool allocator into the dictionary template. Afaik boost has a component that can be directly used. Another option: If you know only 64.000 entries in your integers exist you can write those to a file and create a perfect hash function for it. That way you can just use the hash function to map your integers into the 0 to 64.000 range and index a bit-array. Probably the fastest way, but less flexible. You have to redo your perfect hash function (can be done automatically) each time your set of integers changes.
Performance when checking for duplicates
[ "", "c#", "performance", "collections", ".net-2.0", "" ]
What are some suggestions for easy to use C++ compilers for a beginner? Free or open-source ones would be preferred.
GCC is a good choice for simple things. Visual Studio Express edition is the free version of the major windows C++ compiler. If you are on Windows I would use VS. If you are on linux you should use GCC. \*I say GCC for simple things because for a more complicated project the build process isn't so easy
G++ is the GNU C++ compiler. Most \*nix distros should have the package available.
What are some good compilers to use when learning C++?
[ "", "c++", "compiler-construction", "" ]
We have various php projects developed on windows (xampp) that need to be deployed to a mix of linux/windows servers. We've used [capistrano](http://www.capify.org/) in the past to deploy from windows to the linux servers, but recent changes in architecture and windows servers left the old config not working. The recipe works fine for the linux deployment, but setting up the windows servers has required more time than we have right now. Ideas for the Capistrano recipe are valid answers. obviously the windows/linux servers don't share users, so this complicates it a tad (for the capistrano assumption of same username/password everywhere). Currently we're using svn-update for the windows servers, which i dislike, since it leaves all the svn files hanging on the production servers. (and we still have to manually svn-update them on windows) And manual updating of files using winscp and syncing the directories with their linux counterparts. My question is, what tools/setup do you suggest to automatize this deployment scenario: **"Various php windows/linux developers deploying to 2+ mixed windows/linux machines"** (ps: we have no problems using linux tools or anything working through cygwin, we simply need to make deployment a simple one-step operation) *edit: Currently we can't work on a all-linux enviroment, we have to deploy to both linux and windows server. We can start the deploy from anywhere, but we'd prefer to be able to do it from either enviroment.*
I use 4 different approaches depending on the client environment: 1. Capistrano and similar tools (effective, but complex) 2. `rsync` from + to Windows, Linux, Mac (simple, doesn't enforce discipline) 3. `svn` from + to Windows, Linux, Mac (simple, doesn't enforce discipline) 4. On-server scripts (run through the browser, complex) There are some requirements that drive what you need: * How much discipline you want to enforce * If you need database (or configuration) migrations (up and/or down) * If you want a static "we're down" page * Who can do the update * Configuration differences between servers I strongly suggest enforcing enough discipline to save you from yourself: deploy to a development server, allow for upward migrations and simple database restore, and limit who can update the live server to a small number of responsible admins (where the dev server is open to more developers). Also consider pushing via a cron job (to the development server), so there's a daily snapshot of your incremental changes. Most of the time, I find that either `svn` or `rsync` setups are enough, with a few server-side scripts, especially when the admin set is limited to a few developers.
This will probably sound silly but... I used to have this kind of problem all the time until I decided in the end that if I'm always *deploying* on Linux, I ought really to at least try *developing* on Linux also. I did. It was pain free. I never went back. Now. I am not suggesting this is for everyone. But, if you install [VirtualBox](http://www.virtualbox.org/) you could run a Linux install as a local server on your windows box. Share a folder in the virtual machine and you can use all your known and trusted Windows software and techniques *and* have the piece of mind of knowing that everything is working well on its target platform. Plus you'll be able to go back to Capistrano (a fine choice) for deployment. Best of all, if you thought you knew Linux / Unix wait until you use it everyday on your desktop! Who knows you may even like it :)
PHP Deployment to windows/unix servers
[ "", "php", "windows", "linux", "deployment", "automation", "" ]
Each time a python file is imported that contains a large quantity of static regular expressions, cpu cycles are spent compiling the strings into their representative state machines in memory. ``` a = re.compile("a.*b") b = re.compile("c.*d") ... ``` Question: Is it possible to store these regular expressions in a cache on disk in a pre-compiled manner to avoid having to execute the regex compilations on each import? Pickling the object simply does the following, causing compilation to happen anyway: ``` >>> import pickle >>> import re >>> x = re.compile(".*") >>> pickle.dumps(x) "cre\n_compile\np0\n(S'.*'\np1\nI0\ntp2\nRp3\n." ``` And `re` objects are unmarshallable: ``` >>> import marshal >>> import re >>> x = re.compile(".*") >>> marshal.dumps(x) Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: unmarshallable object ```
> Is it possible to store these regular expressions in a cache on disk in a pre-compiled manner to avoid having to execute the regex compilations on each import? Not easily. You'd have to write a custom serializer that hooks into the C `sre` implementation of the Python regex engine. Any performance benefits would be vastly outweighed by the time and effort required. First, have you actually profiled the code? I doubt that compiling regexes is a significant part of the application's run-time. Remember that they are only compiled the first time the module is imported in the current execution -- thereafter, the module and its attributes are cached in memory. If you have a program that basically spawns once, compiles a bunch of regexes, and then exits, you could try re-engineering it to perform multiple tests in one invocation. Then you could re-use the regexes, as above. Finally, you could compile the regexes into C-based state machines and then link them in with an extension module. While this would likely be more difficult to maintain, it would eliminate regex compilation entirely from your application.
Note that each module initializes itself only once during the life of an app, no matter how many times you import it. So if you compile your expressions at the module's global scope (ie. not in a function) you should be fine.
Caching compiled regex objects in Python?
[ "", "python", "regex", "caching", "" ]
I need some software to explore and modify some SQLite databases. Does anything similar to SQL Server Management Studio or MySQLAdmin exist for it?
[As a Firefox plugin](https://addons.mozilla.org/en-US/firefox/addon/5817) (aimed mainly at gears, but should work) [As a (sucky) web based app](http://www.sqlitemanager.org) And [a big list of management tools](http://www.sqlite.org/cvstrac/wiki?p=ManagementTools)
I also discovered some SQLite software for Visual Studio at <http://sqlite.phxsoftware.com/> which allows you to use the Visual Studio Server Explorer to create connections to SQLite databases.
Is there a MySQLAdmin or SQL Server Management Studio equivalent for SQLite databases on Windows?
[ "", "sql", "windows", "sqlite", "" ]
This is sort of SQL newbie question, I think, but here goes. I have a SQL Query (SQL Server 2005) that I've put together based on an example user-defined function: ``` SELECT CASEID, GetNoteText(CASEID) FROM ( SELECT CASEID FROM ATTACHMENTS GROUP BY CASEID ) i GO ``` the UDF works great (it concatenates data from multiple rows in a related table, if that matters at all) but I'm confused about the "i" after the FROM clause. The query works fine with the i but fails without it. What is the significance of the "i"? EDIT: As Joel noted below, it's not a keyword
When you use a subquery in the FROM clause, you need to give the query a name. Since the name doesn't really matter to you, something simple like 'i' or 'a' is often chosen. But you could put any name there you wanted- there's no significance to 'i' all by itself, and it's certainly not a keyword. If you have a really complex query, you may need to join your sub query with other queries or tables. In that case the name becomes more important and you should choose something more meaningful.
The i names the (subquery), which is required, and also needed for further joins. You will have to prefix columns in the outer query with the subquery name when there are conflicting column names between joined tables, like: ``` SELECT c.CASEID, c.CASE_NAME, a.COUNT AS ATTACHMENTSCOUNT, o.COUNT as OTHERCOUNT, dbo.GetNoteText(c.CASEID) FROM CASES c LEFT OUTER JOIN ( SELECT CASEID, COUNT(*) AS COUNT FROM ATTACHMENTS GROUP BY CASEID ) a ON a.CASEID = c.CASEID LEFT OUTER JOIN ( SELECT CASEID, COUNT(*) AS COUNT FROM OTHER GROUP BY CASEID ) o ON o.CASEID = c.CASEID ```
Unfamiliar character in SQL statement
[ "", "sql", "sql-server", "t-sql", "derived-table", "" ]
Imagine this sample java class: ``` class A { void addListener(Listener obj); void removeListener(Listener obj); } class B { private A a; B() { a = new A(); a.addListener(new Listener() { void listen() {} } } ``` Do I need to add a finalize method to B to call a.removeListener? Assume that the A instance will be shared with some other objects as well and will outlive the B instance. I am worried that I might be creating a garbage collector problem here. What is the best practice?
I just found a huge memory leak, so I am going to call the code that created the leak to be *wrong* and my fix that does not leak as *right*. Here is the old code: (This is a common pattern I have seen all over) ``` class Singleton { static Singleton getInstance() {...} void addListener(Listener listener) {...} void removeListener(Listener listener) {...} } class Leaky { Leaky() { // If the singleton changes the widget we need to know so register a listener Singleton singleton = Singleton.getInstance(); singleton.addListener(new Listener() { void handleEvent() { doSomething(); } }); } void doSomething() {...} } // Elsewhere while (1) { Leaky leaky = new Leaky(); // ... do stuff // leaky falls out of scope } ``` Clearly, this is bad. Many Leaky's are being created and never get garbage collected because the listeners keep them alive. Here was my alternative that fixed my memory leak. This works because I only care about the event listener while the object exists. The listener should not keep the object alive. ``` class Singleton { static Singleton getInstance() {...} void addListener(Listener listener) {...} void removeListener(Listener listener) {...} } class NotLeaky { private NotLeakyListener listener; NotLeaky() { // If the singleton changes the widget we need to know so register a listener Singleton singleton = Singleton.getInstance(); listener = new NotLeakyListener(this, singleton); singleton.addListener(listener); } void doSomething() {...} protected void finalize() { try { if (listener != null) listener.dispose(); } finally { super.finalize(); } } private static class NotLeakyListener implements Listener { private WeakReference<NotLeaky> ownerRef; private Singleton eventer; NotLeakyListener(NotLeaky owner, Singleton e) { ownerRef = new WeakReference<NotLeaky>(owner); eventer = e; } void dispose() { if (eventer != null) { eventer.removeListener(this); eventer = null; } } void handleEvent() { NotLeaky owner = ownerRef.get(); if (owner == null) { dispose(); } else { owner.doSomething(); } } } } // Elsewhere while (1) { NotLeaky notleaky = new NotLeaky(); // ... do stuff // notleaky falls out of scope } ```
There is a cycle in the reference graph. A references B and B references A. The garbage collector will detect cycles and see when there are no external references to A and B, and will then collect both. Attempting to use the finaliser here is wrong. If B is being destroyed, the reference to A is also being removed. --- The statement: "Assume that the A instance will be shared with some other objects as well and will outlive the B instance." is wrong. The only way that will happen is if the listener is explicitly removed from somewhere other than a finalizer. If references to A are passed around, that will imply a reference to B, and B will not be garbage collected because there are external references to the A-B cycle. --- Further update: If you want to break the cycle and not require B to explicitly remove the listener, you can use a WeakReference. Something like this: ``` class A { void addListener(Listener obj); void removeListener(Listener obj); } class B { private static class InnerListener implements Listener { private WeakReference m_owner; private WeakReference m_source; InnerListener(B owner, A source) { m_owner = new WeakReference(owner); m_source = new WeakReference(source); } void listen() { // Handling reentrancy on this function left as an excercise. B b = (B)m_owner.get(); if (b == null) { if (m_source != null) { A a = (A) m_source.get(); if (a != null) { a.removeListener(this); m_source = null; } } return; } ... } } private A a; B() { a = new A(); a.addListener(new InnerListener(this, a)); } } ``` Could be further generalised if needed across multiple classes.
Do Java listeners need to be removed? (In general)
[ "", "java", "" ]
I am working on a large C++ project in Visual Studio 2008, and there are a lot of files with unnecessary `#include` directives. Sometimes the `#include`s are just artifacts and everything will compile fine with them removed, and in other cases classes could be forward declared and the #include could be moved to the `.cpp` file. Are there any good tools for detecting both of these cases?
While it won't reveal unneeded include files, Visual studio has a setting `/showIncludes` (right click on a `.cpp` file, `Properties->C/C++->Advanced`) that will output a tree of all included files at compile time. This can help in identifying files that shouldn't need to be included. You can also take a look at the pimpl idiom to let you get away with fewer header file dependencies to make it easier to see the cruft that you can remove.
[PC Lint](http://www.gimpel.com/html/pcl.htm "PC Lint") works quite well for this, and it finds all sorts of other goofy problems for you too. It has command line options that can be used to create External Tools in Visual Studio, but I've found that the [Visual Lint](http://www.riverblade.co.uk/products/visual_lint/index.html "Visual Lint") addin is easier to work with. Even the free version of Visual Lint helps. But give PC-Lint a shot. Configuring it so it doesn't give you too many warnings takes a bit of time, but you'll be amazed at what it turns up.
How should I detect unnecessary #include files in a large C++ project?
[ "", "c++", "visual-studio-2008", "include", "header", "dependencies", "" ]
I know how to test an object to see if it is of a type, using the IS keyword e.g. ``` if (foo is bar) { //do something here } ``` but how do you test for it not being "bar"?, I can't seem to find a keyword that works with IS to test for a negative result. BTW - I have a horrible feeling this is soooo obvious, so apologies in advance...
``` if (!(foo is bar)) { } ```
You can also use the [as operator](http://msdn.microsoft.com/en-us/library/cscsdfbt(VS.71).aspx). > The as operator is used to perform > conversions between compatible types. ``` bar aBar = foo as bar; // aBar is null if foo is not bar ```
Test an object for NOT being a type
[ "", "c#", "syntax", "object", "testing", "" ]
I am writing a simple Python web application that consists of several pages of business data formatted for the iPhone. I'm comfortable programming Python, but I'm not very familiar with Python "idiom," especially regarding classes and objects. Python's object oriented design differs somewhat from other languages I've worked with. So, even though my application is working, I'm curious whether there is a better way to accomplish my goals. Specifics: How does one typically implement the request-transform-render database workflow in Python? Currently, I am using pyodbc to fetch data, copying the results into attributes on an object, performing some calculations and merges using a list of these objects, then rendering the output from the list of objects. (Sample code below, SQL queries redacted.) Is this sane? Is there a better way? Are there any specific "gotchas" I've stumbled into in my relative ignorance of Python? I'm particularly concerned about how I've implemented the list of rows using the empty "Record" class. ``` class Record(object): pass def calculate_pnl(records, node_prices): for record in records: try: # fill RT and DA prices from the hash retrieved above if hasattr(record, 'sink') and record.sink: record.da = node_prices[record.sink][0] - node_prices[record.id][0] record.rt = node_prices[record.sink][1] - node_prices[record.id][1] else: record.da = node_prices[record.id][0] record.rt = node_prices[record.id][1] # calculate dependent values: RT-DA and PNL record.rtda = record.rt - record.da record.pnl = record.rtda * record.mw except: print sys.exc_info() def map_rows(cursor, mappings, callback=None): records = [] for row in cursor: record = Record() for field, attr in mappings.iteritems(): setattr(record, attr, getattr(row, field, None)) if not callback or callback(record): records.append(record) return records def get_positions(cursor): # get the latest position time cursor.execute("SELECT latest data time") time = cursor.fetchone().time hour = eelib.util.get_hour_ending(time) # fetch the current positions cursor.execute("SELECT stuff FROM atable", (hour)) # read the rows nodes = {} def record_callback(record): if abs(record.mw) > 0: if record.id: nodes[record.id] = None return True else: return False records = util.map_rows(cursor, { 'id': 'id', 'name': 'name', 'mw': 'mw' }, record_callback) # query prices for node_id in nodes: # RT price row = cursor.execute("SELECT price WHERE ? ? ?", (node_id, time, time)).fetchone() rt5 = row.lmp if row else None # DA price row = cursor.execute("SELECT price WHERE ? ? ?", (node_id, hour, hour)).fetchone() da = row.da_lmp if row else None # update the hash value nodes[node_id] = (da, rt5) # calculate the position pricing calculate_pnl(records, nodes) # sort records.sort(key=lambda r: r.name) # return the records return records ```
The empty Record class and the free-floating function that (generally) applies to an individual Record is a hint that you haven't designed your class properly. ``` class Record( object ): """Assuming rtda and pnl must exist.""" def __init__( self ): self.da= 0 self.rt= 0 self.rtda= 0 # or whatever self.pnl= None # self.sink = None # Not clear what this is def setPnl( self, node_prices ): # fill RT and DA prices from the hash retrieved above # calculate dependent values: RT-DA and PNL ``` Now, your `calculate_pnl( records, node_prices )` is simpler and uses the object properly. ``` def calculate_pnl( records, node_prices ): for record in records: record.setPnl( node_prices ) ``` The point isn't to trivially refactor the code in small ways. The point is this: **A Class Encapsulates Responsibility**. Yes, an empty-looking class *is* usually a problem. It means the responsibilities are scattered somewhere else. A similar analysis holds for the collection of records. This is more than a simple list, since the collection -- as a whole -- has operations it performs. The "Request-Transform-Render" isn't quite right. You have a Model (the Record class). Instances of the Model get built (possibly because of a Request.) The Model objects are responsible for their own state transformations and updates. Perhaps they get displayed (or rendered) by some object that examines their state. It's that "Transform" step that often violates good design by scattering responsibility all over the place. "Transform" is a hold-over from non-object design, where responsibility was a nebulous concept.
Have you considered using an ORM? [SQLAlchemy](http://www.sqlalchemy.org/features.html "SQL Alchemy features") is pretty good, and [Elixir](http://elixir.ematia.de/trac/wiki "Elixir Wiki") makes it beautiful. It can really reduce the ammount of boilerplate code needed to deal with databases. Also, a lot of the *gotchas* mentioned have already shown up and the SQLAlchemy developers dealt with them.
Best practices for manipulating database result sets in Python?
[ "", "python", "database", "" ]
I'm trying to implement some drag and drop functionality for a material system being developed at my work. Part of this system includes a 'Material Library' which acts as a repository, divided into groups, of saved materials on the user's hard drive. As part of some UI polish, I was hoping to implement a 'highlight' type feature. When dragging and dropping, windows that you can legally drop a material onto will very subtly change color to improve feedback to the user that this is a valid action. I am changing the bar with 'Basic Materials' (Just a CWnd with a CStatic) from having a medium gray background when unhighlighed to a blue background when hovered over. It all works well, the OnDragEnter and OnDragExit messages seem robust and set a flag indicating the highlight status. Then in OnCtrlColor I do this: ``` if (!m_bHighlighted) { pDC->FillSolidRect(0, 0, m_SizeX, kGroupHeaderHeight, kBackgroundColour); } else { pDC->FillSolidRect(0, 0, m_SizeX, kGroupHeaderHeight, kHighlightedBackgroundColour); } ``` However, as you can see in the screenshot, the painting 'glitches' below the dragged object, leaving the original gray in place. It looks really ugly and basically spoils the whole effect. Is there any way I can get around this?
Thanks for the answers guys, ajryan, you seem to always come up with help for my questions so extra thanks. Thankfully this time the answer was fairly straightforward.... ``` ImageList_DragShowNolock(FALSE); m_pDragDropTargetWnd->SendMessage(WM_USER_DRAG_DROP_OBJECT_DRAG_ENTER, (WPARAM)pDragDropObject, (LPARAM)(&dragDropPoint)); ImageList_DragShowNolock(TRUE); ``` This turns off the drawing of the dragged image, then sends a message to the window being entered to repaint in a highlighted state, then finally redraws the drag image over the top. Seems to have done the trick.
Remote debugging is a godsend for debugging visual issues. It's a pain to set up, but having a VM ready for remote debugging will pay off for sure. What I like to do is set a ton of breakpoints in my paint handling, as well as in the framework paint code itself. This allows you to effectively "freeze frame" the painting without borking it up by flipping into devenv. This way you can get the true picture of who's painting in what order, and where you've got the chance to break in a fill that rect the way you need to.
How to fix an MFC Painting Glitch?
[ "", "c++", "mfc", "paint", "" ]
What is the difference between **`const`** and **`readonly`** in C#? When would you use one over the other?
Apart from the apparent difference of * having to declare the value at the time of a definition for a `const` VS `readonly` values can be computed dynamically but need to be assigned before the constructor exits. After that it is frozen. * `const`'s are implicitly `static`. You use a `ClassName.ConstantName` notation to access them. There is a subtle difference. Consider a class defined in `AssemblyA`. ``` public class Const_V_Readonly { public const int I_CONST_VALUE = 2; public readonly int I_RO_VALUE; public Const_V_Readonly() { I_RO_VALUE = 3; } } ``` `AssemblyB` references `AssemblyA` and uses these values in code. When this is compiled: * in the case of the `const` value, it is like a find-replace. The value 2 is 'baked into' the `AssemblyB`'s IL. This means that if tomorrow I update `I_CONST_VALUE` to 20, *`AssemblyB` would still have 2 till I recompile it*. * in the case of the `readonly` value, it is like a `ref` to a memory location. The value is not baked into `AssemblyB`'s IL. This means that if the memory location is updated, `AssemblyB` gets the new value without recompilation. So if `I_RO_VALUE` is updated to 30, you only need to build `AssemblyA` and all clients do not need to be recompiled. So if you are confident that the value of the constant won't change, use a `const`. ``` public const int CM_IN_A_METER = 100; ``` But if you have a constant that may change (e.g. w.r.t. precision) or when in doubt, use a `readonly`. ``` public readonly float PI = 3.14; ``` *Update: Aku needs to get a mention because he pointed this out first. Also I need to plug where I learned this: [Effective C# - Bill Wagner](https://rads.stackoverflow.com/amzn/click/com/0321245660)*
There is a gotcha with consts! If you reference a constant from another assembly, its value will be compiled right into the calling assembly. That way when you update the constant in the referenced assembly it won't change in the calling assembly!
What is the difference between const and readonly in C#?
[ "", "c#", ".net", "constants", "readonly", "" ]
How do you return 1 value per row of the max of several columns: **TableName** ``` [Number, Date1, Date2, Date3, Cost] ``` I need to return something like this: ``` [Number, Most_Recent_Date, Cost] ``` Query?
This is an old answer and broken in many way. See <https://stackoverflow.com/a/6871572/194653> which has way more upvotes and works with sql server 2008+ and handles nulls, etc. **Original but problematic answer**: Well, you can use the CASE statement: ``` SELECT CASE WHEN Date1 >= Date2 AND Date1 >= Date3 THEN Date1 WHEN Date2 >= Date1 AND Date2 >= Date3 THEN Date2 WHEN Date3 >= Date1 AND Date3 >= Date2 THEN Date3 ELSE Date1 END AS MostRecentDate ```
Here is another nice solution for the `Max` functionality using T-SQL and SQL Server ``` SELECT [Other Fields], (SELECT Max(v) FROM (VALUES (date1), (date2), (date3),...) AS value(v)) as [MaxDate] FROM [YourTableName] ``` Values is the [Table Value Constructor](https://learn.microsoft.com/en-us/sql/t-sql/queries/table-value-constructor-transact-sql?view=sql-server-ver15). "Specifies a set of row value expressions to be constructed into a table. The Transact-SQL table value constructor allows multiple rows of data to be specified in a single DML statement. The table value constructor can be specified either as the VALUES clause of an INSERT ... VALUES statement, or as a derived table in either the USING clause of the MERGE statement or the FROM clause."
SQL MAX of multiple columns?
[ "", "sql", "sql-server", "t-sql", "" ]
We try to use Java and UTF-8 on Windows. The application writes logs on the console, and we would like to use UTF-8 for the logs as our application has internationalized logs. It is possible to configure the JVM so it generates UTF-8, using `-Dfile.encoding=UTF-8` as arguments to the JVM. It works fine, but the output on a Windows console is garbled. Then, we can set the code page of the console to 65001 (`chcp 65001`), but in this case, the `.bat` files do not work. This means that when we try to launch our application through our script (named start.bat), absolutely nothing happens. The command simple returns: ``` C:\Application> chcp 65001 Activated code page: 65001 C:\Application> start.bat C:\Application> ``` But without `chcp 65001`, there is no problem, and the application can be launched. Any hints about that?
Try `chcp 65001 && start.bat` The `chcp` command changes the code page, and 65001 is the Win32 code page identifier for UTF-8 under Windows 7 and up. A code page, or character encoding, specifies how to convert a Unicode code point to a sequence of bytes or back again.
Java on windows does NOT support unicode ouput by default. I have written a workaround method by calling Native API with JNA library.The method will call WriteConsoleW for unicode output on the console. ``` import com.sun.jna.Native; import com.sun.jna.Pointer; import com.sun.jna.ptr.IntByReference; import com.sun.jna.win32.StdCallLibrary; /** For unicode output on windows platform * @author Sandy_Yin * */ public class Console { private static Kernel32 INSTANCE = null; public interface Kernel32 extends StdCallLibrary { public Pointer GetStdHandle(int nStdHandle); public boolean WriteConsoleW(Pointer hConsoleOutput, char[] lpBuffer, int nNumberOfCharsToWrite, IntByReference lpNumberOfCharsWritten, Pointer lpReserved); } static { String os = System.getProperty("os.name").toLowerCase(); if (os.startsWith("win")) { INSTANCE = (Kernel32) Native .loadLibrary("kernel32", Kernel32.class); } } public static void println(String message) { boolean successful = false; if (INSTANCE != null) { Pointer handle = INSTANCE.GetStdHandle(-11); char[] buffer = message.toCharArray(); IntByReference lpNumberOfCharsWritten = new IntByReference(); successful = INSTANCE.WriteConsoleW(handle, buffer, buffer.length, lpNumberOfCharsWritten, null); if(successful){ System.out.println(); } } if (!successful) { System.out.println(message); } } } ```
Java, UTF-8, and Windows console
[ "", "java", "windows", "utf-8", "console", "" ]
I've started to "play around" with PowerShell and am trying to get it to "behave". One of the things I'd like to do is to customize the PROMPT to be "similar" to what "$M$P$\_$+$G" do on MS-Dos: A quick rundown of what these do: **Character****| Description** **$m** The remote name associated with the current drive letter or the empty string if current drive is not a network drive. **$p** Current drive and path **$\_** ENTER-LINEFEED **$+** Zero or more plus sign (+) characters depending upon the depth of the **pushd** directory stack, one character for each level pushed **$g** > (greater-than sign) So the final output is something like: ``` \\spma1fp1\JARAVJ$ H:\temp ++> ``` I've been able to add the `$M` and `$_` functionality (and a nifty History feature) to my prompt as follows: ``` function prompt { ## Get the history. Since the history may be either empty, ## a single item or an array, the @() syntax ensures ## that PowerShell treats it as an array $history = @(get-history) ## If there are any items in the history, find out the ## Id of the final one. ## PowerShell defaults the $lastId variable to '0' if this ## code doesn't execute. if($history.Count -gt 0) { $lastItem = $history[$history.Count - 1] $lastId = $lastItem.Id } ## The command that we're currently entering on the prompt ## will be next in the history. Because of that, we'll ## take the last history Id and add one to it. $nextCommand = $lastId + 1 ## Get the current location $currentDirectory = get-location ## Set the Windows Title to the current location $host.ui.RawUI.WindowTitle = "PS: " + $currentDirectory ## And create a prompt that shows the command number, ## and current location "PS:$nextCommand $currentDirectory >" } ``` But the rest is not yet something I've managed to duplicate.... Thanks a lot for the tips that will surely come!
See if this does what you want: ``` function prompt { ## Get the history. Since the history may be either empty, ## a single item or an array, the @() syntax ensures ## that PowerShell treats it as an array $history = @(get-history) ## If there are any items in the history, find out the ## Id of the final one. ## PowerShell defaults the $lastId variable to '0' if this ## code doesn't execute. if($history.Count -gt 0) { $lastItem = $history[$history.Count - 1] $lastId = $lastItem.Id } ## The command that we're currently entering on the prompt ## will be next in the history. Because of that, we'll ## take the last history Id and add one to it. $nextCommand = $lastId + 1 ## Get the current location $currentDirectory = get-location ## Set the Windows Title to the current location $host.ui.RawUI.WindowTitle = "PS: " + $currentDirectory ##pushd info $pushdCount = $(get-location -stack).count $pushPrompt = "" for ($i=0; $i -lt $pushdCount; $i++) { $pushPrompt += "+" } ## And create a prompt that shows the command number, ## and current location "PS:$nextCommand $currentDirectory `n$($pushPrompt)>" } ```
This will get you the count of the locations on the pushd stack: ``` $(get-location -Stack).count ```
Customizing PowerShell Prompt - Equivalent to CMD's $M$P$_$+$G?
[ "", "c#", "powershell", "command", "prompt", "customization", "" ]
I need to convert a value which is in a `DateTime` variable into a `varchar` variable formatted as `yyyy-mm-dd` format (without time part). How do I do that?
With Microsoft Sql Server: ``` -- -- Create test case -- DECLARE @myDateTime DATETIME SET @myDateTime = '2008-05-03' -- -- Convert string -- SELECT LEFT(CONVERT(VARCHAR, @myDateTime, 120), 10) ```
Here's some test sql for all the styles. ``` DECLARE @now datetime SET @now = GETDATE() select convert(nvarchar(MAX), @now, 0) as output, 0 as style union select convert(nvarchar(MAX), @now, 1), 1 union select convert(nvarchar(MAX), @now, 2), 2 union select convert(nvarchar(MAX), @now, 3), 3 union select convert(nvarchar(MAX), @now, 4), 4 union select convert(nvarchar(MAX), @now, 5), 5 union select convert(nvarchar(MAX), @now, 6), 6 union select convert(nvarchar(MAX), @now, 7), 7 union select convert(nvarchar(MAX), @now, 8), 8 union select convert(nvarchar(MAX), @now, 9), 9 union select convert(nvarchar(MAX), @now, 10), 10 union select convert(nvarchar(MAX), @now, 11), 11 union select convert(nvarchar(MAX), @now, 12), 12 union select convert(nvarchar(MAX), @now, 13), 13 union select convert(nvarchar(MAX), @now, 14), 14 --15 to 19 not valid union select convert(nvarchar(MAX), @now, 20), 20 union select convert(nvarchar(MAX), @now, 21), 21 union select convert(nvarchar(MAX), @now, 22), 22 union select convert(nvarchar(MAX), @now, 23), 23 union select convert(nvarchar(MAX), @now, 24), 24 union select convert(nvarchar(MAX), @now, 25), 25 --26 to 99 not valid union select convert(nvarchar(MAX), @now, 100), 100 union select convert(nvarchar(MAX), @now, 101), 101 union select convert(nvarchar(MAX), @now, 102), 102 union select convert(nvarchar(MAX), @now, 103), 103 union select convert(nvarchar(MAX), @now, 104), 104 union select convert(nvarchar(MAX), @now, 105), 105 union select convert(nvarchar(MAX), @now, 106), 106 union select convert(nvarchar(MAX), @now, 107), 107 union select convert(nvarchar(MAX), @now, 108), 108 union select convert(nvarchar(MAX), @now, 109), 109 union select convert(nvarchar(MAX), @now, 110), 110 union select convert(nvarchar(MAX), @now, 111), 111 union select convert(nvarchar(MAX), @now, 112), 112 union select convert(nvarchar(MAX), @now, 113), 113 union select convert(nvarchar(MAX), @now, 114), 114 union select convert(nvarchar(MAX), @now, 120), 120 union select convert(nvarchar(MAX), @now, 121), 121 --122 to 125 not valid union select convert(nvarchar(MAX), @now, 126), 126 union select convert(nvarchar(MAX), @now, 127), 127 --128, 129 not valid union select convert(nvarchar(MAX), @now, 130), 130 union select convert(nvarchar(MAX), @now, 131), 131 --132 not valid order BY style ``` Here's the result ``` output style Apr 28 2014 9:31AM 0 04/28/14 1 14.04.28 2 28/04/14 3 28.04.14 4 28-04-14 5 28 Apr 14 6 Apr 28, 14 7 09:31:28 8 Apr 28 2014 9:31:28:580AM 9 04-28-14 10 14/04/28 11 140428 12 28 Apr 2014 09:31:28:580 13 09:31:28:580 14 2014-04-28 09:31:28 20 2014-04-28 09:31:28.580 21 04/28/14 9:31:28 AM 22 2014-04-28 23 09:31:28 24 2014-04-28 09:31:28.580 25 Apr 28 2014 9:31AM 100 04/28/2014 101 2014.04.28 102 28/04/2014 103 28.04.2014 104 28-04-2014 105 28 Apr 2014 106 Apr 28, 2014 107 09:31:28 108 Apr 28 2014 9:31:28:580AM 109 04-28-2014 110 2014/04/28 111 20140428 112 28 Apr 2014 09:31:28:580 113 09:31:28:580 114 2014-04-28 09:31:28 120 2014-04-28 09:31:28.580 121 2014-04-28T09:31:28.580 126 2014-04-28T09:31:28.580 127 28 جمادى الثانية 1435 9:31:28:580AM 130 28/06/1435 9:31:28:580AM 131 ``` Make `nvarchar(max)` shorter to trim the time. For example: ``` select convert(nvarchar(11), GETDATE(), 0) union select convert(nvarchar(max), GETDATE(), 0) ``` outputs: ``` May 18 2018 May 18 2018 9:57AM ```
How to convert DateTime to VarChar
[ "", "sql", "sql-server", "datetime", "sql-convert", "" ]
I was able to implement a thread-safe Dictionary in C# by deriving from IDictionary and defining a private SyncRoot object: ``` public class SafeDictionary<TKey, TValue>: IDictionary<TKey, TValue> { private readonly object syncRoot = new object(); private Dictionary<TKey, TValue> d = new Dictionary<TKey, TValue>(); public object SyncRoot { get { return syncRoot; } } public void Add(TKey key, TValue value) { lock (syncRoot) { d.Add(key, value); } } // more IDictionary members... } ``` I then lock on this SyncRoot object throughout my consumers (multiple threads): Example: ``` lock (m_MySharedDictionary.SyncRoot) { m_MySharedDictionary.Add(...); } ``` I was able to make it work, but this resulted in some ugly code. My question is, is there a better, more elegant way of implementing a thread-safe Dictionary?
As Peter said, you can encapsulate all of the thread safety inside the class. You will need to be careful with any events you expose or add, making sure that they get invoked outside of any locks. ``` public class SafeDictionary<TKey, TValue>: IDictionary<TKey, TValue> { private readonly object syncRoot = new object(); private Dictionary<TKey, TValue> d = new Dictionary<TKey, TValue>(); public void Add(TKey key, TValue value) { lock (syncRoot) { d.Add(key, value); } OnItemAdded(EventArgs.Empty); } public event EventHandler ItemAdded; protected virtual void OnItemAdded(EventArgs e) { EventHandler handler = ItemAdded; if (handler != null) handler(this, e); } // more IDictionary members... } ``` **Edit:** The MSDN docs point out that enumerating is inherently not thread safe. That can be one reason for exposing a synchronization object outside your class. Another way to approach that would be to provide some methods for performing an action on all members and lock around the enumerating of the members. The problem with this is that you don't know if the action passed to that function calls some member of your dictionary (that would result in a deadlock). Exposing the synchronization object allows the consumer to make those decisions and doesn't hide the deadlock inside your class.
The .NET 4.0 class that supports concurrency is named [`ConcurrentDictionary`](http://msdn.microsoft.com/en-us/library/dd287191.aspx).
What's the best way of implementing a thread-safe Dictionary?
[ "", "c#", ".net", "thread-safety", "collections", "" ]
I have got a python script which is creating an ODBC connection. The ODBC connection is generated with a connection string. In this connection string I have to include the username and password for this connection. Is there an easy way to obscure this password in the file (just that nobody can read the password when I'm editing the file) ?
[Base64 encoding](https://docs.python.org/3/library/base64.html) is in the standard library and will do to stop shoulder surfers: ``` >>> import base64 >>> print(base64.b64encode("password".encode("utf-8"))) cGFzc3dvcmQ= >>> print(base64.b64decode("cGFzc3dvcmQ=").decode("utf-8")) password ```
Here is a simple method: 1. Create a python module - let's call it peekaboo.py. 2. In peekaboo.py, include both the password and any code needing that password 3. Create a compiled version - peekaboo.pyc - by importing this module (via python commandline, etc...). 4. Now, delete peekaboo.py. 5. You can now happily import peekaboo relying only on peekaboo.pyc. Since peekaboo.pyc is byte compiled it is not readable to the casual user. This should be a bit more secure than base64 decoding - although it is vulnerable to a py\_to\_pyc decompiler.
Hiding a password in a python script (insecure obfuscation only)
[ "", "python", "security", "" ]
``` Element[] array = {new Element(1), new Element(2), new Element(3)}; ``` How do I convert the above variable of type `Element[]` into a variable of type [`ArrayList<Element>`](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/ArrayList.html)? ``` ArrayList<Element> arrayList = ...; ```
You can use the following instruction: ``` new ArrayList<>(Arrays.asList(array)); ```
Given: ``` Element[] array = new Element[] { new Element(1), new Element(2), new Element(3) }; ``` The simplest answer is to do: ``` List<Element> list = Arrays.asList(array); ``` This will work fine. But some caveats: 1. The list returned from asList has **fixed size**. So, if you want to be able to add or remove elements from the returned list in your code, you'll need to wrap it in a new `ArrayList`. Otherwise you'll get an `UnsupportedOperationException`. 2. The list returned from `asList()` is backed by the original array. If you modify the original array, the list will be modified as well. This may be surprising.
Create ArrayList from array
[ "", "java", "arrays", "arraylist", "type-conversion", "" ]
Hi i want to write a game with a main game form and lot of other normal forms. What is the best way to manage update-paint cycle in that case? Should the game form paint loop only should be overriden? or should i do an application.do events() in the main method? Please guide me regarding this. i am new to windows forms world
Your logic thread should be separate from the form, so you won't need DoEvents(). If you're using GDI+, then you should force an Update() on a loop. Windows Forms doesn't do double buffering very well, so depending on how sophisticated your graphics will be you might have some difficulties with flicker. My suggestion is to look at using the [DirectX managed library](http://msdn.microsoft.com/en-us/library/bb318659(VS.85).aspx). It's a lot to learn, but gives you everything you need. **EDIT:** I have been reading recently about WPF, which seems like a much better platform for simple to moderately complex games, because it provides a much higher level API than the [DirectX managed Library](http://msdn.microsoft.com/en-us/library/bb318659(VS.85).aspx). It probably has performance and flexibility limitations for more complex games, however.
The body of the question doesn't mention Compact Framework, just Winforms. This is pretty much the accepted answer for Winforms from Tom Miller (Xna Game Studio and Managed DirectX guy from Microsoft): [Winforms Game Loop](http://blogs.msdn.com/tmiller/archive/2005/05/05/415008.aspx) @Rich B: The game loop is independent of how the rendering is done (DirectX, MDX, GDI+)
Game Loop and GDI over .NET CF
[ "", "c#", "game-loop", "" ]
I am trying to use the `import random` statement in python, but it doesn't appear to have any methods in it to use. Am I missing something?
You probably have a file named random.py or random.pyc in your working directory. That's shadowing the built-in random module. You need to rename random.py to something like my\_random.py and/or remove the random.pyc file. To tell for sure what's going on, do this: ``` >>> import random >>> print random.__file__ ``` That will show you exactly which file is being imported.
This is happening because you have a random.py file in the python search path, most likely the current directory. Python is searching for modules using sys.path, which normally includes the current directory before the standard site-packages, which contains the expected random.py. This is expected to be fixed in Python 3.0, so that you can't import modules from the current directory without using a special import syntax. Just remove the random.py + random.pyc in the directory you're running python from and it'll work fine.
Random in python 2.5 not working?
[ "", "python", "" ]
Windows file system is case insensitive. How, given a file/folder name (e.g. "somefile"), I get the *actual* name of that file/folder (e.g. it should return "SomeFile" if Explorer displays it so)? Some ways I know, all of which seem quite backwards: 1. Given the full path, search for each folder on the path (via FindFirstFile). This gives proper cased results of each folder. At the last step, search for the file itself. 2. Get filename from handle (as in [MSDN example](http://msdn.microsoft.com/en-us/library/aa366789(VS.85).aspx)). This requires opening a file, creating file mapping, getting it's name, parsing device names etc. Pretty convoluted. And it does not work for folders or zero-size files. Am I missing some obvious WinAPI call? The simplest ones, like GetActualPathName() or GetFullPathName() return the name using casing that was passed in (e.g. returns "program files" if that was passed in, even if it should be "Program Files"). I'm looking for a native solution (not .NET one).
And hereby I answer my own question, based on [original answer from *cspirz*](https://stackoverflow.com/questions/74451/getting-actual-file-name-with-proper-casing-on-windows#74588). Here's a function that given absolute, relative or network path, will return the path with upper/lower case as it would be displayed on Windows. If some component of the path does not exist, it will return the passed in path from that point. It is quite involved because it tries to handle network paths and other edge cases. It operates on wide character strings and uses std::wstring. Yes, in theory Unicode TCHAR could be not the same as wchar\_t; that is an exercise for the reader :) ``` std::wstring GetActualPathName( const wchar_t* path ) { // This is quite involved, but the meat is SHGetFileInfo const wchar_t kSeparator = L'\\'; // copy input string because we'll be temporary modifying it in place size_t length = wcslen(path); wchar_t buffer[MAX_PATH]; memcpy( buffer, path, (length+1) * sizeof(path[0]) ); size_t i = 0; std::wstring result; // for network paths (\\server\share\RestOfPath), getting the display // name mangles it into unusable form (e.g. "\\server\share" turns // into "share on server (server)"). So detect this case and just skip // up to two path components if( length >= 2 && buffer[0] == kSeparator && buffer[1] == kSeparator ) { int skippedCount = 0; i = 2; // start after '\\' while( i < length && skippedCount < 2 ) { if( buffer[i] == kSeparator ) ++skippedCount; ++i; } result.append( buffer, i ); } // for drive names, just add it uppercased else if( length >= 2 && buffer[1] == L':' ) { result += towupper(buffer[0]); result += L':'; if( length >= 3 && buffer[2] == kSeparator ) { result += kSeparator; i = 3; // start after drive, colon and separator } else { i = 2; // start after drive and colon } } size_t lastComponentStart = i; bool addSeparator = false; while( i < length ) { // skip until path separator while( i < length && buffer[i] != kSeparator ) ++i; if( addSeparator ) result += kSeparator; // if we found path separator, get real filename of this // last path name component bool foundSeparator = (i < length); buffer[i] = 0; SHFILEINFOW info; // nuke the path separator so that we get real name of current path component info.szDisplayName[0] = 0; if( SHGetFileInfoW( buffer, 0, &info, sizeof(info), SHGFI_DISPLAYNAME ) ) { result += info.szDisplayName; } else { // most likely file does not exist. // So just append original path name component. result.append( buffer + lastComponentStart, i - lastComponentStart ); } // restore path separator that we might have nuked before if( foundSeparator ) buffer[i] = kSeparator; ++i; lastComponentStart = i; addSeparator = true; } return result; } ``` Again, thanks to cspirz for pointing me to SHGetFileInfo.
Have you tried using [SHGetFileInfo?](http://msdn.microsoft.com/en-us/library/bb762179(VS.85).aspx)
Getting actual file name (with proper casing) on Windows
[ "", "c++", "c", "windows", "winapi", "" ]
Is there a way to use constants in **JavaScript**? If not, what's the common practice for specifying variables that are used as constants?
Since [ES2015](https://www.ecma-international.org/ecma-262/6.0/), JavaScript has a notion of [`const`](https://www.ecma-international.org/ecma-262/6.0/#sec-let-and-const-declarations): ``` const MY_CONSTANT = "some-value"; ``` This will work in [pretty much all browsers except IE 8, 9 and 10](https://caniuse.com/#search=const). Some may also need [strict mode](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Strict_mode) enabled. You can use `var` with conventions like ALL\_CAPS to show that certain values should not be modified if you need to support older browsers or are working with legacy code: ``` var MY_CONSTANT = "some-value"; ```
Are you trying to protect the variables against modification? If so, then you can use a module pattern: ``` var CONFIG = (function() { var private = { 'MY_CONST': '1', 'ANOTHER_CONST': '2' }; return { get: function(name) { return private[name]; } }; })(); alert('MY_CONST: ' + CONFIG.get('MY_CONST')); // 1 CONFIG.MY_CONST = '2'; alert('MY_CONST: ' + CONFIG.get('MY_CONST')); // 1 CONFIG.private.MY_CONST = '2'; // error alert('MY_CONST: ' + CONFIG.get('MY_CONST')); // 1 ``` Using this approach, the values cannot be modified. But, you have to use the get() method on CONFIG :(. If you don't need to strictly protect the variables value, then just do as suggested and use a convention of ALL CAPS.
Are there constants in JavaScript?
[ "", "javascript", "constants", "" ]
I have a function that takes, amongst others, a parameter declared as *int privateCount*. When I want to call ToString() on this param, ReSharper greys it out and marks it as a redundant call. So, curious as I am, I remove the ToString(), and the code still builds! How can a C# compiler allow this, where *str* is a string? `str += privateCount +` ...
The + operator for string is overloaded to call String.Concat passing in the left and right side of the expression. Thus: ``` string x = "123" + 45; ``` Gets compiled to: ``` String.Concat("123", 45); ``` Since String.Concat takes in two objects, the right hand side (45) is boxed and then ToString() is called on it. Note that this "overloading" is not via operator overloading in the language (aka it's not a method named op\_Addition) but is handled by the compiler.
It is not only bad practice, but also less performant: The integer has to be boxed because String.Concat expectes an object while int.ToString() does not require boxing.
Redundant Call to Object.ToString()
[ "", "c#", ".net", "resharper", "" ]
I'm trying to find a way to "pretty print" a JavaScript data structure in a human-readable form for debugging. I have a rather big and complicated data structure being stored in JS and I need to write some code to manipulate it. In order to work out what I'm doing and where I'm going wrong, what I really need is to be able to see the data structure in its entirety, and update it whenever I make changes through the UI. All of this stuff I can handle myself, apart from finding a nice way to dump a JavaScript data structure to a human-readable string. JSON would do, but it really needs to be nicely formatted and indented. I'd usually use Firebug's excellent DOM dumping stuff for this, but I really need to be able to see the entire structure at once, which doesn't seem to be possible in Firebug.
I wrote a function to dump a JS object in a readable form, although the output isn't indented, but it shouldn't be too hard to add that: I made this function from one I made for Lua (which is much more complex) which handled this indentation issue. Here is the "simple" version: ``` function DumpObject(obj) { var od = new Object; var result = ""; var len = 0; for (var property in obj) { var value = obj[property]; if (typeof value == 'string') value = "'" + value + "'"; else if (typeof value == 'object') { if (value instanceof Array) { value = "[ " + value + " ]"; } else { var ood = DumpObject(value); value = "{ " + ood.dump + " }"; } } result += "'" + property + "' : " + value + ", "; len++; } od.dump = result.replace(/, $/, ""); od.len = len; return od; } ``` I will look at improving it a bit. Note 1: To use it, do `od = DumpObject(something)` and use od.dump. Convoluted because I wanted the len value too (number of items) for another purpose. It is trivial to make the function return only the string. Note 2: it doesn't handle loops in references. **EDIT** I made the indented version. ``` function DumpObjectIndented(obj, indent) { var result = ""; if (indent == null) indent = ""; for (var property in obj) { var value = obj[property]; if (typeof value == 'string') value = "'" + value + "'"; else if (typeof value == 'object') { if (value instanceof Array) { // Just let JS convert the Array to a string! value = "[ " + value + " ]"; } else { // Recursive dump // (replace " " by "\t" or something else if you prefer) var od = DumpObjectIndented(value, indent + " "); // If you like { on the same line as the key //value = "{\n" + od + "\n" + indent + "}"; // If you prefer { and } to be aligned value = "\n" + indent + "{\n" + od + "\n" + indent + "}"; } } result += indent + "'" + property + "' : " + value + ",\n"; } return result.replace(/,\n$/, ""); } ``` Choose your indentation on the line with the recursive call, and you brace style by switching the commented line after this one. ... I see you whipped up your own version, which is good. Visitors will have a choice.
Use [**Crockford's JSON.stringify**](https://github.com/douglascrockford/JSON-js/blob/master/json2.js) like this: ``` var myArray = ['e', {pluribus: 'unum'}]; var text = JSON.stringify(myArray, null, '\t'); //you can specify a number instead of '\t' and that many spaces will be used for indentation... ``` Variable `text` would look like this: ``` [ "e", { "pluribus": "unum" } ] ``` --- By the way, this requires nothing more than that JS file - it will work with any library, etc.
JavaScript data formatting/pretty printer
[ "", "javascript", "debugging", "json", "" ]
Implementing Equals() for reference types is harder than it seems. My current canonical implementation goes like this: ``` public bool Equals( MyClass obj ) { // If both refer to the same reference they are equal. if( ReferenceEquals( obj, this ) ) return true; // If the other object is null they are not equal because in C# this cannot be null. if( ReferenceEquals( obj, null ) ) return false; // Compare data to evaluate equality return _data.Equals( obj._data ); } public override bool Equals( object obj ) { // If both refer to the same reference they are equal. if( ReferenceEquals( obj, this ) ) return true; // If the other object is null or is of a different types the objects are not equal. if( ReferenceEquals( obj, null ) || obj.GetType() != GetType() ) return false; // Use type-safe equality comparison return Equals( (MyClass)obj ); } public override int GetHashCode() { // Use data's hash code as our hashcode return _data.GetHashCode(); } ``` I think that this covers all corner (inheritance and such) cases but I may be wrong. What do you guys think?
I wrote a fairly comprehensive guide to this a while back. For a start your equals implementations should be shared (i.e. the overload taking an object should pass through to the one taking a strongly typed object). Additionally you need to consider things such as your object should be immutable because of the need to override GetHashCode. More info here: <http://gregbeech.com/blog/implementing-object-equality-in-dotnet>
Better hope that this.\_data is not null if it's also a reference type. ``` public bool Equals( MyClass obj ) { if (obj == null) { return false; } else { return (this._data != null && this._data.Equals( obj._data )) || obj._data == null; } } public override bool Equals( object obj ) { if (obj == null || !(obj is MyClass)) { return false; } else { return this.Equals( (MyClass)obj ); } } public override int GetHashCode() { return this._data == null ? 0 : this._data.GetHashCode(); } ```
What is the "best" canonical implementation of Equals() for reference types?
[ "", "c#", ".net", "equals", "" ]
I don't want a discussion about when to and not to throw exceptions. I wish to resolve a simple issue. 99% of the time the argument for not throwing exceptions revolves around them being slow while the other side claims (with benchmark test) that the speed is not the issue. I've read numerous blogs, articles, and posts pertaining one side or the other. So which is it? Some links from the answers: [Skeet](http://yoda.arachsys.com/csharp/exceptions2.html), [Mariani](http://blogs.msdn.com/ricom/archive/2006/09/25/771142.aspx), [Brumme](http://blogs.msdn.com/cbrumme/archive/2003/10/01/51524.aspx).
I'm on the "not slow" side - or more precisely "not slow enough to make it worth avoiding them in normal use". I've written two [short](http://pobox.com/%7Eskeet/csharp/exceptions.html) [articles](http://pobox.com/%7Eskeet/csharp/exceptions2.html) about this. There are criticisms of the benchmark aspect, which are mostly down to "in real life there'd be more stack to go through, so you'd blow the cache etc" - but using error codes to work your way up the stack would *also* blow the cache, so I don't see that as a particularly good argument. Just to make it clear - I don't support using exceptions where they're not logical. For instance, `int.TryParse` is entirely appropriate for converting data from a user. It's inappropriate when reading a machine-generated file, where failure means "The file isn't in the format it's meant to be, I really don't want to try to handle this as I don't know what else might be wrong." When using exceptions in "only reasonable circumstances" I've never seen an application whose performance was significantly impaired by exceptions. Basically, exceptions shouldn't happen often unless you've got significant correctness issues, and if you've got significant correctness issues then performance isn't the biggest problem you face.
There is the definitive answer to this from the guy who implemented them - Chris Brumme. He wrote an [excellent blog article](https://devblogs.microsoft.com/cbrumme/the-exception-model/) about the subject (warning - its very long)(warning2 - its very well written, if you're a techie you'll read it to the end and then have to make up your hours after work :) ) The executive summary: they are slow. They are implemented as Win32 SEH exceptions, so some will even pass the ring 0 CPU boundary! Obviously in the real world, you'll be doing a lot of other work so the odd exception will not be noticed at all, but if you use them for program flow expect your app to be hammered. This is another example of the MS marketing machine doing us a disservice. I recall one microsoftie telling us how they incurred absolutely zero overhead, which is complete tosh. Chris gives a pertinent quote: > In fact, the CLR internally uses > exceptions even in the unmanaged > portions of the engine. However, > there is a serious long term > performance problem with exceptions > and this must be factored into your > decision.
How slow are .NET exceptions?
[ "", "c#", ".net", "performance", "exception", "" ]
I've discovered that any time I do the following: ``` echo '<a href="http://" title="bla">huzzah</a>'; ``` I end up with the following being rendered to the browser: ``` <a href="http:///" title="bla">huzzah</a> ``` This is particularly annoying when I link to a file with an extension, as it breaks the link. Any ideas why this is happening and how I can fix it? **Update:** For those asking about my exact implementation, here it is. In my troubleshooting I've dumbed it down as much as I could, so please don't mind where I concat plain text to plaintext... ``` function print_it($item) { echo '<div class="listItem clearfix">'; echo '<div class="info">'; echo '<span class="title">'; if(isset($item[6])) { echo '<a href="http://" title="">' . 'me' . '</a>'; } echo '</span>'; echo '</div></div>'; } ``` **Update:** In response to Matt Long, I pasted in your line and it rendered the same. **Update:** In response to Fire Lancer, I've put back in my original attempt, and will show you both below. ``` echo substr($item[6],13) . '<br>'; echo '<a href="http://' . substr($item[6],13) . '" title="' . $item[0] . '">' . $item[0] . '</a>'; <span class="title">www.edu.gov.on.ca%2Feng%2Ftcu%2Fetlanding.html<br> <a href="http://www.edu.gov.on.ca%2Feng%2Ftcu%2Fetlanding.html" title="Employment Ontario">Employment Ontario</a></span> ``` The reason for the substr'ing is due to the URL being run through rawurlencode() elsewhere, and linking to http%3A%2F%2F makes the page think it is a local/relative link. **Update:** I pasted the above response without really looking at it. So the HTML is correct when viewing source, but the actual page interprets it with another trailing slash after it. **Solution:** This was all a result of rawlurlencode(). If I decoded, or skipped the encoding all together, everything worked perfectly. Something about rawurlencode() makes the browser want to stick a trailing slash in there.
Firefox, especially, shows you the html source the way it's seeing it which is rarely the way you've sent it. Clearly something about your link or it's context is making the browser interpret a trailing slash. I wonder if it's a side effect of the url encoding. If you rawurldecode it will that help. If there are parts of the url that need to stay encoded you could search for the slashes and just put those back.
Ive never had that, how ecactly are you echoing the link? All the following should work. ``` echo '<a href="http://someothersite.com">Link</a>'; echo '<a href="anotherpage.php">Some page</a>'; echo '<a href="../pageinparentdir.php">Another page</a>'; etc ``` edit, since you added the info. You can't just have http:// as href, even entering that link directly into a html page has that effect. eg: html: ``` <a href="http://" title="bla">huzzah</a> ``` link (in FF3): ``` http:/// ```
Echo A Link, Get A Trailing Slash?
[ "", "php", "jfilechooser", "" ]
Using the Sun Java VM 1.5 or 1.6 on Windows, I connect a non-blocking socket. I then fill a `ByteBuffer` with a message to output, and attempt to `write()` to the SocketChannel. I expect the write to complete only partially if the amount to be written is greater than the amount of space in the socket's TCP output buffer (this is what I expect intuitively, it's also pretty much my understanding of the [docs](http://java.sun.com/j2se/1.5.0/docs/api/java/nio/channels/SocketChannel.html#write(java.nio.ByteBuffer))), but that's not what happens. The `write()` *always* seems to return reporting the full amount written, even if it's several megabytes (the socket's SO\_SNDBUF is 8KB, much, much less than my multi-megabyte output message). A problem here is that I can't test the code that handles the case where the output is partially written (registering an interest set of `WRITE` to a selector and doing a `select()` to wait until the remainder can be written), as that case never seems to happen. What am I not understanding?
I managed to reproduce a situation that might be similar to yours. I think, ironically enough, your recipient is consuming the data faster than you're writing it. ``` import java.io.InputStream; import java.net.ServerSocket; import java.net.Socket; public class MyServer { public static void main(String[] args) throws Exception { final ServerSocket ss = new ServerSocket(12345); final Socket cs = ss.accept(); System.out.println("Accepted connection"); final InputStream in = cs.getInputStream(); final byte[] tmp = new byte[64 * 1024]; while (in.read(tmp) != -1); Thread.sleep(100000); } } import java.net.InetSocketAddress; import java.nio.ByteBuffer; import java.nio.channels.SocketChannel; public class MyNioClient { public static void main(String[] args) throws Exception { final SocketChannel s = SocketChannel.open(); s.configureBlocking(false); s.connect(new InetSocketAddress("localhost", 12345)); s.finishConnect(); final ByteBuffer buf = ByteBuffer.allocate(128 * 1024); for (int i = 0; i < 10; i++) { System.out.println("to write: " + buf.remaining() + ", written: " + s.write(buf)); buf.position(0); } Thread.sleep(100000); } } ``` If you run the above server and then make the above client attempt to write 10 chunks of 128 kB of data, you'll see that every write operation writes the whole buffer without blocking. However, if you modify the above server not to read anything from the connection, you'll see that only the first write operation on the client will write 128 kB, whereas all subsequent writes will return `0`. Output when the server is reading from the connection: ``` to write: 131072, written: 131072 to write: 131072, written: 131072 to write: 131072, written: 131072 ... ``` Output when the server is not reading from the connection: ``` to write: 131072, written: 131072 to write: 131072, written: 0 to write: 131072, written: 0 ... ```
I've been working with UDP in Java and have seen some really "interesting" and completely undocumented behavior in the Java NIO stuff in general. The best way to determine what is happening is to look at the source which comes with Java. I also would wager rather highly that you might find a better implementation of what you're looking for in any other JVM implementation, such as IBM's, but I can't guarantee that without look at them myself.
Why do SocketChannel writes always complete for the full amount even on non-blocking sockets?
[ "", "java", "sockets", "network-programming", "nio", "" ]
I've got a generic dictionary `Dictionary<string, T>` that I would like to essentially make a Clone() of ..any suggestions.
Okay, the .NET 2.0 answers: If you don't need to clone the values, you can use the constructor overload to Dictionary which takes an existing IDictionary. (You can specify the comparer as the existing dictionary's comparer, too.) If you *do* need to clone the values, you can use something like this: ``` public static Dictionary<TKey, TValue> CloneDictionaryCloningValues<TKey, TValue> (Dictionary<TKey, TValue> original) where TValue : ICloneable { Dictionary<TKey, TValue> ret = new Dictionary<TKey, TValue>(original.Count, original.Comparer); foreach (KeyValuePair<TKey, TValue> entry in original) { ret.Add(entry.Key, (TValue) entry.Value.Clone()); } return ret; } ``` That relies on `TValue.Clone()` being a suitably deep clone as well, of course.
(Note: although the cloning version is potentially useful, for a simple shallow copy the constructor I mention in the other post is a better option.) How deep do you want the copy to be, and what version of .NET are you using? I suspect that a LINQ call to ToDictionary, specifying both the key and element selector, will be the easiest way to go if you're using .NET 3.5. For instance, if you don't mind the value being a shallow clone: ``` var newDictionary = oldDictionary.ToDictionary(entry => entry.Key, entry => entry.Value); ``` If you've already constrained T to implement ICloneable: ``` var newDictionary = oldDictionary.ToDictionary(entry => entry.Key, entry => (T) entry.Value.Clone()); ``` (Those are untested, but should work.)
What is the best way to clone/deep copy a .NET generic Dictionary<string, T>?
[ "", "c#", "generics", "collections", "clone", "" ]
I have the following code: ``` info = new System.Diagnostics.ProcessStartInfo("TheProgram.exe", String.Join(" ", args)); info.CreateNoWindow = true; info.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden; info.RedirectStandardOutput = true; info.UseShellExecute = false; System.Diagnostics.Process p = System.Diagnostics.Process.Start(info); p.WaitForExit(); Console.WriteLine(p.StandardOutput.ReadToEnd()); //need the StandardOutput contents ``` I know that the output from the process I am starting is around 7MB long. Running it in the Windows console works fine. Unfortunately programmatically this hangs indefinitely at `WaitForExit`. Note also this code does NOT hang for smaller outputs (like 3KB). Is it possible that the internal `StandardOutput` in `ProcessStartInfo` can't buffer 7MB? If so, what should I do instead? If not, what am I doing wrong?
The problem is that if you redirect `StandardOutput` and/or `StandardError` the internal buffer can become full. Whatever order you use, there can be a problem: * If you wait for the process to exit before reading `StandardOutput` the process can block trying to write to it, so the process never ends. * If you read from `StandardOutput` using ReadToEnd then *your* process can block if the process never closes `StandardOutput` (for example if it never terminates, or if it is blocked writing to `StandardError`). The solution is to use asynchronous reads to ensure that the buffer doesn't get full. To avoid any deadlocks and collect up all output from both `StandardOutput` and `StandardError` you can do this: EDIT: See answers below for how avoid an **ObjectDisposedException** if the timeout occurs. ``` using (Process process = new Process()) { process.StartInfo.FileName = filename; process.StartInfo.Arguments = arguments; process.StartInfo.UseShellExecute = false; process.StartInfo.RedirectStandardOutput = true; process.StartInfo.RedirectStandardError = true; StringBuilder output = new StringBuilder(); StringBuilder error = new StringBuilder(); using (AutoResetEvent outputWaitHandle = new AutoResetEvent(false)) using (AutoResetEvent errorWaitHandle = new AutoResetEvent(false)) { process.OutputDataReceived += (sender, e) => { if (e.Data == null) { outputWaitHandle.Set(); } else { output.AppendLine(e.Data); } }; process.ErrorDataReceived += (sender, e) => { if (e.Data == null) { errorWaitHandle.Set(); } else { error.AppendLine(e.Data); } }; process.Start(); process.BeginOutputReadLine(); process.BeginErrorReadLine(); if (process.WaitForExit(timeout) && outputWaitHandle.WaitOne(timeout) && errorWaitHandle.WaitOne(timeout)) { // Process completed. Check process.ExitCode here. } else { // Timed out. } } } ```
The [documentation](http://msdn.microsoft.com/en-us/library/system.diagnostics.process.standardoutput.aspx) for `Process.StandardOutput` says to read before you wait otherwise you can deadlock, snippet copied below: ``` // Start the child process. Process p = new Process(); // Redirect the output stream of the child process. p.StartInfo.UseShellExecute = false; p.StartInfo.RedirectStandardOutput = true; p.StartInfo.FileName = "Write500Lines.exe"; p.Start(); // Do not wait for the child process to exit before // reading to the end of its redirected stream. // p.WaitForExit(); // Read the output stream first and then wait. string output = p.StandardOutput.ReadToEnd(); p.WaitForExit(); ```
ProcessStartInfo hanging on "WaitForExit"? Why?
[ "", "c#", "processstartinfo", "" ]