Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
I have a data acquisition program written in C++ (Visual Studio 6.0). Some clients would like to control the software from their own custom software or LabView. I would like to come up with a simple API with a dll I can distribute to them and would like some tips on how to get started. This is going to be VERY basic, maybe 4 or 5 commands. My DAQ program will still be running in its own window on the same machine, I would just like to set it up to be controlled from another program.
You are on the right track with a DLL. The real trick, it sounds like, will be deciding what sort of inter-process communication (IPC) you want to use. Options are: sockets, pipes, shared memory, synchronization objects (events, etc.), files, registry, etc. Once you decide that, then implement a listener within your executable to wait for incoming IPC messages from whatever software is using your DLL. As far as the API is concerned, you can keep it simple just like you were wanting. Have the DLL expose your 4 or 5 functions (make sure you only use native data types, like char\* and long, to avoid module boundary issues), and then those will use your IPC mechanism to communicate with your executing app.
Things that start simple like this have a habit of growing over time, so you may be better off doing a little more work up front and using a technique that will grow with you. Implementing a COM interface to your program would give the clients are lot of freedom in how the interface with it, and you wouldn't have to worry about the mechanics of IPC, etc since COM is designed to hide all that from you. In the future COM already has well define idioms for things like events that are well support by scripting languages, etc should you need them. **Update**: there are a lot of ways of implementing COM. You can build it from the first principals with the guide of a good COM book, or use of framework like ATL to save some of the boiler plate. There are a lot of good samples, for example see [MSDN](http://msdn.microsoft.com/en-us/library/wc9s55de(VS.71).aspx).
How to add a simple API to my C++ application for access by LabView?
[ "", "c++", "windows", "api", "labview", "" ]
Is it possible to have a post-mortem ( or post-exception ) debugging session in Java ? What would the workarounds be ( if there isn't a solution for this already ) ?
You can attach the debugger to a java process and set a breakpoint when a specific exception is received. Is this what you need? From <http://java.sun.com/j2se/1.5.0/docs/tooldocs/solaris/jdb.html> > When an exception occurs for which > there isn't a catch statement anywhere > up a Java program's stack, the Java > runtime normally dumps an exception > trace and exits. When running under > jdb, however, that exception is > treated as a non-recoverable > breakpoint, and jdb stops at the > offending instruction. If that class > was compiled with the -g option, > instance and local variables can be > printed to determine the cause of the > exception. This type of breakpoints can be set with any IDE, such as Eclipse. Using eclipse you can also set a breakpoint on a specific exception type, even if it is caught in the normal code. If you have something like a multi-threaded server running, and one of the threads servicing a client throws an unhandled exception, then you would be able to check the debugger and see what happens. I don't think this is something for production, but definitively helps when testing. The application does not have to run from the debugger, but it can be launched with the debug options as arguments: ``` -Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=XXXX ``` The application runs normally, but switches into "interpreted" mode when a breakpoint is hit, at least in more modern versions of the JVM. So the performance is not affected. Check the section about [full-speed debugging for HotSpot VM](http://java.sun.com/products/hotspot/docs/whitepaper/Java_Hotspot_v1.4.1/Java_HSpot_WP_v1.4.1_1002_1.html) > Full Speed Debugging > > The Java HotSpot VM now uses > full-speed debugging. In previous > version of the VM, when debugging was > enabled, the program executed using > only the interpreter. Now, the full > performance advantage of HotSpot > technology is available to programs, > even with compiled code. The improved > performance allows long-running > programs to be more easily debugged. > It also allows testing to proceed at > full speed. Once there is an > exception, the debugger launches with > full visibility to code sources.
As far as I know, you'd have to wait for Java 7 for an official API - see <http://tech.puredanger.com/java7#jsr326>. In the meantime, you could substitute Exception (replace base class, inject code via instrumentation, etc) to keep your data. Please note though the ClassLoader throws and catches ClassNotFoundException regularly (each new package loaded). You'd have a lot of control that way without having to modify you base code.
Java post-mortem debugging?
[ "", "java", "debugging", "exception", "" ]
I know there are already a few questions regarding recommendations for C++ unit test frameworks, but all the answers did not help as they just recommend one of the frameworks but do not provide any information about a (feature) comparison. I think the most interesting frameworks are CppUnit, Boost and the new Google testing framework. Has anybody done any comparison yet?
[See this question](https://stackoverflow.com/questions/91683/how-do-you-implement-unit-testing-in-large-scale-c-projects) for some discussion. They recommend the articles: [Exploring the C++ Unit Testing Framework Jungle](http://gamesfromwithin.com/?p=29), By Noel Llopis. And the more recent: [C++ Test Unit Frameworks](http://accu.org/index.php/journals/1326) I have not found an article that compares googletest to the other frameworks yet.
A new player is [Google Test](http://code.google.com/p/googletest/) (also known as *Google C++ Testing Framework*) which is pretty nice though. ``` #include <gtest/gtest.h> TEST(MyTestSuitName, MyTestCaseName) { int actual = 1; EXPECT_GT(actual, 0); EXPECT_EQ(1, actual) << "Should be equal to one"; } ``` Main features: * **Portable** * Fatal and **non-fatal assertions** * Easy assertions informative **messages**: `ASSERT_EQ(5, Foo(i)) << " where i = " << i;` * Google Test **automatically** detects your tests and doesn't require you to enumerate them in order to run them * Make it easy to **extend** your assertion vocabulary * **Death tests** (see advanced guide) * `SCOPED_TRACE` for subroutine loops * You can decide **which tests to run** * **XML** test report generation * **Fixtures** / **Mock** / **Templates**...
Comparison of C++ unit test frameworks
[ "", "c++", "unit-testing", "cppunit", "googletest", "boost-test", "" ]
We use a base entity with properties such as version (datetime needed for NHibernate) and guid (as key). It also has an Id (int) field with two functions. Firstly to relate to legacy application key if there is one. Secondly as a shorthand code: for instance files are sometimes created based on these which would look ugly and long using our guid key. My question is not really about pros and cons of base entities but about up-typing this Id to Int64? It would not affect how it is stored within our MS SQL Server database. Would it have more cost in our cache and memory?. Is this really that much of a worry? I am interested to hear other downsides besides performance. Consider also these values will probably be exposed through web services to third parties in time too. The alternative is to deal with the exceptions of larger integers as they arise and implement them specifically in derived entities. The downside is this would need to be done in code and what would we do when we discover some cases when in production of larger integers? There would of course be input validation to stop actual errors but it may restrict expanding data.
Well, int64 uses 8 byte of memory storage, while int uses 4 byte... however, you pointed out most of the disadvantages already. Of course calculations performed will also be slower on many systems (a 64 bit system running in 64 bit mode can perform operations on 64 bit as fast as on 32 bit, but a 32 bit system needs to perform extra work, that means adding two 64 bit numbers is performed by two 32 bit adds plus some extra code - other math operations will be equally broken down into 32 bit operations). However unless you store millions of these numbers and perform tons of operations with them, I doubt you will see any performance difference, though, neither in CPU time nor in memory.
If your app is running on a 64 bit CPU then probably not much difference at all. On a 32 bit CPU, a 64 bit integer will be more processor intensive to perfom calculations with. There is also the obvious memory use.
Downsides to using Int64 universally instead of int (C#)
[ "", "c#", ".net-2.0", "" ]
I have two STL containers that I want to merge, removing any elements that appear more than once. For example: ``` typedef std::list<int> container; container c1; container c2; c1.push_back(1); c1.push_back(2); c1.push_back(3); c2.push_back(2); c2.push_back(3); c2.push_back(4); container c3 = unique_merge(c1, c2); // c3 now contains the following 4 elements: // 1, 2, 3, 4 ``` std::unique seems to be for adjacent elements only, and in my case the containers could be in any order. I could do some **std::set** trickery I guess: ``` container unique_merge(const container& c1, const container& c2) { std::set<container::value_type> s; BOOST_FOREACH(const container::value_type& val, c1) s.insert(val); BOOST_FOREACH(const container::value_type& val, c2) s.insert(val); return container(s.begin(), s.end()); } ``` Is there a better way or have I missed something bleeding obvious?
For an unordered lists, your set trick is probably one of the best. It each insert should be O(log n), with N inserts required, and traversing will be O(n), giving you O(N\*log n). The other option is to run std::sort on each list individually and then walk through them in parallel using [std::set\_union](http://msdn.microsoft.com/en-us/library/a20tb7e2.aspx), which removes duplicates for you. This will also be O(n\*log n), so if you're worried about performance, you'll have to profile. If you're not, do whichever makes more sense to you. Edit: `set_union` will only work if there are no duplicates in the original lists, otherwise you'll have to go with `sort`, `merge`, `unique` and `erase`. The big O performance is still the same, with the same caveats about profiling. ``` template <typename container> container unique_merge(container c1, container c2) { std::sort(c1.begin(), c1.end()); std::sort(c2.begin(), c2.end()); container mergeTarget; std::merge(c1.begin(), c1.end(), c2.begin(), c2.end(), std::insert_iterator(mergeTarget, mergeTarget.end()) ); std::erase( std::unique(mergeTarget.begin(), mergeTarget.end()), mergeTarget.end() ); return mergeTarget; } ```
You are going to need to either sort (either explicitly, or implicitly via a sorted container like set). There is a common idiom using std::sort/std::unique/std::erase to get unique elements in a container. So create a container with the contents of c1, append the contents of c2, then sort, move unique elements to the end, and erase them. Something like this: ``` container c(c1.begin(), c1.end()); c.insert(c.end(), c2.begin(), c2.end()); std::sort(c.begin(), c.end()); c.erase(std::unique(c.begin(), c.end()), c.end()); ```
Best way to merge multiple STL containers, removing duplicate elements?
[ "", "c++", "stl", "" ]
I'm working on an app which scrapes data from a website and I was wondering how I should go about getting the data. Specifically I need data contained in a number of div tags which use a specific CSS class - Currently (for testing purposes) I'm just checking for ``` div class = "classname" ``` in each line of HTML - This works, but I can't help but feel there is a better solution out there. Is there any nice way where I could give a class a line of HTML and have some nice methods like: ``` boolean usesClass(String CSSClassname); String getText(); String getLink(); ```
Several years ago I used JTidy for the same purpose: <http://jtidy.sourceforge.net/> "JTidy is a Java port of HTML Tidy, a HTML syntax checker and pretty printer. Like its non-Java cousin, JTidy can be used as a tool for cleaning up malformed and faulty HTML. In addition, JTidy provides a DOM interface to the document that is being processed, which effectively makes you able to use JTidy as a DOM parser for real-world HTML. JTidy was written by Andy Quick, who later stepped down from the maintainer position. Now JTidy is maintained by a group of volunteers. More information on JTidy can be found on the JTidy SourceForge project page ."
Another library that might be useful for HTML processing is jsoup. Jsoup tries to clean malformed HTML and allows html parsing in Java using jQuery like tag selector syntax. <http://jsoup.org/>
Java HTML Parsing
[ "", "java", "html", "parsing", "web-scraping", "" ]
I have two forms, form A and form B. These forms must differ in appearance, but they share a lot of logic. The problem is that this logic is tied to the appearance (validation on button click, events being fired, etc.). For example, I have a name field, and when the save button is pressed, I need to fire an event which causes the parent form to validate the record name to avoid duplicates. Both forms need this logic, but their save buttons are in different places, and the tooltip that is shown when an error occurs also needs to appear in a different place. This is just one example, but does anyone know of a way that I can avoid copying and pasting code here? Perhaps I am missing something obvious...
You could create an object with data that is represented in both forms, and put validation logic in that object. The presentation layer should populate that object with the entered data, ask the object to validate itself, and then handle validation errors in a form-specific way.
If the common logic is UI related you need to create your own custom form class (that inherit from Form class) with the desired logic. then all you need to do is inherit that class in your forms. If the common logic is less UI related create an internal class that encapsulates the common logic and call it from both forms.
How to avoid duplicating logic on two similar WinForms?
[ "", "c#", ".net", "coding-style", "" ]
I've been looking around for a good MVC framework for Python using PyGTK. I've looked at [Kiwi](http://www.async.com.br/projects/kiwi/) but found it a bit lacking, especially with using the Gazpacho Glade-replacement. Are there any other nice desktop Python MVC frameworks? I'm one of the few (it seems) to not want a webapp.
In defense of Kiwi: * Kiwi works fine with Glade3 instead of Gazpacho. (who forced you to use Gazpacho?) * Kiwi is my first dependency for *any* PyGTK application commercial or open source. * Kiwi is very actively maintained. I have generally got to a stage where I think its irresponsible to not use Kiwi in a PyGTK application. Perhaps you can tell us what you found "lacking" so we can improve the framework. #kiwi on irc.gimp.net (or the Kiwi mailing list).
There's [Dabo](https://stackoverflow.com/questions/310856/python-gtk-mvc), made by some guys moving from FoxPro. It might work for you if you're writing a data driven business app. Beyond that, I haven't found anything that you haven't. > GUI stuff is *supposed* to be hard. It builds character. ([Attributed](http://quotations.amk.ca/python-quotes/#q28) to Jim Ahlstrom, at one of the early Python workshops. Unfortunately, things haven't changed much since then.)
Python GTK MVC: Kiwi?
[ "", "python", "model-view-controller", "gtk", "" ]
I cannot figure out a way to disable a container AND its children in Swing. Is Swing really missing this basic feature? If I do setEnabled(false) on a container, its children are still enabled. My GUI structure is pretty complex, and doing a traversion of all elements below the container is not an option. Neither is a GlassPane on top of the container (the container is not the entire window).
To add to [mmyers's answer](https://stackoverflow.com/questions/305527#305551), disabling children is not an easy task (see this [thread](http://forums.java.net/jive/thread.jspa?threadID=13758)) > The problem is near-to unsolvable in the general case. That's why it is not part of core Swing. > > Technically, the disable-and-store-old-state followed by a enable-and-restore-to-old-state might look attractive. It even might be a nice-to-have in special cases. But there are (at least, probably a bunch more) two issues with that. > > **Compound components** > > The recursion must stop on a "compound component" (or "single entity"). Then the component is responsible for keeping dependent's state. There's no general way to detect such a component - examples are JComboBox, JXDatePicker (which as related [issue](https://swingx.dev.java.net/issues/show_bug.cgi?id=275)) > > To make things even more complicated, dependents don't need to be under the hierarchy of the "compound component", f.i. JXTable takes care of the ColumnControl's (and header's) enabled state. > > Trying to tackle both would require to have > > a) a property on the compound: "don't touch my children" and > b) a property on the uncontained dependents: "don't touch me" > > **Binding to enabled** > > enable-and-update-to-old might break application state if the enabled status is bound to a (presentation or other) model property and that property changed in-the-meantime - now the old-state is invalid. > > Trying to tackle that would require to have > > c) a "real" stored-old-enabled-due-to-view-concerns property > d) bind the presentation model property to both the enabled and the stored-old-enabled > > JXRadioGroup has a variant of that problem: On disabling - the group itself or the general controller - keeps track of the old-enabled of every button. Button's enabled is controlled by the Action - if there is an Action. So the enabled controller needs to restore to old-enabled or to action's enabled. During group's disabled (as-group) a problem looms if the Action's enabled was false on storing and changed to true. > Another if actions are added. > > Now imagine the complexity of state transitions when overloading a)-- d)
[JXLayer](https://jxlayer.dev.java.net/) might be what you're looking for, according to [this post](http://weblogs.java.net/blog/alexfromsun/archive/2007/06/_enablingdisabl_1.html): > Wrap your container with the JXLayer and call `JXLayer.setLocked(true)` after that - all components inside will be disabled [alt text http://www.java.net/download/javadesktop/blogs/alexfromsun/2007.06.25/LayerDemo.PNG](http://www.java.net/download/javadesktop/blogs/alexfromsun/2007.06.25/LayerDemo.PNG)
How to disable a container and its children in Swing
[ "", "java", "swing", "" ]
``` // A Mutex allows threads mutually exclusive access to a resource. //----------------------------------------------------------------------- class Mutex { private: CRITICAL_SECTION m_mutex; public: Mutex() { InitializeCriticalSection(&m_mutex); } ~Mutex() { DeleteCriticalSection(&m_mutex); } void acquire() { EnterCriticalSection(&m_mutex); } void release() { LeaveCriticalSection(&m_mutex); } }; ``` Using the Entrek Codesnitch software to debug and test for any memory leaks, etc., it reports the following error: ``` InitializeCriticalSection Error: lpCriticalSection (0x000387d4) points to an invalid memory location (0x00018984) Mutex::Mutex in lockmutex.h, line 29 ``` Maybe all my sleepless nights are finally getting to me. But I don't understand what it's exactly complaining about. Any ideas?
I'll bet you can fake out the snitch with ::memset ( & m\_mutex, 0, sizeof ( m\_mutex ) ); before the call to init it.
CodeSnitch is apparently not smart enough to know that InitializeCriticalSection() *expects* to be working on a structure containing an uninitialized pointer. Think of it from CodeSnitch's point of view. What's the difference between what you're doing, and this: ``` struct Customer { char * name; }; extern void greetCustomer(Customer* c); class CheckoutLine { private: Customer m_customer; public CheckoutLine() { greetCustomer(&m_customer); } }; ``` This looks way more fishy to the *human* eye, because we infer that greetCustomer is probably going to rely on m\_customer being initialized, which it obviously is not. But semantically, this exactly the same as your code. It's probably worth filing a bug with Entrek; InitializeCriticalSection() is a reasonable exception to the "structures should be initialized before passing them to a function" rule.
What is wrong with this tiny piece of mutex code?
[ "", "c++", "mutex", "critical-section", "" ]
I am taking my first foray into PHP programming and need to configure the environment for the first time. Can I use PHP with the built in VS web server or do I need to (and I hope not) use IIS locally? In addition, any pointers on pitfalls to be avoided would be great. Many thanks. **Update:** I should have made the question more explicit. I am developing a ASP.Net MVC application. **Update 2:** It's become clear that I haven't asked the question as cleanly as I would have liked. Here is what I am doing. I have an existing ASP.net MVC application that I am adding an e-mail form to. While researching, I came across this page: [Ajax Forms with jQuery](http://trevordavis.net/blog/tutorial/ajax-forms-with-jquery/) and I liked the interface he presented and thought I would try and adapt it. Calls are made to PHP functions and hence my question. It is also clear that the confusion also could come from the fact that there is a better approach entirely. So, what is the way out of the maze, Alice?
For what you're doing, you really shouldn't be using the PHP scripts from that example. Instead, you should be pulling data from the Form variables posted to the server on your own self-made pages. I don't know the "proper" way to do this using the MVC framework. With the ASP Forms framework, you'd do something like this to handle the POSTed data (example of the sendmail.php file) ``` string mailTo = Request.Form["emailTo"]; string mailFrom = Request.Form["emailFrom"]; string subject = Request.Form["subject"]; string message = Request.Form["message"]; // Send mail here using variables above // You'll need an SMTP server and some mail // sending code which I'm drawing a blank as // to what the name of the classes are at the moment ``` There is probably a better way to handle this code in the MVC framework, but I haven't worked with it enough to tell you what it is. Basically, you can't use PHP code at all for an ASP.NET app.
PHP on IIS is a bit of a pitfall in itself, you can find some reference here: [What do I need to run PHP applications on IIS?](https://stackoverflow.com/questions/10515/php-on-iis) I would sugest using WAMP from here: <http://www.apachefriends.org/en/xampp-windows.html>
What's the best way to develop local using PHP and Visual Studio?
[ "", "php", "asp.net-mvc", "visual-studio", "" ]
Any good reason why $("p").html(0) makes all paragraphs empty as opposed to contain the character '0'? Instead of assuming I found a bug in jQuery, it's probably a misunderstanding on my part.
jQuery only accepts a string as an argument for the `val` parameter of the `html()` method. If you pass a number like you are it will call the `html()` method override that sets the contents of the element but the value of the argument will end up being null or an empty string. Try this: ``` $("p").html((0).toString()) ``` [Relevant documentation](http://docs.jquery.com/Attributes/html#val)
Try using `text()` instead `html()`.
Weird Behaviour in jQuery's html method
[ "", "javascript", "jquery", "" ]
What's the better way to insert cell comments in excel 2007 files programmatically using c# and .net 3.5?
I just did exactly that but with MS Word (using Microsoft.Office.Interop.Word range.Comments.Add ( range, ref \_categoryMessage ); So, I would suggest using Microsoft.Office.Interop.Excel and the similar method. Consider this from MSDN: <https://learn.microsoft.com/en-us/dotnet/api/microsoft.office.interop.excel.range.addcomment> Also see [this](https://stackoverflow.com/questions/213303/sofware-requirements-analysis#213452) too
The accepted answer points in the right direction, but the correct syntax is: ``` Excel.Range cell; cell.AddComment("My comment"); ```
Insert cell comments in excel programmatically
[ "", "c#", "excel", ".net-3.5", "openxml", "" ]
I have some code like this: ``` [AcceptVerbs(HttpVerbs.Post)] public ActionResult Save([Bind(Prefix="")]Person person) { String s = person.property; /* ... */ } ``` But it throws the error: "Cannot use local variable 'person' before it is declared". What simple thing am I missing?
Okay, this is just some really bizarre error - if the variable is named a particular name it does not work, for any other name it does work...
It is most likely that you are receiving this error because the same variable is being declared later in the same code block. According to compiler rules, a variable reference will refer to default by a matching declaration withing the same block EVEN IF THE SAME DECLARATION EXISTS OUTSIDE OF THE BLOCK IN IN LOGICAL SCOPE FLOW. So in short, check to see if the variable isnt being declared later on(a couple of lines down) in the same application block.
Cannot use local variable before it is declared ASP.NET
[ "", "c#", "asp.net-mvc", "" ]
I am looking to write a function like ``` ref String TestIt( int index ) { return this.TestArray[index]; }; ``` so that I could write code like: ``` MyClass.TestIt(0) = "Hello World"; ``` My goal is to mimic this c++ declaration ``` CString& MyClass::Data( UINT index); ``` By Reference I am referring to the c++ term the Address of the variable. in other words after my call to TestIT(0) TestArray[0] would contain "Hello World". **EDIT** I can't use an indexer because my goal is to convert a .cpp file to c# on an ongoing basis. The closer I can mimic this c++ code, the less of a converter I have to write.
To do this you need to write a setter property. Unfortunately, setters can’t take further arguments in C# so you won't be able to write this code 1:1 in C#. The closest you can get is a nested class with a default property: ``` class YourClass { public class Nested { public Nested(YourClass outer) { m_RefToOuterWorld = outer; } private readonly YourClass m_RefToOuterWorld; public string this[int index] { get { return m_RefToOuter.TestArray[index]; set { m_RefToOuter.TestArray[index] = value; } } } private readonly Nested m_Nested; private string[] TestArray = new string[10]; public YourClass() { m_Nested = new Nested(this); } public Nested TestIt { get { return m_Nested; } } } ``` You can use it like this: ``` var test = new YourClass(); test.TestIt[2] = "Hello world!"; ``` By the way, since this is so much effort, you probably don't want to do this. Also, it doesn't feel very C#-y. The useless indiretion through the nested class here isn't something you'll see very often.
The short answer is that you cannot return a reference to a string *variable*, i.e. a reference to the string reference). The simple solution is to avoid this kind of API and require the user to set the string in another way: ``` myobj.SetString(0, "Hello, world!"); ``` If you *really* need to represent (as a first-class object) a reference to your string reference, try something like this API: ``` Interface IStringReference { void SetString(string value); string GetString(); } class MyClass { public IStringReference TestIt() { ... details left out ;) ... } } ``` but I think this is going too far in mimicking C++'s lvalues.
How to return a reference to a string in c#?
[ "", "c#", "" ]
I'm fairly new to WPF and I've come across a problem that seems a bit tricky to solve. Basically I want a 4x4 grid thats scalable but keeps a square (or any other arbitrary) aspect ratio. This actually seems quite tricky to do, which surprises me because I would imagine its a reasonably common requirement. I start with a Grid definition like this: ``` <Grid> <Grid.RowDefinitions> <Grid.RowDefinition Height="*"/> <Grid.RowDefinition Height="*"/> <Grid.RowDefinition Height="*"/> <Grid.RowDefinition Height="*"/> </Grid.RowDefinitions> <Grid.ColumnDefinitions> <Grid.ColumnDefinition Width="*"/> <Grid.ColumnDefinition Width="*"/> <Grid.ColumnDefinition Width="*"/> <Grid.ColumnDefinition Width="*"/> </Grid.ColumnDefinition> ... </Grid> ``` Now if you set that to stretch, it can fill the Window or whatever container you put it in. The rows and column are uniform but the aspect ratio isn't fixed. Then I tried putting it in a StackPanel to use the available space. Didn't help. What did get me most of the way there was when I remembered Viewboxes. ``` <StackPanel Orientation="Horizontal"> <Viewbox> <Grid Height="1000" Width="1000"> <!-- this locks aspect ratio --> <Grid.RowDefinitions> <Grid.RowDefinition Height="*"/> <Grid.RowDefinition Height="*"/> <Grid.RowDefinition Height="*"/> <Grid.RowDefinition Height="*"/> </Grid.RowDefinitions> <Grid.ColumnDefinitions> <Grid.ColumnDefinition Width="*"/> <Grid.ColumnDefinition Width="*"/> <Grid.ColumnDefinition Width="*"/> <Grid.ColumnDefinition Width="*"/> </Grid.ColumnDefinition> ... </Grid> </viewbox> <Label HorizontalAlignment="Stretch">Extra Space</Label> </StackPanel> ``` Now my content scales and keeps aspect ratio. The problem is that if the window isn't wide enough some of my grid is off the screen. I'd like to be able to scroll to it if that were the case. Likewise, I might need a minimum size, which might lead to vertical scrolling too. Now I've tried putting my StackPanel and Grid (separately) in an appropriate ScrollViewer container but then the content no longer scales to fit the window. It goes to full size, which is no good. So how do I go about doing this? Am I barking up the wrong tree? Is there a better/easier way of doing this?
You need to put the content (the grid) inside a [Viewbox](http://msdn.microsoft.com/en-us/library/system.windows.controls.viewbox.aspx) and set the [Viewbox.Stretch Property](http://msdn.microsoft.com/en-us/library/system.windows.controls.viewbox.stretch.aspx) to [Stretch.Uniform](http://msdn.microsoft.com/en-us/library/system.windows.media.stretch.aspx) The Viewbox control is used to stretch or scale a child element and lets you control the way the child is stretched. Check the [examples](http://msdn.microsoft.com/en-us/library/system.windows.media.stretch.aspx) here. [![alt text](https://i.stack.imgur.com/5sBYY.jpg)](https://i.stack.imgur.com/5sBYY.jpg) (source: [microsoft.com](http://i.msdn.microsoft.com/ms635549.img_mmgraphics_stretchenum(en-us,VS.90).jpg))
In this instance, your best bet is a [UniformGrid](http://msdn.microsoft.com/en-us/library/system.windows.controls.primitives.uniformgrid.aspx). This is only useful if you want NxN grids.
How do I keep aspect ratio on scalable, scrollable content in WPF?
[ "", "c#", ".net", "wpf", "xaml", "" ]
We've been trying to hunt down some heap corruption issues in our multi-threaded C++ apps. As one technique, we tried add -lmcheck to the libraries line of the application. This is causing the app to crash out with apparent heap corruption in relatively short order. Our app does use both malloc/free and new/delete (as appropriate). One of our team wondered if -lmcheck was in fact thread safe, and put a mutex around all malloc/free calls. The crashes went away. Does anyone know if -lmcheck is supposed to support multi-threading? I wonder if we just mis-understand the tool we're trying to use and thereby causing ourselves unneeded worry.
No, mcheck is not thread-safe and should not be used with multi-threaded applications. Doing so can introduce additional problems since there is no synchronization between the threads. Here is the response from Ulrich Drepper (glibc maintainer) on the subject a few months ago: > mcheck does not work for multi-threaded code. It cannot > possibly do. There is no way to fix > this with the technology underlying > mcheck.
I should have checked that before we spent time fooling with it. Ahh well. Here's the link to where that quote comes from (I believe): <http://sourceware.org/bugzilla/show_bug.cgi?id=6547> glibc documentation defect: <http://sourceware.org/bugzilla/show_bug.cgi?id=12751> has been opened to help avoid others from hitting this.
glibc's '-lmcheck' option and multithreading
[ "", "c++", "multithreading", "glibc", "" ]
How do I do the above? I've started using MVC and I'm having issues passing data around. My specific problem is to do with a list of objects I have in my Model which I need to access in a View and iterate through. Thanks in advance.
Let's say your controller action looks something like ``` public ActionResult List() { List<string> myList = database.GetListOfStrings(); (...) } ``` Now you want to pass your list to the view, say "List.aspx". You do this by having the action return a ViewResult (ViewResult is a subclass of ActionResult). You can use the Controller's View method to return a ViewResult like so: ``` public ActionResult List() { List<string> myList = database.GetListOfStrings(); (...) return View("List", myList); } ``` To be able to access the list in a strongly-typed fashion in your view, it must derive from ViewPage, where T is the type of the data you are passing in. Thus, in the current case our view (in List.aspx.cs) would something like this: ``` public partial class List : ViewPage<string> { (...) } ``` The data passed into the view in this way is referred to as the "ViewData". To access the data, you must go through the ViewData.Model properties on the ViewPage. Thus, to render the contents of the list you would write (in List.aspx) ``` <ul> <% foreach(var s in this.ViewData.Model){ %> <li> <%= s %> </li> <% } %> </ul> ``` Here, this.ViewData.Model has the type you specified the type parameter T in ViewPage, so in our case this.ViewData.Model has type List. You *can* use a repeater for rendering stuff like this, but I wouldn't recommend it. If you want to use something similar, check out the Grid module of the MvcContrib project on CodePlex.
The quick and dirty way is to pass it via ViewData ``` public ActionResult List() { ViewData["MyList"] = new List<string> () {"test1", "test2"}; return View (); } ``` then you can access it in your view ``` <ul> <% foreach (string item in (List<string>)ViewData["MyList"]) { %> <li><%= item %></li> <% }%> </ul> ```
ASP.NET MVC: How do I pass a list (from a class in Model) to a repeater in a View?
[ "", "c#", "asp.net-mvc", "model-view-controller", "" ]
Assume I have a function like this: ``` MyClass &MyFunction(void) { static MyClass *ptr = 0; if (ptr == 0) ptr = new MyClass; return MyClass; } ``` The question is at program exit time, will the ptr variable ever become invalid (i.e. the contents of that ptr are cleaned up by the exiting process)? I realize that this function leaks, but it is only an example for simplicity. The same question also applies to other primitives besides pointers as well. How about if I have a static integer, does the value of that integer always persist throughout exit or is variable due to static destruction order issues? EDIT: Just to clarify, I want to know what actually happens to the contents of the static pointer (or any other primitive type like an int or a float) and not to the memory it is pointing to. For instance, imagine that the ptr points to some memory address which I want to check in the destructor of some other static class. Can I rely on the fact that the contents of the ptr won't be changed (i.e. that the pointer value won't be cleaned up during the static destruction process)? Thanks, Joe
To answer your question: ``` 'imagine that the ptr points to some memory address which I want to check in the destructor of some other static class' ``` The answer is yes. You can see the value of the pointer (the address). You can look at the content if you have not called delete on the pointer. Static function variables behave in the same way as static class variables and global variables (**aka** non local static), in that there destructors will be called in reverse order of creation. Integers, floats and **pointers** (POD) do not have destructors so nothing happens to them until the processes is removed. POD objects: Data can safely by referenced from the destructor of other objects (even global s). Other static objects (i.e. those with destructors): In the general case, it is not safe to accesses these objects after main() has exited because the order of destruction is not know (it is the reverse of the order of creation, but the order of creation is complex see: [Construction Order](https://stackoverflow.com/questions/294270/how-do-you-call-a-constructor-for-global-objects-for-arrays-of-objects-and-for#294308) ). It can be done but you have to take explicit precautions to make sure the object is still alive. ### Note: non local static: The memory will always be there, the object will just not be valid after a destructor is called (note POD does not have a destructor). ### Note: Stack: Only valid until the scope in which they are declared is left. After the stack is popped the memory page that it is on could potentially be dropped resulting in SEG faults if you attempt to access it. ### Note: Heap: Valid until you call delete on the pointer that allocated it. Once a pointer is delete the value is potentially random as it may be re-used. Potentially the page the memory was on can also be dropped. Any access to a dropped page would result in a SEG fault.
When you process exits the all memory pages allocated to it will be freed by the OS (modulo shared memory pages that someone else may be using). However, as others point out the destructor for MyClass is never called. Nor is the value pointed to by ptr ever changed. If you have a static int with the value 123 then its value will stay 123 through to the very end of the process' lifetime.
C++: Do static primitives become invalid at program exit?
[ "", "c++", "memory-management", "static", "" ]
Is it possible to perform a named-group match in Perl's regex syntax as with Python's? I always bind the `$n` values to proper names after matching, so I'd find it more convenient to do it in the regex itself if it's possible. Python does it like so: ``` >>> import re >>> regex = re.compile(r'(?P<count>\d+)') >>> match = regex.match('42') >>> print match.groupdict() {'count': '42'} ``` I know the `?P` indicates that it's a Python-specific regex feature, but I'm hoping it's in Perl in a different way or was added later on. Is there any way to get a result hash in a similar manner in Perl?
Perl uses `(?<NAME>pattern)` to specify names captures. You have to use the `%+` hash to retrieve them. ``` $variable =~ /(?<count>\d+)/; print "Count is $+{count}"; ``` This is only supported on Perl 5.10 and higher though.
As of Perl 5.10, Perl regexes support [some Python features](http://perldoc.perl.org/perlre.html#PCRE%2fPython-Support), making them *Python* compatible regexes, I guess. The Python versions have the "P" in them, but all of these work in Perl 5.10. See the [perlre](http://perldoc.perl.org/perlre.html) documentation for the details: Define a named capture buffer. Equivalent to `(?<NAME>pattern)`. ``` (?P<NAME>pattern) ``` Backreference to a named capture buffer. Equivalent to `\g{NAME}`. ``` (?P=NAME) ``` Subroutine call to a named capture buffer. Equivalent to `(?&NAME)`. ``` (?P>NAME) ``` Although I didn't add the Python-compatibility to the latest edition of [Learning Perl](http://oreilly.com/catalog/9780596520106/), we do cover the new Perl 5.10 features, including named captures.
Can I use named groups in a Perl regex to get the results in a hash?
[ "", "python", "regex", "perl", "" ]
How can I fetch more than 1000 record from data store and put all in one single list to pass to django?
Starting with Version 1.3.6 (released Aug-17-2010) you **CAN** [From the changelog:](http://code.google.com/p/googleappengine/wiki/SdkReleaseNotes#Version_1.3.6_-_August_17,_2010) > Results of datastore count() queries **and offsets for all datastore queries are no longer capped at 1000**.
Just for the record - fetch limit of 1000 entries is now gone: <http://googleappengine.blogspot.com/2010/02/app-engine-sdk-131-including-major.html> Quotation: > No more 1000 result limit - That's > right: with addition of Cursors and > the culmination of many smaller > Datastore stability and performance > improvements over the last few months, > we're now confident enough to remove > the maximum result limit altogether. > Whether you're doing a fetch, > iterating, or using a Cursor, there's > no limits on the number of results.
How to fetch more than 1000?
[ "", "python", "google-app-engine", "google-cloud-datastore", "" ]
Is there a way to find out when in a LAN anyone plugs in a pendrive to the USB port? Programatically (in C# preferably) or through some tool. Basically I'd imagine a client application sits on each terminal and monitors the USB ports and sends the information to the server. a.) Can I get the details of the file(s) being copied? b.) Is there a way to do this without a client application? EDIT I dont want to disable the USB port entirely. its to be on a need to have basis. Basically just want the users on the LAN to share data responsibly and know that whatever data is tranfered is monitored and logged and can be questioned later.
[Assuming Windows, given the C# remark. Please tag accordingly] Yes, this is possible. And it is possible to get the details of the file. It will require programming, though. Watch for [WM\_DEVICECHANGE](http://msdn.microsoft.com/en-us/library/aa363480(VS.85).aspx) and re-enumerate drives afterwards. It will get you USB pendrives, but also SD cards. I expect that's a bonus for you. To get more details once you know a drive has arrived, use [System.IO.FileSystemWatcher](http://msdn.microsoft.com/en-us/library/system.io.filesystemwatcher.aspx) **Update** I found a better solution - if you register for volume interface notifications, you'll get the volume path for the new drive. First, create a `DEV_BROADCAST_DEVICEINTERFACE` with `dbcc_classguid=GUID_DEVINTERFACE_VOLUME`. Then pass this to `RegisterDeviceNotification()`. You will again get a WM\_DEVICECHANGE but you can now cast the lParam from the message to `DEV_BROADCAST_DEVICEINTERFACE*`. You can pass the `dbcc_name` you receive to `GetVolumeNameForVolumeMountPoint()`. You can also pass all drive letters from `GetLogicalDriveStrings()` to `GetVolumeNameForVolumeMountPoint()`. You'll have one matching volume name; this is the new drive.
Also check out the registry where all information is stored about the usb devices. HKEY\_LOCAL\_MACHINE\SYSTEM\CurrentControlSet\Enum\USB You can hook into changes of that key in the registry and act upon that. This free utility are a big help when pooking around: <http://www.nirsoft.net/utils/usb_devices_view.html> You can select a usb-drive, choose to open the registry key for that drive and enable/disable the device and a lot more. In the registry you can see if the device is connected, if it's of massstorage type and other interresting information. Its easy to filter the regkeys to just get usb-massstorage drives and then hook into and wait for changes (connect/disconnect). With Windows Management Instrumentation you can register to recieve Registry events: <http://msdn.microsoft.com/en-us/library/aa393035(VS.85).aspx> Check out System.Management in .Net
How to detect using c# if a pendrive is plugged into a USB port?
[ "", "c#", "windows", "usb", "monitoring", "usb-flash-drive", "" ]
This question follows on from [this vim search question](https://stackoverflow.com/questions/299114/can-i-search-for-php-class-members-and-methods-with-vim-star-search) I have a setting in my .vimrc which excludes $ as a valid part of a word: ``` set iskeyword-=$ ``` This works fine for most files but isn't working in PHP. I assume it is being overwritten by a php plugin, but since plugins are loaded after .vimrc I can't work out how to overwrite this setting. I'd prefer not to have to type ``` :set isk-=$ ``` every time I load a PHP file. Any suggestions? ( Ubuntu 8.04 / Vim 7.1.138 if it matters ) **Summary** Two excellent answers, thank you! I went with [tomalak](https://stackoverflow.com/users/18771/tomalak)'s because it was less effort, and added the following to my ~/.vimrc ``` autocmd FileType php setlocal isk-=$ ``` but thanks also to [Luc Hermitte](https://stackoverflow.com/questions/305574/can-i-stop-settings-in-vimrc-from-being-overwritten-by-plugins#305820). Putting the settings in a ~/vim/after/ftplugin/php.vim file also worked. *:help autocmd* and *:help after-directory* both helped too
I would probably just add `set isk-=$` to my syntax highlighting auto command in `$VIMRUNTIME\filetype.vim`. Don't know if it is the nicest way to do it, though. Thinking about it... I think it would be enough to have an appropriate autocommand in your `vimrc`. ``` au FileType php set isk-=$ ``` This executes after the FileType has been set. Auto commands are executed in the order they are given, so when you put it late in your `vimrc` it will execute last for PHP files.
Add a {rtp}/after/ftplugin/php.vim that contains the `:setlocal isk-=$` Otherwise, you will have to track where it has been changed last with `:verbose set isk`, or by playing with `:scriptnames`
Can I stop settings in vimrc from being overwritten by plugins?
[ "", "php", "plugins", "vim", "" ]
We are developing large ASP.NET applications with lot of dynmically created pages containing ASCX controls. We use a lot of jQuery everywhere. I have been reading that it would make sense to move the inline JavaScript code to the bottom of the page as it could delay the loading of the page when it's included "too early". My question is now: **Does this still make sense when working with jQuery?** Most of the code is executed in the ready handler, so I would expect that is does not slow down the loading of the page. In my case the multiple Usercontrols **ASCX have all their own jQuery** bits and pieces, and it would not be easy to move that all down in the rendered page.
You could model the different ways of ordering the JavaScript in [Cuzillion](http://stevesouders.com/cuzillion/) to see how it affects page loading. See the [examples](http://stevesouders.com/cuzillion/help.php#examples) and [this blog post](http://www.stevesouders.com/blog/2008/04/25/cuzillion/) for examples of how ordering of page elements can affect speed.
Placing scripts late in the HTML is recommended because loading and executing scripts happens sequentially (one script at a time) and completely blocks the loading and parsing of images and CSS files meanwhile. Large/lagged/slow-running scripts near the top of the page can cause unnecessary delay to the loading and rendering of the page content/layout. Script's size (download time) and complexity (execution time (dom traversal, etc.)) factor in - but more importantly, the number of individual `<script>` HTTP requests matters far more (the fewer requests the better). Using the "document.ready" handler lessens the delay caused by slow execution - but still leaves the problem of the sequential HTTP overhead. Recommended reading: [High Performance Web Sites](http://nate.koechley.com/blog/2007/06/12/high-performance-web-sites/) by Nate Koeckley.
jQuery: Move JavaScript to the bottom of the page?
[ "", "javascript", "asp.net", "jquery", "" ]
I have a somewhat complex WPF application which seems to be 'hanging' or getting stuck in a Wait call when trying to use the dispatcher to invoke a call on the UI thread. The general process is: 1. Handle the click event on a button 2. Create a new thread (STA) which: creates a new instance of the presenter and UI, then calls the method **Disconnect** 3. Disconnect then sets a property on the UI called **Name** 4. The setter for Name then uses the following code to set the property: ``` if(this.Dispatcher.Thread != Thread.CurrentThread) { this.Dispatcher.Invoke(DispatcherPriority.Normal, (ThreadStart)delegate{ this.Name = value; // Call same setter, but on the UI thread }); return; } SetValue(nameProperty, value); // I have also tried a member variable and setting the textbox.text property directly. ``` My problem is that when the dispatcher **invoke** method is called it seems to hang every single time, and the callstack indicates that its in a sleep, wait or join within the Invoke implementation. So, is there something I am doing wrong which I am missing, obvious or not, or is there a better way of calling across to the UI thread to set this property (and others)? **Edit:** The solution was to call System.Windows.Threading.Dispatcher.Run() at the end of the thread delegate (e.g. where the work was being performed) - Thanks to all who helped.
You say you are creating a new STA thread, is the dispatcher on this new thread running? I'm getting from "this.Dispatcher.Thread != Thread.CurrentThread" that you expect it to be a different dispatcher. Make sure that its running otherwise it wont process its queue.
Invoke is synchronous - you want Dispatcher.BeginInvoke. Also, I believe your code sample should move the "SetValue" inside an "else" statement.
WPF Dispatcher.Invoke 'hanging'
[ "", "c#", ".net", "wpf", "invoke", "dispatcher", "" ]
I have a SQL challenge that is wracking my brain. I am trying to reconcile two reports for licenses of an application. The first report is an access database table. It has been created and maintained by hand by my predecessors. Whenever they installed or uninstalled the application they would manually update the table, more or less. It has a variety of columns of inconsistent data, including Name(displayName) Network ID(SAMAccountName) and Computer Name. Each record has a value for at least one of these fields. Most only have 1 or 2 of the values, though. The second report is based on an SMS inventory. It has three columns: NetbiosName for the computer name, SAMAccountName, and displayName. Every record has a NetbiosName, but there are some nulls in SAMAccountName and displayName. I have imported both of these as tables in an MS SQL Server 2005 database. What I need to do is get a report of each record in the Access table that is not in the SMS table and vice versa. I think it can be done with a properly formed join and where clause, but I can't see how to do it. *Edit to add more detail:* If the records match for at least one of the three columns, it is a match. So I need the records form the Access table where the Name, NetworkID, and ComputerName are all missing from the SMS table. I can do it for anyone column, but I can't see how to combine all three columns.
Taking Kaboing's answer and the edited question, the solution seems to be: ``` SELECT * FROM report_1 r1 FULL OUTER JOIN report_2 r2 ON r1.SAMAccountName = r2.SAMAccountName OR r1.NetbiosName = r2.NetbiosName OR r1.DisplayName = r2.DisplayName WHERE r2.NetbiosName IS NULL OR r1.NetbiosName IS NULL ``` Not sure whether records will show up multiple times
You need to look at the [EXCEPT](http://msdn.microsoft.com/en-us/library/ms188055.aspx) clause. It's new to SQL SERVER 2005 and does the same thing that Oracle's MINUS does. SQL1 EXCEPT SQL2 will give you all the rows in SQL1 not found in SQL2 IF SQL1 = A, B, C, D SQL2 = B, C, E the result is A, D
SQL join to find inconsistencies between two data sources
[ "", "sql", "sql-server", "" ]
I have an annoying problem which I might be able to somehow circumvent, but on the other hand would much rather be on top of it and understand what exactly is going on, since it looks like this stuff is really here to stay. Here's the story: I have a simple OpenGL app which works fine: never a major problem in compiling, linking, or running it. Now I decided to try to move some of the more intensive calculations into a worker thread, in order to possibly make the GUI even more responsive — using Boost.Thread, of course. In short, if I add the following fragment in the beginning of my .cpp file: ``` #include <boost/thread/thread.hpp> void dummyThreadFun() { while (1); } boost::thread p(dummyThreadFun); ``` , then I start getting "This application has failed to start because MSVCP90.dll was not found" when trying to launch the Debug build. (Release mode works ok.) Now looking at the executable using the Dependency Walker, who also does not find this DLL (which is expected I guess), I could see that we are looking for it in order to be able to call the following functions: ``` ?max@?$numeric_limits@K@std@@SAKXZ ?max@?$numeric_limits@_J@std@@SA_JXZ ?min@?$numeric_limits@K@std@@SAKXZ ?min@?$numeric_limits@_J@std@@SA_JXZ ``` Next, I tried to convert every instance of `min` and `max` to use macros instead, but probably couldn't find all references to them, as this did not help. (I'm using some external libraries for which I don't have the source code available. But even if I could do this — I don't think it's the right way really.) So, my questions — I guess — are: 1. Why do we look for a non-debug DLL even though working with the debug build? 2. What is the correct way to fix the problem? Or even a quick-and-dirty one? I had this first in a pretty much vanilla installation of Visual Studio 2008. Then tried installing the Feature Pack and SP1, but they didn't help either. Of course also tried to Rebuild several times. I am using prebuilt binaries for Boost (v1.36.0). This is not the first time I use Boost in this project, but it may be the first time that I use a part that is based on a separate source. Disabling incremental linking doesn't help. The fact that the program is OpenGL doesn't seem to be relevant either — I got a similar issue when adding the same three lines of code into a simple console program (but there it was complaining about MSVCR90.dll and `_mkdir`, and when I replaced the latter with `boost::create_directory`, the problem went away!!). And it's really just removing or adding those three lines that makes the program run ok, or not run at all, respectively. I can't say I understand Side-by-Side (don't even know if this is related but that's what I assume for now), and to be honest, I am not super-interested either — as long as I can just build, debug and deploy my app... --- **Edit 1:** While trying to build a stripped-down example that anyway reproduces the problem, I have discovered that the issue has to do with [the Spread Toolkit](http://www.spread.org/), the use of which is a factor common to all my programs having this problem. (However, I never had this before starting to link in the Boost stuff.) I have now come up with a minimal program that lets me reproduce the issue. It consists of two compilation units, A.cpp and B.cpp. A.cpp: ``` #include "sp.h" int main(int argc, char* argv[]) { mailbox mbox = -1; SP_join(mbox, "foo"); return 0; } ``` B.cpp: ``` #include <boost/filesystem.hpp> ``` Some observations: 1. If I comment out the line `SP_join` of A.cpp, the problem goes away. 2. If I comment out the single line of B.cpp, the problem goes away. 3. If I move or copy B.cpp's single line to the beginning or end of A.cpp, the problem goes away. (In scenarios 2 and 3, the program crashes when calling `SP_join`, but that's just because the mailbox is not valid... this has nothing to do with the issue at hand.) In addition, Spread's core library is linked in, and that's surely part of the answer to my question #1, since there's no debug build of that lib in my system. Currently, I'm trying to come up with something that'd make it possible to reproduce the issue in another environment. (Even though I will be quite surprised if it actually can be repeated outside my premises...) --- **Edit 2:** Ok, so [here](http://users.tkk.fi/jsreunan/BoostThreadTest.zip) we now have a package using which I was able to reproduce the issue on an almost vanilla installation of WinXP32 + VS2008 + Boost 1.36.0 (still [pre-built binaries from BoostPro Computing](http://www.boostpro.com/products/free)). The culprit is surely the Spread lib, my build of which somehow requires a rather archaic version of STLPort for *MSVC 6*! Nevertheless, I still find the symptoms relatively amusing. Also, it would be nice to hear if you can actually reproduce the issue — including scenarios 1-3 above. The package is quite small, and it should contain all the necessary pieces. As it turns out, the issue did not really have anything to do with Boost.Thread specifically, as this example now uses the Boost Filesystem library. Additionally, it now complains about MSVCR90.dll, not P as previously.
Boost.Thread has quite a few possible build combinations in order to try and cater for all the differences in linking scenarios possible with MSVC. Firstly, you can either link statically to Boost.Thread, or link to Boost.Thread in a separate DLL. You can then link to the DLL version of the MSVC runtime, or the static library runtime. Finally, you can link to the debug runtime or the release runtime. The Boost.Thread headers try and auto-detect the build scenario using the predefined macros that the compiler generates. In order to link against the version that uses the debug runtime you need to have `_DEBUG` defined. This is automatically defined by the /MD and /MDd compiler switches, so it should be OK, but your problem description suggests otherwise. Where did you get the pre-built binaries from? Are you explicitly selecting a library in your project settings, or are you letting the auto-link mechanism select the appropriate .lib file?
This is a classic link error. It looks like you're [linking to a Boost DLL](http://www.boost.org/doc/libs/1_36_0/more/getting_started/windows.html#library-naming) that itself links to the wrong C++ runtime (there's also [this page](http://www.boost.org/development/separate_compilation.html), do a text search for "threads"). It also looks like the `boost::posix::time` library links to the correct DLL. Unfortunately, I'm not finding the page that discusses how to pick the correctly-built Boost DLL (although I did find a [three-year-old email](http://lists.boost.org/Archives/boost/2005/11/96515.php) that seems to point to `BOOST_THREAD_USE_DLL` and `BOOST_THREAD_USE_LIB`). --- Looking at your answer again, it appears you're using pre-built binaries. The DLL you're not able to link to is [part of the TR1 feature pack](http://blogs.msdn.com/vcblog/archive/2008/01/08/q-a-on-our-tr1-implementation.aspx) (second question on that page). [That feature pack is available on Microsoft's website](http://www.microsoft.com/downloads/details.aspx?FamilyId=D466226B-8DAB-445F-A7B4-448B326C48E7&displaylang=en). Or you'll need a different binary to link against. Apparently the `boost::posix::time` library links against the unpatched C++ runtime. Since you've already applied the feature pack, I think the next step I would take would be to build Boost by hand. That's the path I've always taken, and it's very simple: [download the BJam binary](http://www.boost.org/users/download/), and run the Boost Build script in the library source. That's it.
Adding Boost makes Debug build depend on "non-D" MSVC runtime DLLs
[ "", "c++", "visual-studio-2008", "dll", "boost", "sxs", "" ]
What is the simplest way to get: `http://www.[Domain].com` in asp.net? There doesn't seem to be one method which can do this, the only way I know is to do some string acrobatics on server variables or Request.Url. Anyone?
You can do it like this: ``` string.Format("{0}://{1}:{2}", Request.Url.Scheme, Request.Url.Host, Request.Url.Port) ``` And you'll get the [generic URI syntax](http://www.faqs.org/rfcs/rfc2396.html) <protocol>://<host>:<port>
We can use Uri and his baseUri constructor : * `new Uri(this.Request.Url, "/")` for the root of the website * `new Uri(this.Request.Url, this.Request.ResolveUrl("~/"))` for the root of the website
What is the quickest way to get the absolute uri for the root of the app in asp.net?
[ "", "c#", "asp.net", "" ]
What is the simplest, fastest way to complete the PHP code below such that the output is in a user-friendly format (for example, "October 27, 2006")? ``` $result = mysql_query("SELECT my_timestamp FROM some_table WHERE id=42", $DB_CONN); $row = mysql_fetch_array($result); $formatted_date = ???($row['my_timestamp']); echo $formatted_date; ```
You could use MySQL to do this for you, ``` $result = mysql_query("SELECT DATE_FORMAT(my_timestamp, '%M %d, %Y) AS my_timestamp FROM some_table WHERE id=42", $DB_CONN); $row = mysql_fetch_array($result); $formatted_date = $row['my_timestamp']; echo $formatted_date; ``` Or use PHP, ``` $result = mysql_query("SELECT my_timestamp FROM some_table WHERE id=42", $DB_CONN); $row = mysql_fetch_array($result); $formatted_date = strftime('%B %d, %y', $row['my_timestamp']); echo $formatted_date; ```
I tend to do the date formatting in SQL, like [Aron](https://stackoverflow.com/users/11568/aron)'s [answer](https://stackoverflow.com/questions/238071/what-is-the-simplest-way-to-format-a-timestamp-from-sql-in-php#238077). Although for PHP dates, I prefer using the [DateTime](http://www.php.net/manual/en/function.date-create.php) object (PHP5+) over [date](http://www.php.net/manual/en/function.date.php): ``` $timestamp = new DateTime($row['my_timestamp']); echo $timestamp->format('F j, Y') . '<br />'; echo $timestamp->format('F j, Y g:ia'); ```
What is the simplest way to format a timestamp from SQL in PHP?
[ "", "php", "mysql", "formatting", "timestamp", "" ]
When measuring network latency (time ack received - time msg sent) in any protocol over TCP, what timer would you recommend to use and why? What resolution does it have? What are other advantages/disadvantages? Optional: how does it work? Optional: what timer would you NOT use and why? I'm looking mostly for Windows / C++ solutions, but if you'd like to comment on other systems, feel free to do so. (Currently we use GetTickCount(), but it's not a very accurate timer.)
This is a copy of my answer from: [C++ Timer function to provide time in nano seconds](https://stackoverflow.com/questions/275004/c-timer-function-to-provide-time-in-nano-seconds#275231) For Linux (and BSD) you want to use [clock\_gettime()](http://opengroup.org/onlinepubs/007908799/xsh/clock_gettime.html). ``` #include <sys/time.h> int main() { timespec ts; // clock_gettime(CLOCK_MONOTONIC, &ts); // Works on FreeBSD clock_gettime(CLOCK_REALTIME, &ts); // Works on Linux } ``` For windows you want to use the [QueryPerformanceCounter](http://support.microsoft.com/kb/172338). And here is more on [QPC](http://msdn.microsoft.com/en-us/library/ms979201.aspx) Apparently there is a known [issue](http://support.microsoft.com/kb/274323) with QPC on some chipsets, so you may want to make sure you do not have those chipset. Additionally some dual core AMDs may also cause a [problem](http://forum.beyond3d.com/showthread.php?t=47951). See the second post by sebbbi, where he states: > QueryPerformanceCounter() and > QueryPerformanceFrequency() offer a > bit better resolution, but have > different issues. For example in > Windows XP, all AMD Athlon X2 dual > core CPUs return the PC of either of > the cores "randomly" (the PC sometimes > jumps a bit backwards), unless you > specially install AMD dual core driver > package to fix the issue. We haven't > noticed any other dual+ core CPUs > having similar issues (p4 dual, p4 ht, > core2 dual, core2 quad, phenom quad).
You mentioned that you use GetTickCount(), so I'm going to recommend that you take a look at QueryPerformanceCounter().
Timers to measure latency
[ "", "c++", "winapi", "timer", "latency", "" ]
I know in the MVC Framework, you have the Html Class to create URLs: ``` Html.ActionLink("About us", "about", "home"); ``` But what if you want to generate Urls in Webforms? I haven't found a really good resource on the details on generating URLs with Webforms. For example, if I'm generating routes like so: ``` Route r = new Route("{country}/{lang}/articles/{id}/{title}", new ArticleRouteHandler("~/Forms/Article.aspx")); Route r2 = new Route("{country}/{lang}/articles/", new ArticleRouteHandler("~/Forms/ArticlesList.aspx")); Routes.Add(r); Routes.Add(r2); ``` How would i generate URLs using the Routing table data. ## How do I generate URLS based on my routes? eg. /ca/en/articles/123/Article-Title without
As you say, ASP.NET MVC offers you a set of helper methods to "reverse lookup" the RouteTable and generate a URL for you. I've not played with this much yet but as far as I can see you need to call the GetVirtualPath method on a RouteCollection (most likely RouteTable.Routes). So something like: ``` Dim routedurl = RouteTable.Routes.GetVirtualPath(context, rvd).VirtualPath ``` You need to pass the RequestContext and a RouteValueDictionary. The RouteValueDictionary contains the route parameters (so in your case something like county="UK", lang="EN-GB" etc. The tricky part is the RequestContext as this is not part of the normal HttpContext. You can push it into the HttpContext in your IRouteHandler: ``` requestContext.HttpContext.Items("RequestContext") = requestContext ``` and then restore it again in your IHttpHandler (aspx page) when required: ``` Dim rvd = New RouteValueDictionary(New With {.country = "UK", .lang = "EN-GB"}) Dim routedurl = RouteTable.Routes.GetVirtualPath(context.Items("RequestContext"), rvd).VirtualPath ``` Apologies for responding to a C# question in VB, it was just that the ASP.NET routing site I had to hand was in VB.NET.
Thanks for the answers. TO add to this, here is what I've done: ## In Global.asax ``` RouteValueDictionary rvdSiteDefaults = new RouteValueDictionary { { "country", "ca" }, { "lang", "en" } }; Route oneArticle = new Route("{country}/{lang}/articles/a{id}/{title}", rvdSiteDefaults, rvdConstrainID, new ArticleRouteHandler("~/Articles/Details.aspx")); Routes.Add( "Article", oneArticle); ``` ## Create Url from Article object ``` public static string CreateUrl(Article a) { // Note, Article comes from Database, has properties of ArticleID, Title, etc. RouteValueDictionary parameters; string routeName = "Article"; // Set in Global.asax parameters = new RouteValueDictionary { { "id", a.ArticleID }, { "title", a.Title.CleanUrl() } }; ``` CleanUrl() [returns a URL Friendly name](https://stackoverflow.com/questions/266719/url-routing-handling-spaces-and-illegal-characters-when-creating-friendly-urls#271568). ``` VirtualPathData vpd = RouteTable.Routes.GetVirtualPath(null, routeName, parameters); string url = vpd.VirtualPath; return url; // eg. /ca/en/1/The-Article-Title } ``` TaDa!
Generate a URL with URL Routing in Webforms
[ "", "c#", "url", "routes", "url-routing", "" ]
I've got Postscript code/data (?) in memory (in a Java Tomcat webapp) that I'd like to send directly to a networked PS printer. Is there an easy way (i.e. just popping open a port and sending the text) to print this, bypassing all of the O/S-specific drivers and stuff (and hopefully not even requiring extra jars)? A link to example code showing how to do this? Thanks, Dave
open a TCP socket to the LPR port on the target printer. send your data; as long as the printer comprehends it, you're cool. don't forget a Line feed when you're done. (then close the port.)
You can send it directly to a network printer on port 9100. I wrote a blog post about this here: <http://frank.zinepal.com/printing-directly-to-a-network-printer> The problem is that most laser printers do not support PostScript. You usually have to get a printer add-on for it.
Java printing directly to a Postscript network printer
[ "", "java", "networking", "printing", "postscript", "" ]
I know it makes little difference to a project but, assuming you use #defined header guards for your C++ code, what format do you use? e.g. assuming a header called `foo.hpp`: ``` #ifndef __FOO_HPP__ ... #ifndef INCLUDED_FOO_HPP ... #ifndef SOME_OTHER_FORMAT ``` I'm sold on the idea of upper-case #defines but cannot settle on a format for these guards.
I always included the namespace or relative path in the include guard, because only the header name alone has proven to be dangerous. For example, you have some large project with the two files somewhere in your code ``` /myproject/module1/misc.h /myproject/module2/misc.h ``` So if you use a consistent naming schema for your include guards you might end up with having `_MISC_HPP__` defined in both files (very funny to find such errors). So I settled with ``` MYPROJECT_MODULE1_MISC_H_ MYPROJECT_MODULE2_MISC_H_ ``` These names are rather long, but compared with the pain of double definitions it is worth it. Another option, if you don't need compiler/platform independence you might look for some #pragma once stuff.
To truly avoid name collisions, I use GUIDs: ``` #ifndef GUARD_8D419A5B_4AC2_4C34_B16E_2E5199F262ED ```
#include header guard format?
[ "", "c++", "header", "c-preprocessor", "" ]
The situation is somewhat like- ``` var someVar = some_other_function(); someObj.addEventListener("click", function(){ some_function(someVar); }, false); ``` The problem is that the value of `someVar` is not visible inside the listener function of the `addEventListener`, where it is probably being treated as a new variable.
There is absolutely nothing wrong with the code you've written. Both `some_function` and `someVar` should be accessible, in case they were available in the context where anonymous ``` function() { some_function(someVar); } ``` was created. Check if the alert gives you the value you've been looking for, be sure it will be accessible in the scope of anonymous function (unless you have more code that operates on the same `someVar` variable next to the call to `addEventListener`) ``` var someVar; someVar = some_other_function(); alert(someVar); someObj.addEventListener("click", function(){ some_function(someVar); }, false); ```
Why not just get the arguments from the target attribute of the event? Example: ``` const someInput = document.querySelector('button'); someInput.addEventListener('click', myFunc, false); someInput.myParam = 'This is my parameter'; function myFunc(evt) { window.alert(evt.currentTarget.myParam); } ``` ``` <button class="input">Show parameter</button> ``` JavaScript is a prototype-oriented language, remember!
How to pass arguments to addEventListener listener function?
[ "", "javascript", "dom", "addeventlistener", "" ]
Which is the best method to make the browser use cached versions of js files (from the serverside)?
Have a look at Yahoo! tips: <https://developer.yahoo.com/performance/rules.html#expires>. There are also tips by Google: <https://developers.google.com/speed/docs/insights/LeverageBrowserCaching>
or in the .htaccess file ``` AddOutputFilter DEFLATE css js ExpiresActive On ExpiresByType application/x-javascript A2592000 ```
caching JavaScript files
[ "", "javascript", "http", "caching", "" ]
What would be the most efficient data type to store a UUID/GUID in databases that do not have a native UUID/GUID data type? 2 BIGINTs? And what would be the most efficient code (C# preferred) to convert to and from a GUID to that type? Thanks.
It's hard to say what would be the most efficient without knowing the database you are using. My first inclination would be to use a `binary(16)` column. As for using that value in C#, the `System.Guid` type has a constructor that accepts a `byte[]` array, and a method `ToByteArray()` that returns a byte array.
In my experience, the UUID broken up into two integers will still be more efficient than using a char field. Different DBs react in different ways though. Collation could make a difference there too. That being said, there are usually much bigger performance "sins" all over applications, and I don't think that this would be a major thing either way for many applications. You'll have to judge yourself based off of just how busy is this part of your app going to get? Do you need the absolute fastest querying possibly by UUID? Does 600ns vs 400ns a big time difference to you? If there's going to be a lot of manual sql doen with the db, then having a key that's comprising a UUID from separate fields kind of stinks when you need to do an insert and theres no db default for it. That's also a problem with chars though. If you have a database abstraction layer, then combining multiple table fields to get your UUID shouldn't be a big deal.
Most efficient data type for UUID in database besides a native UUID
[ "", "c#", "database", "database-design", "guid", "uuid", "" ]
I am trying to use `set.insert (key)` as a conditional, where if the key is inserted correctly (meaning that the key does NOT already exist in the set ) then it should go on and perform some kind of code. For example, something like: ``` if (set.insert( key )) { // some kind of code } ``` Is this allowed? Because the compiler is throwing this error: ``` conditional expression of type 'std::_Tree<_Traits>::iterator' is illegal ```
The version of insert that takes a single key value should return a `std::pair<iterator,bool>`, where the bool indicates whether an insertion was made. A value of true indicates that the value was inserted, and false indicates that the value was already present. So your conditional would look like this: ``` if( set.insert( key ).second ) { // code } ```
set::insert returns a pair, try this: ``` if( set.insert( key ).second ) { // some kind of code } ```
Using set.insert( key ) as a conditional?
[ "", "c++", "insert", "conditional-statements", "set", "" ]
For a system I need to convert a pointer to a long then the long back to the pointer type. As you can guess this is very unsafe. What I wanted to do is use dynamic\_cast to do the conversion so if I mixed them I'll get a null pointer. This page says <http://publib.boulder.ibm.com/infocenter/lnxpcomp/v7v91/index.jsp?topic=/com.ibm.vacpp7l.doc/language/ref/clrc05keyword_dynamic_cast.htm> > The dynamic\_cast operator performs > type conversions at run time. The > dynamic\_cast operator guarantees the > conversion of a pointer to a base > class to a pointer to a derived class, > or the conversion of an lvalue > referring to a base class to a > reference to a derived class. A > program can thereby use a class > hierarchy safely. This operator and > the typeid operator provide run-time > type information (RTTI) support in > C++. and I'd like to get an error if it's null so I wrote my own dynamic cast ``` template<class T, class T2> T mydynamic_cast(T2 p) { assert(dynamic_cast<T>(p)); return reinterpret_cast<T>(p); } ``` With MSVC I get the error "error C2681: 'long' : invalid expression type for dynamic\_cast". It turns out this will only work with classes which have virtual functions... WTF! I know the point of a dynamic cast was for the up/down casting inheritance problem but I also thought it was to solve the type cast problem dynamically. I know I could use reinterpret\_cast but that doesn't guarantee the same type of safety. What should I use to check if my typecast are the same type? I could compare the two typeid but I would have a problem when I want to typecast a derived to its base. So how can I solve this?
I've had to do similar things when loading C++ DLLs in apps written in languages that only support a C interface. Here is a solution that will give you an immediate error if an unexpected object type was passed in. This can make things much easier to diagnose when something goes wrong. The trick is that every class that you pass out as a handle has to inherit from a common base class. ``` #include <stdexcept> #include <typeinfo> #include <string> #include <iostream> using namespace std; // Any class that needs to be passed out as a handle must inherit from this class. // Use virtual inheritance if needed in multiple inheritance situations. class Base { public: virtual ~Base() {} // Ensure a v-table exists for RTTI/dynamic_cast to work }; class ClassA : public Base { }; class ClassB : public Base { }; class ClassC { public: virtual ~ClassC() {} }; // Convert a pointer to a long handle. Always use this function // to pass handles to outside code. It ensures that T does derive // from Base, and that things work properly in a multiple inheritance // situation. template <typename T> long pointer_to_handle_cast(T ptr) { return reinterpret_cast<long>(static_cast<Base*>(ptr)); } // Convert a long handle back to a pointer. This makes sure at // compile time that T does derive from Base. Throws an exception // if handle is NULL, or a pointer to a non-rtti object, or a pointer // to a class not convertable to T. template <typename T> T safe_handle_cast(long handle) { if (handle == NULL) throw invalid_argument(string("Error casting null pointer to ") + (typeid(T).name())); Base *base = static_cast<T>(NULL); // Check at compile time that T converts to a Base * base = reinterpret_cast<Base *>(handle); T result = NULL; try { result = dynamic_cast<T>(base); } catch(__non_rtti_object &) { throw invalid_argument(string("Error casting non-rtti object to ") + (typeid(T).name())); } if (!result) throw invalid_argument(string("Error casting pointer to ") + typeid(*base).name() + " to " + (typeid(T).name())); return result; } int main() { ClassA *a = new ClassA(); ClassB *b = new ClassB(); ClassC *c = new ClassC(); long d = 0; long ahandle = pointer_to_handle_cast(a); long bhandle = pointer_to_handle_cast(b); // long chandle = pointer_to_handle_cast(c); //Won't compile long chandle = reinterpret_cast<long>(c); // long dhandle = pointer_to_handle_cast(&d); Won't compile long dhandle = reinterpret_cast<long>(&d); // send handle to library //... // get handle back try { a = safe_handle_cast<ClassA *>(ahandle); //a = safe_handle_cast<ClassA *>(bhandle); // fails at runtime //a = safe_handle_cast<ClassA *>(chandle); // fails at runtime //a = safe_handle_cast<ClassA *>(dhandle); // fails at runtime //a = safe_handle_cast<ClassA *>(NULL); // fails at runtime //c = safe_handle_cast<ClassC *>(chandle); // Won't compile } catch (invalid_argument &ex) { cout << ex.what() << endl; } return 0; } ```
`dynamic_cast` can be used only between classes related through inheritance. For converting a pointer to long or vice-versa, you can use `reinterpret_cast`. To check whether the pointer is null, you can `assert(ptr != 0)`. However, it is usually not advisable to use `reinterpret_cast`. Why do you need to convert a pointer to long? Another option is to use a union: ``` union U { int* i_ptr_; long l; } ``` Again, union too is needed only seldom.
Safely checking the type of a variable
[ "", "c++", "dynamic-cast", "" ]
I've got a ant `build.xml` that uses the `<copy>` task to copy a variety of xml files. It uses filtering to merge in properties from a `build.properties` file. Each environment (dev, stage, prod) has a different `build.properties` that stores configuration for that environment. Sometimes we add new properties to the Spring XML or other config files that requires updating the `build.properties` file. I want ant to fail fast if there are properties missing from `build.properties`. That is, if any raw `@...@` tokens make it into the generated files, I want the build to die so that the user knows they need to add one or more properties to their local build.properties. Is this possible with the built in tasks? I couldn't find anything in the docs. I'm about to write a custom ant task, but maybe I can spare myself the effort. Thanks
You can do it in ant 1.7, using a combination of the `LoadFile` task and the `match` condition. ``` <loadfile property="all-build-properties" srcFile="build.properties"/> <condition property="missing-properties"> <matches pattern="@[^@]*@" string="${all-build-properties}"/> </condition> <fail message="Some properties not set!" if="missing-properties"/> ```
If you are looking for a specific property, you can just use the fail task with the unless attribute, e.g.: ``` <fail unless="my.property">Computer says no. You forgot to set 'my.property'!</fail> ``` Refer to [the documentation for Ant's fail task](https://ant.apache.org/manual/Tasks/fail.html "Ant fail documentation") for more detail.
ant filtering - fail if property not set
[ "", "java", "ant", "" ]
I'm building a JSF+Facelets web app, one piece of which is a method that scans a directory every so often and indexes any changes. This method is part of a bean which is in application scope. I have built a subclass of TimerTask to call the method every X milliseconds. My problem is getting the bean initialized. I can reference the bean on a page, and when I go to the page, the bean is initialized, and works as directed; what I would like instead is for the bean to be initialized when the web context is initialized, so that it doesn't require a page visit to start the indexing method. Google has shown a few people that want this functionality, but no real solutions outside of integrating with Spring, which I really don't want to do just to get this piece of functionality. I've tried playing around with both the servlets that have "load-on-startup" set, and a ServletContextListener to get things going, and haven't been able to get the set up right, either because there isn't a FacesContext available, or because I can't reference the bean from the JSF environment. Is there any way to get a JSF bean initialized on web app startup?
If your code calls [FacesContext](http://java.sun.com/javaee/javaserverfaces/1.1_01/docs/api/javax/faces/context/FacesContext.html), it will not work outside a thread associated with a JSF request lifecycle. A FacesContext object is created for every request and disposed at the end of the request. The reason you can fetch it via a [static call](http://java.sun.com/javaee/javaserverfaces/1.1_01/docs/api/javax/faces/context/FacesContext.html#getCurrentInstance()) is because it is set to a [ThreadLocal](http://java.sun.com/j2se/1.4.2/docs/api/java/lang/ThreadLocal.html) at the start of the request. The lifecycle of a FacesContext bears no relation to that of a ServletContext. Maybe this isn't enough (it sounds like you've already been down this route), but you should be able to use a ServletContextListener to do what you want. Just make sure that any calls to the FacesContext are kept in the JSP's request thread. web.xml: ``` <listener> <listener-class>appobj.MyApplicationContextListener</listener-class> </listener> ``` Implementation: ``` public class MyApplicationContextListener implements ServletContextListener { private static final String FOO = "foo"; public void contextInitialized(ServletContextEvent event) { MyObject myObject = new MyObject(); event.getServletContext().setAttribute(FOO, myObject); } public void contextDestroyed(ServletContextEvent event) { MyObject myObject = (MyObject) event.getServletContext().getAttribute( FOO); try { event.getServletContext().removeAttribute(FOO); } finally { myObject.dispose(); } } } ``` You can address this object via the JSF application scope (or just directly if no other variable exists with the same name): ``` <f:view> <h:outputText value="#{applicationScope.foo.value}" /> <h:outputText value="#{foo.value}" /> </f:view> ``` If you wish to retrieve the object in a JSF managed bean, you can get it from the [ExternalContext](http://java.sun.com/javaee/javaserverfaces/1.1_01/docs/api/index.html): ``` FacesContext.getCurrentInstance() .getExternalContext().getApplicationMap().get("foo"); ```
Using listeners or load-on-startup, try this: <http://www.thoughtsabout.net/blog/archives/000033.html>
JSF initialize application-scope bean when context initialized
[ "", "java", "jsf", "" ]
I'm designing a system which is receiving data from a number of partners in the form of CSV files. The files may differ in the number and ordering of columns. For the most part, I will want to choose a subset of the columns, maybe reorder them, and hand them off to a parser. I would obviously prefer to be able to transform the incoming data into some canonical format so as to make the parser as simple as possible. Ideally, I would like to be able to generate a transformation for each incoming data format using some graphical tool and store the transformation as a document in a database or on disk. Upon receival of data, I would apply the correct transformation (never mind how I determine the correct transformation) to get an XML document in a canonical format. If the incoming files had contained XML I would just have created an XSLT document for each format and been on my way. I've used BizTalk's Flat File XSLT Extensions (or whatever they are called) for something similar in the past, but I don't want the hassle of BizTalk (and I can't afford it either) on this project. Does anyone know if there are alternative technologies and/or XSLT extensions which would enable me to achieve my goal in an elegant way? I'm developing my app in C# on .NET 3.5 SP1 (thus would prefer technologies supported by .NET).
XSLT provides new features that make it easier to parse non-XML files. Andrew Welch posted an [XSLT 2.0 example that converts CSV into XML](http://ajwelch.blogspot.com/2007/02/csv-to-xml-converter-in-xslt-20.html)
I think you need something like this (sorry, not supported by .NET but code is very simple) <http://csv2xml.sourceforge.net>
Transforming flat file to XML using XSLT-like technology
[ "", "c#", ".net", "xml", "xslt", "flat-file", "" ]
What is the most recommended/best way to stop multiple instances of a setTimeout function from being created (in javascript)? An example (psuedo code): ``` function mouseClick() { moveDiv("div_0001", mouseX, mouseY); } function moveDiv(objID, destX, destY) { //some code that moves the div closer to destination ... ... ... setTimeout("moveDiv(objID, destX, destY)", 1000); ... ... ... } ``` My issue is that if the user clicks the mouse multiple times, I have multiple instances of moveDiv() getting called. The option I have seen is to create a flag, that only allows the timeout to be called if no other instance is available...is that the best way to go? I hope that makes it clear....
when you call settimeout, it returns you a variable "handle" (a number, I think) if you call settimeout a second time, you should first ``` clearTimeout( handle ) ``` then: ``` handle = setTimeout( ... ) ``` to help automate this, you might use a wrapper that associates timeout calls with a string (i.e. the div's id, or anything you want), so that if there's a previous settimeout with the same "string", it clears it for you automatically before setting it again, You would use an array (i.e. dictionary/hashmap) to associate strings with handles. ``` var timeout_handles = [] function set_time_out( id, code, time ) /// wrapper { if( id in timeout_handles ) { clearTimeout( timeout_handles[id] ) } timeout_handles[id] = setTimeout( code, time ) } ``` There are of course other ways to do this ..
I would do it this way: ``` // declare an array for all the timeOuts var timeOuts = new Array(); // then instead of a normal timeOut call do this timeOuts["uniqueId"] = setTimeout('whateverYouDo("fooValue")', 1000); // to clear them all, just call this function clearTimeouts() { for (key in timeOuts) { clearTimeout(timeOuts[key]); } } // clear just one of the timeOuts this way clearTimeout(timeOuts["uniqueId"]); ```
How do you handle multiple instances of setTimeout()?
[ "", "javascript", "" ]
In regular Java, you can get the text of a stack trace by passing a PrintWriter to printStackTrace. I have a feeling I know the answer to this (i.e. "No") but, Is there any way to obtain the text of a stack trace in JavaME as a String? **Update:** I should mention that I'm restricted to CLDC 1.0
AFAIK there is no way to get the stack trace as a string value, unless a specific platform provides a means to override the default System.err stream. On the BlackBerry platform, it throws out the stack trace on `catch(Exception)` in order to save memory, however it doesn't do this on `catch(Throwable)` and gives access to the stack trace through the device event log. What I've ended up doing is catching Throwable rather than Exception at the last possible moment and printing the stack trace from there. This of course has the danger that you're also catching `java.lang.Error` which isn't very good, especially if its `OutOfMemoryError`, although a call to `System.gc()` before printing the stack trace seems to reduce the risk and we haven't had any problems with it. I'd look at whatever platform you're targeting and see if they give access to System.err somewhere. You can always hook up a debugger and it should appear on the console output, although it sounds like you're after getting stack traces 'in the field'.
two solutions: * reproduce the exception on emulator. the wireless toolkit and Netbeans will print stack traces on your computer. * use a Symbian device. Prior to the Feature Pack 2 of Series 60 3rd edition, Symbian handsets use the Sun Hotspot java virtual machine. It was adapted to Symbian OS by linking it to a partial implementation of the C standard library. This allowed Symbian to create a C++ program called redirector, which was capable of capturing the VM standard output and standard error, including java exception stack traces. the c++ redirector was never upgraded for version 9 of Symbian OS. Instead, a "redirect://" GCF protocol was introduced into the VM, From a separate MIDlet, open an InputStream from the connection returned by Connector.open("redirect://", Connector.READ); you can then capture exception stack traces on Symbian phones. EDIT : "redirect://" is back in Series60 5th edition and "redirect://test" should work on Series60 3rd edition feature pack 2
How to get the text of an exception stack trace in Java ME?
[ "", "java", "java-me", "" ]
I have extensively used Prototype before and it helped us add considerable interactivity to our web applications. However we are looking at making the move to use jQuery in order to standardize on something better supported in Visual Studio. I understand that we can use the jQuery.noConflict to run it alongside Prototype, but we would like to avoid having users need to download both libraries to use our website. So, is there a good resource that can help us move old scripts from Prototype to jQuery?
I can't really help you too much with your question, other than to say that I haven't heard of any such tool, and that I'd be really surprised if one actually existed. While I think jQuery is a great library, and that you're right to be wanting to only use one library, just remember that the cost of you changing over all your scripts is going to be many many hours of work. The cost of your users downloading an extra 30kb of scripts is going to be roughly 0.3 seconds. Perhaps try to slowly phase out Prototype and only refactor your existing pages when a) you have to, or b) if you've got nothing better to do.
Falkayn, There is no automated process available for conversion of JavaScipt code written against one JS library to another one. Moreover there cannot be one. Different libraries implement different proramming models as well as they arrange their APIs in different manner. So, before you have found a solution to your problem now ask yourself a question: Am I going to convert my jQuery code once another even "cooler" "X-type" JavaScript library became available? If your answer is no, take your time and convert the code manually no mater how long will it take. In case you answer "yes" don't convert the code at all. So it goes.
Is there a resource to help convert Prototype JavaScript to jQuery?
[ "", "javascript", "jquery", "asp.net", "visual-studio", "prototypejs", "" ]
My C++ framework has Buttons. A Button derives from Control. So a function accepting a Control can take a Button as its argument. So far so good. I also have List`<`T>. However, List`<`Button> doesn't derive from List`<`Control>, which means a function accepting a list of Controls can't take a list of Buttons as its argument. This is unfortunate. Maybe this is a stupid question, but I don't see how can I solve this :( List`<`Button`>` should derive from List`<`Control`>`, but I don't see a way to make this happen "automatically".
I hate to tell you but if you're using a list of instances to Control instead of pointers to Control, your buttons will be garbage anyway (Google "object slicing"). If they're lists of pointers, then either make the `list<button*>` into `list<control*>` as others have suggested, or do a copy to a new `list<control*>` from the `list<button*>` and pass *that* into the function instead. Or rewrite the function as a template. So if you previously had a function called doSomething that took a list of controls as an argument, you'd rewrite it as: ``` template <class TControl> void doSomething( const std::list<TControl*>& myControls ) { ... whatever the function is currently doing ... } void doSomethingElse() { std::list<Button*> buttons; std::list<Control*> controls; doSomething( buttons ); doSomething( controls ); } ```
Stroustrup has an item on this in his FAQ: [Why can't I assign a `vector<Apple*>` to a `vector<Fruit*>`](http://www.research.att.com/~bs/bs_faq2.html#conversion) You can solve it in two ways: * Make the List contain pointers to `Control` . Then accept `List<Control*>` * Make your function a template. You can still use `List<Button>` and `List<Control>` then, but it's more boilerplate code, and not necassary most of the time. Here is code for the second alternative. The first alternative is already explained by other answers: ``` class MyWindow { template<typename T> void doSomething(List<T> & l) { // do something with the list... if(boost::is_same<Control, T>::value) { // special casing Control } else if(boost::is_same<Button, T>::value) { // special casing Button } } }; ``` To restrict `doSomething` only for `List<derived from Control>`, some more code is needed (look for `enable_if` if you want to know). Note that this kind of code (looking what type you have) is rather to avoid. You should handle such things with virtual functions. Add a function `doSomething` to Control, and override it in Button.
C++ templates and inheritance
[ "", "c++", "inheritance", "templates", "" ]
So, when playing with the development I can just set `settings.DEBUG` to `True` and if an error occures I can see it nicely formatted, with good stack trace and request information. But on kind of production site I'd rather use `DEBUG=False` and show visitors some standard error 500 page with information that I'm working on fixing this bug at this moment ;) At the same time I'd like to have some way of logging all those information (stack trace and request info) to a file on my server - so I can just output it to my console and watch errors scroll, email the log to me every hour or something like this. What logging solutions would you recomend for a django-site, that would meet those simple requirements? I have the application running as `fcgi` server and I'm using apache web server as frontend (although thinking of going to lighttpd).
Well, when `DEBUG = False`, Django will automatically mail a full traceback of any error to each person listed in the `ADMINS` setting, which gets you notifications pretty much for free. If you'd like more fine-grained control, you can write and add to your settings a middleware class which defines a method named `process_exception()`, which will have access to the exception that was raised: <http://docs.djangoproject.com/en/dev/topics/http/middleware/#process-exception> Your `process_exception()` method can then perform whatever type of logging you'd like: writing to console, writing to a file, etc., etc. Edit: though it's a bit less useful, you can also listen for the `got_request_exception` signal, which will be sent whenever an exception is encountered during request processing: <http://docs.djangoproject.com/en/dev/ref/signals/#got-request-exception> This does *not* give you access to the exception object, however, so the middleware method is much easier to work with.
Django Sentry is a good way to go, as already mentioned, but there is a bit of work involved in setting it up properly (as a separate website). If you just want to log everything to a simple text file here's the logging configuration to put in your `settings.py` ``` LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'handlers': { # Include the default Django email handler for errors # This is what you'd get without configuring logging at all. 'mail_admins': { 'class': 'django.utils.log.AdminEmailHandler', 'level': 'ERROR', # But the emails are plain text by default - HTML is nicer 'include_html': True, }, # Log to a text file that can be rotated by logrotate 'logfile': { 'class': 'logging.handlers.WatchedFileHandler', 'filename': '/var/log/django/myapp.log' }, }, 'loggers': { # Again, default Django configuration to email unhandled exceptions 'django.request': { 'handlers': ['mail_admins'], 'level': 'ERROR', 'propagate': True, }, # Might as well log any errors anywhere else in Django 'django': { 'handlers': ['logfile'], 'level': 'ERROR', 'propagate': False, }, # Your own app - this assumes all your logger names start with "myapp." 'myapp': { 'handlers': ['logfile'], 'level': 'WARNING', # Or maybe INFO or DEBUG 'propagate': False }, }, } ```
How do you log server errors on django sites
[ "", "python", "django", "error-logging", "" ]
I want to do some pattern matching on lists in Python. For example, in Haskell, I can do something like the following: ``` fun (head : rest) = ... ``` So when I pass in a list, `head` will be the first element, and `rest` will be the trailing elements. Likewise, in Python, I can automatically unpack tuples: ``` (var1, var2) = func_that_returns_a_tuple() ``` I want to do something similar with lists in Python. Right now, I have a function that returns a list, and a chunk of code that does the following: ``` ls = my_func() (head, rest) = (ls[0], ls[1:]) ``` I wondered if I could somehow do that in one line in Python, instead of two.
So far as I know there's no way to make it a one-liner in current Python without introducing another function, e.g.: ``` split_list = lambda lst: (lst[0], lst[1:]) head, rest = split_list(my_func()) ``` However, in Python 3.0 the specialized syntax used for variadic argument signatures and argument unpacking will become available for this type of general sequence unpacking as well, so in 3.0 you'll be able to write: ``` head, *rest = my_func() ``` See [PEP 3132](https://www.python.org/dev/peps/pep-3132/) for details.
First of all, please note that the "pattern matching" of functional languages and the assignment to tuples you mention are not really that similar. In functional languages the patterns are used to give partial definitions of a function. So `f (x : s) = e` does not mean take the head and tail of the argument of `f` and return `e` using them, but it means that *if* the argument of `f` is of the form `x : s` (for some `x` and `s`), *then* `f (x : s)` is equal to `e`. The assignment of python is more like a multiple assignment (I suspect that was its original intention). So you write, for example, `x, y = y, x` to swap the values in `x` and `y` without needing a temporary variable (as you would with a simple assignment statement). This has little to do with pattern matching as it is basically a shorthand for the "simultaneous" execution of `x = y` and `y = x`. Although python allows arbitrary sequences instead of comma-separated lists, I would not suggest calling this pattern matching. With pattern matching you check whether or not something matches a pattern; in the python assignment you should ensure that the sequences on both sides are the same. To do what you seem to want you would usually (also in functional languages) use either a auxiliary function (as mentioned by others) or something similar to `let` or `where` constructs (which you can regard as using anonymous functions). For example: ``` (head, tail) = (x[0], x[1:]) where x = my_func() ``` Or, in actual python: ``` (head, tail) = (lambda x: (x[0], x[1:]))(my_func()) ``` Note that this is essentially the same as the solutions given by others with an auxiliary function except that this is the one-liner you wanted. It is, however, not necessarily better than a separate function. (Sorry if my answer is a bit over the top. I just think it's important to make the distinction clear.)
Pattern matching of lists in Python
[ "", "python", "functional-programming", "pattern-matching", "" ]
I am trying to get the signature on the method below to work. As this is an Anonymous Type I have some trouble, any help would be great. When I looked at sortedGameList.ToList() in a QuickWatch window I get the signature ``` System.Collections.Generic.List<<>f__AnonymousType0<System.DateTime,System.Linq.IGrouping<System.DateTime,DC.FootballLeague.Web.Models.Game>>> ``` Many Thanks Donald ``` public List<IGrouping<DateTime, Game>> getGamesList(int leagueID) { var sortedGameList = from g in Games group g by g.Date into s select new { Date = s.Key, Games = s }; return sortedGameList.ToList(); } ```
select new { Date = s.Key, Games = s.ToList() }; Edit: thats wrong! I think this will do. ``` public List<IGrouping<DateTime, Game>> getGamesList(int leagueID) { var sortedGameList = from g in Games group g by g.Date; return sortedGameList.ToList(); } ``` And no, you do not need the select!
You shouldn't return anonymous instances. You can't return anonymous types. Make a type (named) and return that: ``` public class GameGroup { public DateTime TheDate {get;set;} public List<Game> TheGames {get;set;} } ``` // ``` public List<GameGroup> getGamesGroups(int leagueID) { List<GameGroup> sortedGameList = Games .GroupBy(game => game.Date) .OrderBy(g => g.Key) .Select(g => new GameGroup(){TheDate = g.Key, TheGames = g.ToList()}) .ToList(); return sortedGameList; } ```
Anonymous Types in a signature
[ "", "c#", "asp.net-mvc", "linq", "anonymous-types", "" ]
Is it ever acceptable to have a [memory leak](http://en.wikipedia.org/wiki/Memory_leak) in your C or C++ application? What if you allocate some memory and use it until the very last line of code in your application (for example, a global object's destructor)? As long as the memory consumption doesn't grow over time, is it OK to trust the OS to free your memory for you when your application terminates (on Windows, Mac, and Linux)? Would this even consider this a real memory leak if the memory was being used continuously until it was freed by the OS? What if a third party library forced this situation on users? Should one refuse to use that third party library no matter how great it otherwise might be? I only see one practical disadvantage, and that is that these benign leaks will show up with memory leak detection tools as false positives.
No. As professionals, the question we should not be asking ourselves is, "Is it ever OK to do this?" but rather "Is there ever a *good* reason to do this?" And "hunting down that memory leak is a pain" isn't a good reason. I like to keep things simple. And the simple rule is that my program should have no memory leaks. That makes my life simple, too. If I detect a memory leak, I eliminate it, rather than run through some elaborate decision tree structure to determine whether it's an "acceptable" memory leak. It's similar to compiler warnings – will the warning be fatal to my particular application? Maybe not. But it's ultimately a matter of professional discipline. Tolerating compiler warnings and tolerating memory leaks is a bad habit that will ultimately bite me in the rear. To take things to an extreme, would it ever be acceptable for a surgeon to leave some piece of operating equipment inside a patient? Although it is possible that a circumstance could arise where the cost/risk of removing that piece of equipment exceeds the cost/risk of leaving it in, and there could be circumstances where it was harmless, if I saw this question posted on SurgeonOverflow.com and saw any answer other than "no," it would seriously undermine my confidence in the medical profession. – If a third party library forced this situation on me, it would lead me to seriously suspect the overall quality of the library in question. It would be as if I test drove a car and found a couple loose washers and nuts in one of the cupholders – it may not be a big deal in itself, but it portrays a lack of commitment to quality, so I would consider alternatives.
I don't consider it to be a memory leak unless the amount of memory being "used" keeps growing. Having some unreleased memory, while not ideal, is not a big problem unless the amount of memory required keeps growing.
Are memory leaks ever OK?
[ "", "c++", "c", "memory-leaks", "" ]
Please tell me if it is possible to do the following: * create an instance of a specific class in Java * pass it to JRuby to do something with it * continue using the "modified" version in Java May you provide a small working example? EDIT: It turns out that embedding was the simplest way to achieve this. More information is available on [Embedding JRuby](http://github.com/jruby/jruby/wiki/RedBridge).
This was the solution I used : [Direct JRuby embedding](https://github.com/jruby/jruby/wiki/RedBridge)
Yes it's possible. [This page](https://github.com/jruby/jruby/wiki/CallingJavaFromJRuby) on the JRuby wiki should get you started.
JRuby and Java objects
[ "", "java", "scripting", "jruby", "jruby-java-interop", "" ]
I'm trying to find the best solution for nonblocking IO via stdin/stdout with the following characteristics: * As long as there is enough data, read in *n*-sized chunks. * If there's not enough data, read in a partial chunk. * If there is no data available, block until there is some (even though it may be smaller than *n*). The goal is to allow efficient transfer for large datasets while processing 'control' codes immediately (instead of having them linger in some partially-filled buffer somewhere). I know I can achieve this by using threads and a istream::get() loop, or by writing a bunch of platform-specific code (since you can't select() on file handles in windows)... ((There is also istream::readsome() which seems promising, but the only results I can find on google were of people saying it doesn't actually work well.)) Since I haven't done much coding w/ these APIs, perhaps there is a better way.
Maybe [boost::asio](http://www.boost.org/doc/libs/1_37_0/doc/html/boost_asio.html) can be of use for you?
I used the threads and platform specific code. See [my answer to another question](https://stackoverflow.com/questions/717572/c-nonblocking-io-on-linux/1280659#1280659). I was able to put the OS-specific stuff in inputAvailable() (Linux uses select, Windows just returns true). I could then use WaitForSingleObject() with a timeout on Windows to try to let the thread complete, then TerminateThread() to kill it. Very ugly, but the team didn't want to use this bit of boost.
Cross-platform (linux/Win32) nonblocking C++ IO on stdin/stdout/stderr
[ "", "c++", "pipe", "stdin", "iostream", "nonblocking", "" ]
How can you convert a byte array to a hexadecimal string and vice versa?
You can use [`Convert.ToHexString`](https://learn.microsoft.com/en-us/dotnet/api/system.convert.tohexstring) starting with .NET 5. There's also a method for the reverse operation: [`Convert.FromHexString`](https://learn.microsoft.com/en-us/dotnet/api/system.convert.fromhexstring). --- For older versions of .NET you can either use: ``` public static string ByteArrayToString(byte[] ba) { StringBuilder hex = new StringBuilder(ba.Length * 2); foreach (byte b in ba) hex.AppendFormat("{0:x2}", b); return hex.ToString(); } ``` or: ``` public static string ByteArrayToString(byte[] ba) { return BitConverter.ToString(ba).Replace("-",""); } ``` There are even more variants of doing it, for example [here](https://social.msdn.microsoft.com/Forums/en-US/csharpgeneral/thread/3928b8cb-3703-4672-8ccd-33718148d1e3/). The reverse conversion would go like this: ``` public static byte[] StringToByteArray(String hex) { int NumberChars = hex.Length; byte[] bytes = new byte[NumberChars / 2]; for (int i = 0; i < NumberChars; i += 2) bytes[i / 2] = Convert.ToByte(hex.Substring(i, 2), 16); return bytes; } ``` --- Using `Substring` is the best option in combination with `Convert.ToByte`. See [this answer](https://stackoverflow.com/a/26304129) for more information. If you need better performance, you must avoid `Convert.ToByte` before you can drop `SubString`.
## Performance Analysis *Note: new leader as of 2015-08-20.* I ran each of the various conversion methods through some crude `Stopwatch` performance testing, a run with a random sentence (n=61, 1000 iterations) and a run with a Project Gutenburg text (n=1,238,957, 150 iterations). Here are the results, roughly from fastest to slowest. All measurements are in ticks ([10,000 ticks = 1 ms](https://msdn.microsoft.com/en-us/library/system.timespan.tickspermillisecond.aspx)) and all relative notes are compared to the [slowest] `StringBuilder` implementation. For the code used, see below or the [test framework repo](https://github.com/patridge/PerformanceStubs) where I now maintain the code for running this. ## Disclaimer *WARNING: Do not rely on these stats for anything concrete; they are simply a sample run of sample data. If you really need top-notch performance, please test these methods in an environment representative of your production needs with data representative of what you will use.* ## Results * [Lookup by byte `unsafe` (via CodesInChaos)](https://stackoverflow.com/a/24343727/48700) (added to test repo by [airbreather](https://github.com/airbreather)) + Text: 4,727.85 (105.2X) + Sentence: 0.28 (99.7X) * [Lookup by byte (via CodesInChaos)](https://stackoverflow.com/a/24343727/48700) + Text: 10,853.96 (45.8X faster) + Sentence: 0.65 (42.7X faster) * [Byte Manipulation 2 (via CodesInChaos)](https://stackoverflow.com/a/14333437/48700) + Text: 12,967.69 (38.4X faster) + Sentence: 0.73 (37.9X faster) * [Byte Manipulation (via Waleed Eissa)](https://stackoverflow.com/a/632920/48700) + Text: 16,856.64 (29.5X faster) + Sentence: 0.70 (39.5X faster) * [Lookup/Shift (via Nathan Moinvaziri)](https://stackoverflow.com/a/5919521/48700) + Text: 23,201.23 (21.4X faster) + Sentence: 1.24 (22.3X faster) * [Lookup by nibble (via Brian Lambert)](https://blogs.msdn.microsoft.com/blambert/2009/02/22/blambertcodesnip-fast-byte-array-to-hex-string-conversion/) + Text: 23,879.41 (20.8X faster) + Sentence: 1.15 (23.9X faster) * [`BitConverter` (via Tomalak)](https://stackoverflow.com/a/311179/48700) + Text: 113,269.34 (4.4X faster) + Sentence: 9.98 (2.8X faster) * [`{SoapHexBinary}.ToString` (via Mykroft)](https://stackoverflow.com/a/2556329/48700) + Text: 178,601.39 (2.8X faster) + Sentence: 10.68 (2.6X faster) * [`{byte}.ToString("X2")` (using `foreach`) (derived from Will Dean's answer)](https://stackoverflow.com/a/311382/48700) + Text: 308,805.38 (2.4X faster) + Sentence: 16.89 (2.4X faster) * [`{byte}.ToString("X2")` (using `{IEnumerable}.Aggregate`, requires System.Linq) (via Mark)](https://stackoverflow.com/a/3824807/48700) + Text: 352,828.20 (2.1X faster) + Sentence: 16.87 (2.4X faster) * [`Array.ConvertAll` (using `string.Join`) (via Will Dean)](https://stackoverflow.com/a/311382/48700) + Text: 675,451.57 (1.1X faster) + Sentence: 17.95 (2.2X faster) * [`Array.ConvertAll` (using `string.Concat`, requires .NET 4.0) (via Will Dean)](https://stackoverflow.com/a/311382/48700) + Text: 752,078.70 (1.0X faster) + Sentence: 18.28 (2.2X faster) * [`{StringBuilder}.AppendFormat` (using `foreach`) (via Tomalak)](https://stackoverflow.com/a/311179/48700) + Text: 672,115.77 (1.1X faster) + Sentence: 36.82 (1.1X faster) * [`{StringBuilder}.AppendFormat` (using `{IEnumerable}.Aggregate`, requires System.Linq) (derived from Tomalak's answer)](https://stackoverflow.com/a/311179/48700) + Text: 718,380.63 (1.0X faster) + Sentence: 39.71 (1.0X faster) Lookup tables have taken the lead over byte manipulation. Basically, there is some form of precomputing what any given nibble or byte will be in hex. Then, as you rip through the data, you simply look up the next portion to see what hex string it would be. That value is then added to the resulting string output in some fashion. For a long time byte manipulation, potentially harder to read by some developers, was the top-performing approach. Your best bet is still going to be finding some representative data and trying it out in a production-like environment. If you have different memory constraints, you may prefer a method with fewer allocations to one that would be faster but consume more memory. ## Testing Code Feel free to play with the testing code I used. A version is included here but feel free to clone the [repo](https://github.com/patridge/PerformanceStubs) and add your own methods. Please submit a pull request if you find anything interesting or want to help improve the testing framework it uses. 1. Add the new static method (`Func<byte[], string>`) to /Tests/ConvertByteArrayToHexString/Test.cs. 2. Add that method's name to the `TestCandidates` return value in that same class. 3. Make sure you are running the input version you want, sentence or text, by toggling the comments in `GenerateTestInput` in that same class. 4. Hit `F5` and wait for the output (an HTML dump is also generated in the /bin folder). ``` static string ByteArrayToHexStringViaStringJoinArrayConvertAll(byte[] bytes) { return string.Join(string.Empty, Array.ConvertAll(bytes, b => b.ToString("X2"))); } static string ByteArrayToHexStringViaStringConcatArrayConvertAll(byte[] bytes) { return string.Concat(Array.ConvertAll(bytes, b => b.ToString("X2"))); } static string ByteArrayToHexStringViaBitConverter(byte[] bytes) { string hex = BitConverter.ToString(bytes); return hex.Replace("-", ""); } static string ByteArrayToHexStringViaStringBuilderAggregateByteToString(byte[] bytes) { return bytes.Aggregate(new StringBuilder(bytes.Length * 2), (sb, b) => sb.Append(b.ToString("X2"))).ToString(); } static string ByteArrayToHexStringViaStringBuilderForEachByteToString(byte[] bytes) { StringBuilder hex = new StringBuilder(bytes.Length * 2); foreach (byte b in bytes) hex.Append(b.ToString("X2")); return hex.ToString(); } static string ByteArrayToHexStringViaStringBuilderAggregateAppendFormat(byte[] bytes) { return bytes.Aggregate(new StringBuilder(bytes.Length * 2), (sb, b) => sb.AppendFormat("{0:X2}", b)).ToString(); } static string ByteArrayToHexStringViaStringBuilderForEachAppendFormat(byte[] bytes) { StringBuilder hex = new StringBuilder(bytes.Length * 2); foreach (byte b in bytes) hex.AppendFormat("{0:X2}", b); return hex.ToString(); } static string ByteArrayToHexViaByteManipulation(byte[] bytes) { char[] c = new char[bytes.Length * 2]; byte b; for (int i = 0; i < bytes.Length; i++) { b = ((byte)(bytes[i] >> 4)); c[i * 2] = (char)(b > 9 ? b + 0x37 : b + 0x30); b = ((byte)(bytes[i] & 0xF)); c[i * 2 + 1] = (char)(b > 9 ? b + 0x37 : b + 0x30); } return new string(c); } static string ByteArrayToHexViaByteManipulation2(byte[] bytes) { char[] c = new char[bytes.Length * 2]; int b; for (int i = 0; i < bytes.Length; i++) { b = bytes[i] >> 4; c[i * 2] = (char)(55 + b + (((b - 10) >> 31) & -7)); b = bytes[i] & 0xF; c[i * 2 + 1] = (char)(55 + b + (((b - 10) >> 31) & -7)); } return new string(c); } static string ByteArrayToHexViaSoapHexBinary(byte[] bytes) { SoapHexBinary soapHexBinary = new SoapHexBinary(bytes); return soapHexBinary.ToString(); } static string ByteArrayToHexViaLookupAndShift(byte[] bytes) { StringBuilder result = new StringBuilder(bytes.Length * 2); string hexAlphabet = "0123456789ABCDEF"; foreach (byte b in bytes) { result.Append(hexAlphabet[(int)(b >> 4)]); result.Append(hexAlphabet[(int)(b & 0xF)]); } return result.ToString(); } static readonly uint* _lookup32UnsafeP = (uint*)GCHandle.Alloc(_Lookup32, GCHandleType.Pinned).AddrOfPinnedObject(); static string ByteArrayToHexViaLookup32UnsafeDirect(byte[] bytes) { var lookupP = _lookup32UnsafeP; var result = new string((char)0, bytes.Length * 2); fixed (byte* bytesP = bytes) fixed (char* resultP = result) { uint* resultP2 = (uint*)resultP; for (int i = 0; i < bytes.Length; i++) { resultP2[i] = lookupP[bytesP[i]]; } } return result; } static uint[] _Lookup32 = Enumerable.Range(0, 255).Select(i => { string s = i.ToString("X2"); return ((uint)s[0]) + ((uint)s[1] << 16); }).ToArray(); static string ByteArrayToHexViaLookupPerByte(byte[] bytes) { var result = new char[bytes.Length * 2]; for (int i = 0; i < bytes.Length; i++) { var val = _Lookup32[bytes[i]]; result[2*i] = (char)val; result[2*i + 1] = (char) (val >> 16); } return new string(result); } static string ByteArrayToHexViaLookup(byte[] bytes) { string[] hexStringTable = new string[] { "00", "01", "02", "03", "04", "05", "06", "07", "08", "09", "0A", "0B", "0C", "0D", "0E", "0F", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "1A", "1B", "1C", "1D", "1E", "1F", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "2A", "2B", "2C", "2D", "2E", "2F", "30", "31", "32", "33", "34", "35", "36", "37", "38", "39", "3A", "3B", "3C", "3D", "3E", "3F", "40", "41", "42", "43", "44", "45", "46", "47", "48", "49", "4A", "4B", "4C", "4D", "4E", "4F", "50", "51", "52", "53", "54", "55", "56", "57", "58", "59", "5A", "5B", "5C", "5D", "5E", "5F", "60", "61", "62", "63", "64", "65", "66", "67", "68", "69", "6A", "6B", "6C", "6D", "6E", "6F", "70", "71", "72", "73", "74", "75", "76", "77", "78", "79", "7A", "7B", "7C", "7D", "7E", "7F", "80", "81", "82", "83", "84", "85", "86", "87", "88", "89", "8A", "8B", "8C", "8D", "8E", "8F", "90", "91", "92", "93", "94", "95", "96", "97", "98", "99", "9A", "9B", "9C", "9D", "9E", "9F", "A0", "A1", "A2", "A3", "A4", "A5", "A6", "A7", "A8", "A9", "AA", "AB", "AC", "AD", "AE", "AF", "B0", "B1", "B2", "B3", "B4", "B5", "B6", "B7", "B8", "B9", "BA", "BB", "BC", "BD", "BE", "BF", "C0", "C1", "C2", "C3", "C4", "C5", "C6", "C7", "C8", "C9", "CA", "CB", "CC", "CD", "CE", "CF", "D0", "D1", "D2", "D3", "D4", "D5", "D6", "D7", "D8", "D9", "DA", "DB", "DC", "DD", "DE", "DF", "E0", "E1", "E2", "E3", "E4", "E5", "E6", "E7", "E8", "E9", "EA", "EB", "EC", "ED", "EE", "EF", "F0", "F1", "F2", "F3", "F4", "F5", "F6", "F7", "F8", "F9", "FA", "FB", "FC", "FD", "FE", "FF", }; StringBuilder result = new StringBuilder(bytes.Length * 2); foreach (byte b in bytes) { result.Append(hexStringTable[b]); } return result.ToString(); } ``` ### Update (2010-01-13) Added Waleed's answer to analysis. Quite fast. ### Update (2011-10-05) Added `string.Concat` `Array.ConvertAll` variant for completeness (requires .NET 4.0). On par with `string.Join` version. ### Update (2012-02-05) Test repo includes more variants such as `StringBuilder.Append(b.ToString("X2"))`. None upset the results any. `foreach` is faster than `{IEnumerable}.Aggregate`, for instance, but `BitConverter` still wins. ### Update (2012-04-03) Added Mykroft's `SoapHexBinary` answer to analysis, which took over third place. ### Update (2013-01-15) Added CodesInChaos's byte manipulation answer, which took over first place (by a large margin on large blocks of text). ### Update (2013-05-23) Added Nathan Moinvaziri's lookup answer and the variant from Brian Lambert's blog. Both rather fast, but not taking the lead on the test machine I used (AMD Phenom 9750). ### Update (2014-07-31) Added @CodesInChaos's new byte-based lookup answer. It appears to have taken the lead on both the sentence tests and the full-text tests. ### Update (2015-08-20) Added [airbreather's](https://github.com/airbreather) optimizations and `unsafe` variant to this [answer's repo](https://github.com/patridge/PerformanceStubs). If you want to play in the unsafe game, you can get some huge performance gains over any of the prior top winners on both short strings and large texts.
How do you convert a byte array to a hexadecimal string, and vice versa?
[ "", "c#", "arrays", "hex", "" ]
When using the [pImpl idiom](http://en.wikipedia.org/wiki/Pimpl_idiom) is it preferable to use a `boost:shared_ptr` instead of a `std::auto_ptr`? I'm sure I once read that the boost version is more exception friendly? ``` class Foo { public: Foo(); private: struct impl; std::auto_ptr<impl> impl_; }; class Foo { public: Foo(); private: struct impl; boost::shared_ptr<impl> impl_; }; ``` [EDIT] Is it always safe to use std::auto\_ptr<> or are there situations when an alternative boost smart pointer is required?
You shouldn't really use std::auto\_ptr for this. The destructor won't be visible at the point you declare the std::auto\_ptr, so it might not be called properly. This is assuming that you are forward declaring your pImpl class, and creating the instance inside the constructor in another file. If you use [boost::scoped\_ptr](http://www.boost.org/doc/libs/1_37_0/libs/smart_ptr/scoped_ptr.htm) (no need for shared\_ptr here, you won't be sharing the pimpl with any other objects, and this is enforced by scoped\_ptr being [noncopyable](http://www.boost.org/doc/libs/1_37_0/libs/utility/utility.htm#Class_noncopyable)), you only need the pimpl destructor visible at the point you call the scoped\_ptr constructor. E.g. ``` // in MyClass.h class Pimpl; class MyClass { private: std::auto_ptr<Pimpl> pimpl; public: MyClass(); }; // Body of these functions in MyClass.cpp ``` Here, the compiler will generate the destructor of MyClass. Which must call auto\_ptr's destructor. At the point where the auto\_ptr destructor is instantiated, Pimpl is an incomplete type. So in to the auto\_ptr destructor when it deletes the the Pimpl object, it won't know how to call the Pimpl destructor. boost::scoped\_ptr (and shared\_ptr) don't have this problem, because when you call the constructor of a scoped\_ptr (or the reset method) it also makes a function-pointer-equivalent that it will use instead of calling delete. The key point here is that it instantiates the deallocation function when Pimpl is not an incomplete type. As a side note, shared\_ptr allows you to specify a [custom deallocation](http://hafizpariabi.blogspot.com/2008/01/using-custom-deallocator-in.html) function, so you can use for it for things like GDI handles or whatever else you may want - but that's overkill for your needs here. If you really want to use std::auto\_ptr, then you need to take extra care by making sure you define your MyClass destructor in MyClass.cpp when Pimpl is fully defined. ``` // in MyClass.h class Pimpl; class MyClass { private: std::auto_ptr<Pimpl> pimpl; public: MyClass(); ~MyClass(); }; ``` and ``` // in MyClass.cpp #include "Pimpl.h" MyClass::MyClass() : pimpl(new Pimpl(blah)) { } MyClass::~MyClass() { // this needs to be here, even when empty } ``` The compiler will generate the code destruct all of the MyClass members effectively 'in' the empty destructor. So at the point the auto\_ptr destructor is instantiated, Pimpl is no longer incomplete and the compiler now knows how to call the destructor. Personally, I don't think it's worth the hassle of making sure everything is correct. There's also the risk that somebody will come along later and tidy up the code by removing the seemingly redundant destructor. So it's just safer all round to go with boost::scoped\_ptr for this kind of thing.
I tend to use `auto_ptr`. Be sure to make your class noncopyable (declare private copy ctor & operator=, or else inherit `boost::noncopyable`). If you use `auto_ptr`, one wrinkle is that you need to define a non-inline destructor, even if the body is empty. (This is because if you let the compiler generate the default destructor, `impl` will be an incomplete type when the call to `delete impl_` is generated, invoking undefined behaviour). There's little to choose between `auto_ptr` & the boost pointers. I tend not to use boost on stylistic grounds if a standard library alternative will do.
std::auto_ptr or boost::shared_ptr for pImpl idiom?
[ "", "c++", "boost", "stl", "shared-ptr", "auto-ptr", "" ]
Does anybody know what's going on here: I run hibernate 3.2.6 against a PostgreSQL 8.3 (installed via fink) database on my Mac OS X. The setup works fine when I use Java 6 and the JDBC 4 driver (postgresql-8.3-603.jdbc4). However, I need this stuff to work with Java 5 and (hence) JDBC 3 (postgresql-8.3-603.jdbc3). When I change the jar in the classpath and switch to Java 5 (I do this in eclipse), I get the following error: ``` Exception in thread "main" org.hibernate.exception.JDBCConnectionException: Cannot open connection at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:74) <Rows clipped for readability> Caused by: java.sql.SQLException: No suitable driver at java.sql.DriverManager.getConnection(DriverManager.java:545) at java.sql.DriverManager.getConnection(DriverManager.java:140) at org.hibernate.connection.DriverManagerConnectionProvider.getConnection(DriverManagerConnectionProvider.java:110) at org.hibernate.jdbc.ConnectionManager.openConnection(ConnectionManager.java:423) ``` What's the problem here? I cannot see it. Here is my hibernate configuration: ``` <hibernate-configuration> <session-factory> <property name="connection.url">jdbc:postgresql:test</property> <property name="connection.username">postgres</property> <property name="connection.password">p</property> <property name="connection.pool_size">1</property> <property name="dialect">org.hibernate.dialect.PostgreSQLDialect</property> <property name="current_session_context_class">thread</property> <property name="show_sql">true</property> <mapping resource="com/mydomain/MyClass.hbm.xml"/> </session-factory> </hibernate-configuration> ``` **EDIT:** The longer, more usual form of the connection URL: *jdbc:postgresql://localhost/test* has the exact same behaviour. The driver jar is definitely in the classpath, and I also do not manage to get any errors with this direct JDBC test code: ``` public static void main(String[] args) throws Exception { Class.forName("org.postgresql.Driver"); Connection con=DriverManager.getConnection("jdbc:postgresql://localhost/test","postgres", "p"); } ```
I don't see you specifying the driver class in your Hibernate configuration. Try adding the following: ``` <hibernate-configuration> <session-factory> . . <property name="connection.driver_class">org.postgresql.Driver</property> . </session-factory> </hibernate-configuration> ```
did you notice that the connection url is incomplete ``` <property name="connection.url">jdbc:postgresql:test</property> ``` as opposed to ``` <property name="connection.url">jdbc:postgresql://localhost/test</property> ```
"No suitable driver" problem with Hibernate3, PostgreSQL 8.3 and Java 5
[ "", "java", "hibernate", "postgresql", "" ]
I'm not sure what the best api for simple 2d graphics with Java is. I know `java.awt.Graphics2D` was the standard but has it been replaced? Swing is the new API for Java GUI apps but it seems a bit heavy for what I want. What I really want is something like the C [SDL library](http://libsdl.org/).
[Java 2D](http://docs.oracle.com/javase/tutorial/2d/) (`Graphics2D` and friends) is indeed the best choice that I know of. Swing is actually implemented on top of Java 2D, so yes, if you want non-GUI-type graphics, Java 2D is the way to go.
If you want to have the least work possible if you're building a game (or even if not) use <http://slick.cokeandcode.com/> UPDATE: The link has since changed to <http://slick.ninjacave.com/>
Best API for simple 2D graphics with Java
[ "", "java", "graphics", "java-2d", "" ]
I'm writing a GreaseMonkey script where I'm iterating through a bunch of elements. For each element, I need a string ID that I can use to reference that element later. The element itself doesn't have an `id` attribute, and I can't modify the original document to give it one (although I can make DOM changes in my script). I can't store the references in my script because when I need them, the GreaseMonkey script itself will have gone out of scope. Is there some way to get at an "internal" ID that the browser uses, for example? A Firefox-only solution is fine; a cross-browser solution that could be applied in other scenarios would be awesome. Edit: * **If the GreaseMonkey script is out of scope, how are you referencing the elements later?** They GreaseMonkey script is adding events to DOM objects. I can't store the references in an array or some other similar mechanism because when the event fires, the array will be gone because the GreaseMonkey script will have gone out of scope. So the event needs some way to know about the element reference that the script had when the event was attached. And the element in question is not the one to which it is attached. * **Can't you just use a custom property on the element?** Yes, but the problem is on the lookup. I'd have to resort to iterating through all the elements looking for the one that has that custom property set to the desired id. That would work, sure, but in large documents it could be very time consuming. I'm looking for something where the browser can do the lookup grunt work. * **Wait, can you or can you not modify the document?** I can't modify the source document, but I can make DOM changes in the script. I'll clarify in the question. * **Can you not use closures?** Closuses did turn out to work, although I initially thought they wouldn't. See my later post. It sounds like the answer to the question: "Is there some internal browser ID I could use?" is "No."
**UPDATE:** Closures are indeed the answer. So after fiddling with it some more, I figured out why closures were initially problematic and how to fix it. The tricky thing with a closure is you have to be careful when iterating through the elements not to end up with all of your closures referencing the same element. For example, this doesn't work: ``` for (var i = 0; i < elements.length; i++) { var element = elements[i]; var button = document.createElement("button"); button.addEventListener("click", function(ev) { // do something with element here }, false) } ``` But this does: ``` var buildListener = function(element) { return function(ev) { // do something with event here }; }; for (var i = 0; i < elements.length; i++) { var element = elements[i]; var button = document.createElement("button"); button.addEventListener("click", buildListener(element), false) } ``` Anyway, I decided not to select one answer because the question had two answers: 1) No, there are no internal IDs you can use; 2) you should use closures for this. So I simply upvoted the first people to say whether there were internal IDs or who recommended generating IDs, plus anyone who mentioned closures. Thanks for the help!
Closure is the way to go. This way you'll have exact reference to the element that even will survive some shuffling of DOM. Example for those who don't know closures: ``` var saved_element = findThatDOMNode(); document.body.onclick = function() { alert(saved_element); // it's still there! } ``` *If* you had to store it in a cookie, then I recommend computing XPath for it (e.g. walk up the DOM counting previous siblings until you find element with an ID and you'll end up with something like `[@id=foo]/div[4]/p[2]/a`). [XPointer](http://www.w3.org/TR/WD-xptr) is W3C's solution to that problem.
Unique element ID, even if element doesn't have one
[ "", "javascript", "firefox", "dom", "greasemonkey", "" ]
I was running some dynamic programming code (trying to brute-force disprove the Collatz conjecture =P) and I was using a dict to store the lengths of the chains I had already computed. Obviously, it ran out of memory at some point. Is there any easy way to use some variant of a `dict` which will page parts of itself out to disk when it runs out of room? Obviously it will be slower than an in-memory dict, and it will probably end up eating my hard drive space, but this could apply to other problems that are not so futile. I realized that a disk-based dictionary is pretty much a database, so I manually implemented one using sqlite3, but I didn't do it in any smart way and had it look up every element in the DB one at a time... it was about 300x slower. Is the smartest way to just create my own set of dicts, keeping only one in memory at a time, and paging them out in some efficient manner?
Hash-on-disk is generally addressed with Berkeley DB or something similar - several options are listed in the [Python Data Persistence documentation](http://docs.python.org/library/persistence.html). You can front it with an in-memory cache, but I'd test against native performance first; with operating system caching in place it might come out about the same.
The 3rd party [shove](http://pypi.python.org/pypi/shove) module is also worth taking a look at. It's very similar to shelve in that it is a simple dict-like object, however it can store to various backends (such as file, SVN, and S3), provides optional compression, and is even threadsafe. It's a very handy module ``` from shove import Shove mem_store = Shove() file_store = Shove('file://mystore') file_store['key'] = value ```
Python Disk-Based Dictionary
[ "", "python", "database", "dictionary", "disk-based", "" ]
I need to share SSO information between two different domains with a cookie, can this be done in PHP and how?
On both domains, place an image or other web element that is pulled from the other domain. Use the URL to notify the other domain that user X is on domain A, and let domain B associate that user ID with that user on their system. It's a little complex to carry out correctly, but if you think it through it'll work out very well. Vinko points out in a comment (thanks!) that I shouldn't take it for granted that you understand the security risks involved. If this information is of any value to anyone, then you should make sure you use proper encryption, authentication, etc to avoid releasing sensitive information and to avoid various attacks (replay, man in the middle, etc). This shouldn't be too onerous since you control both websites and you can select a secure secret key for both, since the communication is only going between the two servers via this special URL. Keep it in mind though. -Adam
You don't, cookies are bound to a domain. There are restrictions on this and it's referred to as cross site scripting. Now, for some help to your problem. What you can do is create a script that helps bridge them. You can globally rewrite all links to your second site are going to need cookie information from the first site. You would save all the cookies from site-a to a database that they both can read, then programatically appending the cookie-id querystring on all of the links to site-b, then you lookup that cookie id and re-set the cookies under the new domain. There is a really good PHP database abstraction library ([PHP ADODB](http://adodb.sourceforge.net/)) and it has a session sharing plugin that makes all of this a whole lot easier.
How do I use cookies across two different domains?
[ "", "php", "cookies", "" ]
I am attempting to insert a copy of a row from one table into another table with the same schema, with the addition of one column (a timestamp) to provide a "history" of the first table in MS Sql Server 2005. So, my query, without the additional column would be: ``` "SELECT INTO [WebsiteHistory] FROM [Website]" ``` I want to populate the timestamp column as well, but am not sure how to best do this. I'd like to do something like: ``` "SELECT Website.*, '" + DateTime.Now.ToShortDateString() + "' INTO [WebsiteHistory] FROM [Website]" ``` But that shouldn't work, especially if the timestamp column is not the last one. Is there any way to do this?
Be warned. This works, but it is neither *nice* nor recommendable: ``` INSERT WebsiteHistory SELECT *, GETDATE() FROM Website WHERE Id = @WebsiteId ``` This assumes `WebsiteHistory` has the same structure as `Website` (you said it has), plus there is one additional `DATETIME` field. Better is this, because it is much more fail-safe (at the expense of being more verbose): ``` INSERT WebsiteHistory ( Id, Field1, Field2, Field3, Field4, ModifiedDate ) SELECT Id, Field1, Field2, Field3, Field4, GETDATE() FROM Website WHERE Id = @WebsiteId ```
Can't you set a default constraint on the column that would automatically populate the timestamp column when a row is inserted to the table?
SELECT INTO with an additional column
[ "", ".net", "sql", "sql-server-2005", "t-sql", "" ]
I want to build two-dimentional array of strings where length of one dimention is 2. Similar to this ``` string[,] array = new string[,] { {"a", "b"}, {"c", "d"}, {"e", "f"}, {"g", "h"} } ``` Doing ``` List<string[]> list = new List<string[]>(); list.Add(new string[2] {"a", "b"}); list.Add(new string[2] {"c", "d"}); list.Add(new string[2] {"e", "f"}); list.Add(new string[2] {"g", "h"}); list.ToArray(); ``` gives me ``` string[][] ``` but not ``` string[,] ``` array. Just curious, is there some trick to build dynamically ``` string[,] ``` array somehow?
Well, you could reasonably easily write an extension method to do it. Something like this (only tested very slightly): ``` public static T[,] ToRectangularArray<T>(this IEnumerable<T[]> source) { if (!source.Any()) { return new T[0,0]; } int width = source.First().Length; if (source.Any(array => array.Length != width)) { throw new ArgumentException("All elements must have the same length"); } T[,] ret = new T[source.Count(), width]; int row = 0; foreach (T[] array in source) { for (int col=0; col < width; col++) { ret[row, col] = array[col]; } row++; } return ret; } ``` It's a slight shame that the above code uses T[] as the element type. Due to generic invariance I can't currently make source `IEnumerable<IEnumerable<T>>` which would be nice. An alternative might be to introduce a new type parameter with a constraint: ``` public static T[,] ToRectangularArray<T,U>(this IEnumerable<U> source) where U : IEnumerable<T> ``` Somewhat hairy, but it should work. (Obviously the implementation needs some changes too, but the basic principle is the same.)
You can do this. ``` List<KeyValuePair<string, string>> ``` The idea being that the Key Value Pair would mimic the array of strings you replicated.
Is there a way to define a List<> of two elements string array?
[ "", "c#", "arrays", "generics", "data-structures", "" ]
I'm fairly new to c# so that's why I'm asking this here. I am consuming a web service that returns a long string of XML values. Because this is a string all the attributes have escaped double quotes ``` string xmlSample = "<root><item att1=\"value\" att2=\"value2\" /></root>" ``` Here is my problem. I want to do a simple string.replace. If I was working in PHP I'd just run strip\_slashes(). However, I'm in C# and I can't for the life of me figure it out. I can't write out my expression to replace the double quotes (") because it terminates the string. If I escape it then it has incorrect results. What am I doing wrong? ``` string search = "\\\""; string replace = "\""; Regex rgx = new Regex(search); string strip = rgx.Replace(xmlSample, replace); //Actual Result <root><item att1=value att2=value2 /></root> //Desired Result <root><item att1="value" att2="value2" /></root> ``` > MizardX: To include a quote in a raw string you need to double it. That's important information, trying that approach now...No luck there either There is something going on here with the double quotes. The concepts you all are suggesting are solid, BUT the issue here is dealing with the double quotes and it looks like I'll need to do some additional research to solve this problem. If anyone comes up with something please post an answer. ``` string newC = xmlSample.Replace("\\\"", "\""); //Result <root><item att=\"value\" att2=\"value2\" /></root> string newC = xmlSample.Replace("\"", "'"); //Result newC "<root><item att='value' att2='value2' /></root>" ```
the following statement in C# ``` string xmlSample = "<root><item att1=\"value\" att2=\"value2\" /></root>" ``` will actually store the value ``` <root><item att1="value" att2="value2" /></root> ``` whereas ``` string xmlSample = @"<root><item att1=\""value\"" att2=\""value2\"" /></root>"; ``` have the value of ``` <root><item att1=\"value\" att2=\"value2\" /></root> ``` for the second case, you need to replace the slash () by empty string as follow ``` string test = xmlSample.Replace(@"\", string.Empty); ``` the result will be ``` <root><item att1="value" att2="value2" /></root> ``` P.S. 1. slash (`\`) is default escape character in C# 2. to ignore slashes, use @ at the beginning of string 3. if @ is used, the escape character is double quote (")
There's no reason to use a Regular expression at all... that's a lot heavier than what you need. ``` string xmlSample = "blah blah blah"; xmlSample = xmlSample.Replace("\\\", "\""); ```
C# String.Replace double quotes and Literals
[ "", "c#", "xml", "" ]
I'm wondering if I'm missing something about Java Beans. I like my objects to do as much initialization in the constructor as possible and have a minimum number of mutators. Beans seem to go directly against this and generally feel clunky. What capabilities am I missing out on by not building my objects as Beans?
It sounds like you are on the right track. It's not you who's missing the point of Java Beans, it is other programmers that are misusing them. The Java Beans specification was designed to be used with visual tools. The idea was that an application designer would be able to configure an instance of an object interactively, then serialize (or generate code for) the configured bean, so that it could be reconstructed at runtime; the intent was that it would not be mutated at runtime. Unfortunately, a lot of developers don't understand that [accessors violate encapsulation](https://www.infoworld.com/article/2073723/why-getter-and-setter-methods-are-evil.html). They use structs instead of objects. They don't see anything wrong with other classes, even other packages, having dependencies on a class's data members. Of course, you will in general have the need to configure instances of your objects. It's just that this should be done through some sort of configuration feature. This might be a dependency injection container, a "BeanBox" style visual tool, or simply reading JSON, XML, or properties files that you wrote by hand. The key is that at runtime these objects are effectively immutable; clients just invoke their operations, they don't access their properties.
> I like my objects to do as much > initialization in the constructor as > possible and have a minimum number of > mutators. Favouring immutable objects is a wise choice. However the benefit of beans is that frameworks/tools/libraries can determine at runtime the properties of a class, without requiring you to implement a particular interface. For example, assume you have a collection of Person beans, and each bean has properties such as name, age, height, etc. You can sort this collection of beans by name (for example) using the following code: ``` Collection<Person> myCollection = // initialise and populate the collection Comparator nameCompare = new BeanComparator("name"); Collections.sort(myCollection, nameCompare); ``` The [BeanComparator](http://commons.apache.org/beanutils/commons-beanutils-1.6.1/docs/api/org/apache/commons/beanutils/BeanComparator.html) class knows how to extract the "name" property from each object, because the Java Beans convention is followed, i.e. you're spared the "overhead" of implementing an interface such as: ``` interface Nameable { public String getName(); public void setName(String name); } ``` Another example from Spring MVC is a bean that stores request URL parameters. This can be defined in a web controller (known as an 'Action' in Struts) like this: ``` public ModelAndView searchUsers(UserSearchCriteria criteria) { // implementation omitted } ``` Because UserSearchCriteria is expected to be a JavaBean, if the request URL contains a parameter such as `maxItems=6`, the Spring framework 'knows' that it should call a method with the signature ``` void setMaxItems(int maxItems); ``` In essence, JavaBeans is just a simple convention which allows the properties of a class to be discovered dynamically at runtime (usually by a tool or framework), when it's inconvenient/impossible to know a priori the properties that may be provided.
Java Beans: What am I missing?
[ "", "java", "javabeans", "" ]
Is there anything to use, to determine if a type is actually a anonymous type? For example an interface, etc? The goal is to create something like the following... ``` //defined like... public static T Get<T>(this IAnonymous obj, string prop) { return (T)obj.GetType().GetProperty(prop).GetValue(obj, null); } //... //And then used like... var something = new { name = "John", age = 25 }; int age = something.Get<int>("age"); ``` Or is that just the beauty of an anonymous type? Nothing to identify it self because it takes a new shape? **Note** - I realize that you can write an extension method for the **object** class, but that seems like a little overkill, in my opinion.
EDIT: The list below applies to C# anonymous types. VB.NET has different rules - in particular, it can generate mutable anonymous types (and does by default). Jared has pointed out in the comment that the naming style is different, too. Basically this is all pretty fragile... You can't identify it in a generic constraint, but: * It will be a class (rather than interface, enum, struct etc) * It will have the [CompilerGeneratedAttribute](http://msdn.microsoft.com/en-us/library/system.runtime.compilerservices.compilergeneratedattribute.aspx) applied to it * It will override Equals, GetHashCode and ToString * It will be in the global namespace * It will not be nested in another type * It will be internal * It will be sealed * It will derive directly from `object` * It will be generic with as many type parameters as properties. (You *can* have a non-generic anonymous type, with no properties. It's a bit pointless though.) * Each property will have a type parameter with a name including the property name, and will be of that type parameter, e.g. the Name property becomes a property of type <>\_Name * Each property will be public and read-only * For each property there will be a corresponding readonly private field * There will be no other properties or fields * There will be a constructor taking one parameter corresponding to each type parameter, in the same order as the type parameters * Each method and property will have the [DebuggerHiddenAttribute](http://msdn.microsoft.com/en-us/library/system.diagnostics.debuggerhiddenattribute.aspx) applied to it. * The name of the type will start with "<>" and contain "AnonymousType" Very little of this is guaranteed by the specification, however - so it could all change in the next version of the compiler, or if you use Mono etc.
As I recall, there is a [`[CompilerGenerated]`](http://msdn.microsoft.com/en-us/library/system.runtime.compilerservices.compilergeneratedattribute.aspx) marker... 2 secs Plus the name will be freaky, and it will be a generic type ;-p Actually, for a "get" etc I would probably just use a static (non-extension) method. If you just want a way to get the value from an instance of an anon-type (at a later point in time), a lambda is probably the best option - note you need a few tricks to pull this off: ``` static void Main() { var foo = new { name = "John", age = 25 }; var func = Get(foo, x => x.age); var bar = new { name = "Marc", age = 30 }; int age = func(bar); } // template here is just for type inference... static Func<TSource, TValue> Get<TSource, TValue>( TSource template, Func<TSource, TValue> lambda) { return lambda; } ``` (edit re the comment) There definitely *is* this attribute: ``` var foo = new { A = "B" }; Type type = foo.GetType(); CompilerGeneratedAttribute attrib = (CompilerGeneratedAttribute) Attribute.GetCustomAttribute( type, typeof(CompilerGeneratedAttribute)); // non-null, therefore is compiler-generated ```
Anonymous Types - Are there any distingushing characteristics?
[ "", "c#", ".net", "generics", "extension-methods", "anonymous-types", "" ]
Is it possible? By debug I mean setting breakpoints, inspect values and advance step by step.
You can do remote debugging of python web apps over TCP/IP with [winpdb](http://winpdb.org/). (Link appears down as of June 2019. Try [PyPI winpdb](https://pypi.org/project/winpdb/))
I haven't used web2py, but if it runs in a terminal window, you can use standard pdb stuff. Add this line somewhere in your code: ``` import pdb; pdb.set_trace() ``` This will invoke the debugger and break. Then you can use [PDB](http://docs.python.org/lib/module-pdb.html) commands: n to step to the next line, l to list code, s to step into a function, p to print values, etc.
How to debug Web2py applications?
[ "", "python", "debugging", "web2py", "" ]
I am migrating an application from .NET 1.1 to .NET 2.0. Should I remove all uses of CollectionBase? If so, what is the best strategy for migration?
Yes, the best classes to look at are in System.Collections.Generic. I usually use List. There are two approaches you can use either: **A** ``` public class MyClass { public List<MyItem> Items; } ``` **B** ``` public class MyItemCollection : List<MyItem> { } public class MyClass { public MyItemCollection Items; } ``` The two approaches only differ very slightly and you only need to use method (B) if you plan on extending the functionality of List. Here's a link with more info: <http://msdn.microsoft.com/en-us/library/6sh2ey19(VS.80).aspx> With regards to the classes that you've already implemented, you can remove all of the functions which are specified in the IList interface. e.g. ``` public int Add(InstrumentTradeDataRow instTrade) { return List.Add(instTrade); } ``` This can be removed because List already implements a type safe Add function for you. See this link for more information: <http://msdn.microsoft.com/en-us/library/3wcytfd1(VS.80).aspx>
Generally, `List<T>` does most of what you normally want. If you want to customize behaviour, you should inherit from `Collection<T>` - this has `virtual` methods so you can tweak behaviour when adding/removing/updating etc. You can't do this with `List<T>` since there are no (uesful) `virtual` methods.
CollectionBase vs generics
[ "", "c#", ".net", "generics", "" ]
I'm looking for a production quality bloom filter implementation in Python to handle fairly large numbers of items (say 100M to 1B items with 0.01% false positive rate). [Pybloom](http://www.imperialviolet.org/pybloom.html) is one option but it seems to be showing its age as it throws DeprecationWarning errors on Python 2.5 on a regular basis. Joe Gregorio also has [an implementation](http://bitworking.org/news/380/bloom-filter-resources). Requirements are fast lookup performance and stability. I'm also open to creating Python interfaces to particularly good c/c++ implementations, or even to Jython if there's a good Java implementation. Lacking that, any recommendations on a bit array / bit vector representation that can handle ~16E9 bits?
Eventually I found [pybloomfiltermap](http://github.com/axiak/pybloomfiltermmap). I haven't used it, but it looks like it'd fit the bill.
I recently went down this path as well; though it sounds like my application was slightly different. I was interested in approximating set operations on a large number of strings. You do make the key observation that a **fast** bit vector is required. Depending on what you want to put in your bloom filter, you may also need to give some thought to the speed of the hashing algorithm(s) used. You might find this [library](http://www.partow.net/programming/hashfunctions/index.html) useful. You may also want to tinker with the random number technique used below that only hashes your key a single time. In terms of non-Java bit array implementations: * Boost has [dynamic\_bitset](http://www.boost.org/doc/libs/1_37_0/libs/dynamic_bitset/dynamic_bitset.html) * Java has the built in [BitSet](http://java.sun.com/javase/6/docs/api/java/util/BitSet.html) I built my bloom filter using [BitVector](http://cobweb.ecn.purdue.edu/~kak/dist/). I spent some time profiling and optimizing the library and contributing back my patches to Avi. Go to that BitVector link and scroll down to acknowledgments in v1.5 to see details. In the end, I realized that performance was not a goal of this project and decided against using it. Here's some code I had lying around. I may put this up on google code at python-bloom. Suggestions welcome. ``` from BitVector import BitVector from random import Random # get hashes from http://www.partow.net/programming/hashfunctions/index.html from hashes import RSHash, JSHash, PJWHash, ELFHash, DJBHash # # ryan.a.cox@gmail.com / www.asciiarmor.com # # copyright (c) 2008, ryan cox # all rights reserved # BSD license: http://www.opensource.org/licenses/bsd-license.php # class BloomFilter(object): def __init__(self, n=None, m=None, k=None, p=None, bits=None ): self.m = m if k > 4 or k < 1: raise Exception('Must specify value of k between 1 and 4') self.k = k if bits: self.bits = bits else: self.bits = BitVector( size=m ) self.rand = Random() self.hashes = [] self.hashes.append(RSHash) self.hashes.append(JSHash) self.hashes.append(PJWHash) self.hashes.append(DJBHash) # switch between hashing techniques self._indexes = self._rand_indexes #self._indexes = self._hash_indexes def __contains__(self, key): for i in self._indexes(key): if not self.bits[i]: return False return True def add(self, key): dupe = True bits = [] for i in self._indexes(key): if dupe and not self.bits[i]: dupe = False self.bits[i] = 1 bits.append(i) return dupe def __and__(self, filter): if (self.k != filter.k) or (self.m != filter.m): raise Exception('Must use bloom filters created with equal k / m paramters for bitwise AND') return BloomFilter(m=self.m,k=self.k,bits=(self.bits & filter.bits)) def __or__(self, filter): if (self.k != filter.k) or (self.m != filter.m): raise Exception('Must use bloom filters created with equal k / m paramters for bitwise OR') return BloomFilter(m=self.m,k=self.k,bits=(self.bits | filter.bits)) def _hash_indexes(self,key): ret = [] for i in range(self.k): ret.append(self.hashes[i](key) % self.m) return ret def _rand_indexes(self,key): self.rand.seed(hash(key)) ret = [] for i in range(self.k): ret.append(self.rand.randint(0,self.m-1)) return ret if __name__ == '__main__': e = BloomFilter(m=100, k=4) e.add('one') e.add('two') e.add('three') e.add('four') e.add('five') f = BloomFilter(m=100, k=4) f.add('three') f.add('four') f.add('five') f.add('six') f.add('seven') f.add('eight') f.add('nine') f.add("ten") # test check for dupe on add assert not f.add('eleven') assert f.add('eleven') # test membership operations assert 'ten' in f assert 'one' in e assert 'ten' not in e assert 'one' not in f # test set based operations union = f | e intersection = f & e assert 'ten' in union assert 'one' in union assert 'three' in intersection assert 'ten' not in intersection assert 'one' not in intersection ``` Also, in my case I found it useful to have a faster count\_bits function for BitVector. Drop this code into BitVector 1.5 and it should give you a more performant bit counting method: ``` def fast_count_bits( self, v ): bits = ( 0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4, 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, 4, 5, 5, 6, 5, 6, 6, 7, 5, 6, 6, 7, 6, 7, 7, 8 ) return bits[v & 0xff] + bits[(v >> 8) & 0xff] + bits[(v >> 16) & 0xff] + bits[v >> 24] ```
Modern, high performance bloom filter in Python?
[ "", "python", "jython", "bloom-filter", "" ]
i'm generating controls dynamically on my asp.net page by xslt transformation from an xml file. i will need to reference these controls from code behind later. i would like to add these references to the list/hashtable/whatever during creation (in xslt file i suppose) so that i could reach them later and i have no idea how to do this. i will be absolutely grateful for any suggestions, agnieszka
Once you have transformed your XML using XSLT, you could pass the output to the ASP.Net [ParseControl](http://msdn.microsoft.com/en-us/library/kz3ffe28.aspx) method and it will return your controls ready to use. For example this code will place two buttons on the page: ``` protected void Page_Load(object sender, EventArgs e) { // Fetch your XML here and transform it. This string represents // the transformed output string content = @" <asp:Button runat=""server"" Text=""Hello"" /> <asp:Button runat=""server"" Text=""World"" />"; var controls = ParseControl(content); foreach (var control in controls) { // Wire up events, change settings etc here } // placeHolder is simply an ASP.Net PlaceHolder control on the page // where I would like the controls to end up placeHolder.Controls.Add(controls); } ```
Can you give a better idea of what you are trying to do? XML > XSLT > produces aspx page Sounds close to reinventing the windows presentation framework or XUL Or is it ASPX reads xml > uses XSLT to add DOM elements to page... Sounds like AJAX You want to write out a unique ID using the attribute transform <http://www.w3schools.com/XSL/el_attribute.asp>
ASP.NET - controls generated by xslt transformation
[ "", "c#", "asp.net", "xml", "xslt", "" ]
I am new to mysqli, and trying to confirm that if I so something like the below, the errno will be set to the last error, if any, and not the error of the last query. Is this a decent practice or should I be checking for the error in between every query? Thanks! ``` $mysqli->autocommit(FALSE); $mysqli->query("INSERT INTO ....."); $mysqli->query("INSERT INTO ....."); $mysqli->query("INSERT INTO ....."); $mysqli->query("INSERT INTO ....."); $mysqli->query("INSERT INTO ....."); if ( 0==$mysqli->errno ) { $mysqli->commit(); } else { $mysqli->rollback(); // Handle error } ```
mysqli\_errno — Returns the error code for **the most recent function call**.
No -- it reports the error code of the last mysqli function call. Zero means no error occurred on the last function call. So if one in the middle fails, you won't know about it by checking only at the end. In other words, yes, you need to check the error code after each function call. Note that an error is indicated by the return value of `$mysqli->query()` as well. Paraphrasing the example from the [mysqli\_errno](http://php.net/mysqli.errno) doc: ``` if (!$mysqli->query("INSERT ...")) { printf("Errorcode: %d\n", $mysqli->errno); } ```
mysqli->error: Is it for the last query only, or for the last error from the query group?
[ "", "php", "mysql", "mysqli", "transactions", "" ]
How can I compare strings in a case insensitive way in Python? I would like to encapsulate comparison of a regular strings to a repository string, using simple and Pythonic code. I also would like to have ability to look up values in a dict hashed by strings using regular python strings.
Assuming ASCII strings: ``` string1 = 'Hello' string2 = 'hello' if string1.lower() == string2.lower(): print("The strings are the same (case insensitive)") else: print("The strings are NOT the same (case insensitive)") ``` As of Python 3.3, [casefold()](https://docs.python.org/3/library/stdtypes.html#str.casefold) is a better alternative: ``` string1 = 'Hello' string2 = 'hello' if string1.casefold() == string2.casefold(): print("The strings are the same (case insensitive)") else: print("The strings are NOT the same (case insensitive)") ``` If you want a more comprehensive solution that handles more complex unicode comparisons, see other answers.
Comparing strings in a case insensitive way seems trivial, but it's not. I will be using Python 3, since Python 2 is underdeveloped here. The first thing to note is that case-removing conversions in Unicode aren't trivial. There is text for which `text.lower() != text.upper().lower()`, such as `"ß"`: ``` >>> "ß".lower() 'ß' >>> "ß".upper().lower() 'ss' ``` But let's say you wanted to caselessly compare `"BUSSE"` and `"Buße"`. Heck, you probably also want to compare `"BUSSE"` and `"BUẞE"` equal - that's the newer capital form. The recommended way is to use [`casefold`](https://docs.python.org/3/library/stdtypes.html#str.casefold): > str.**casefold**() > > Return a casefolded copy of the string. Casefolded strings may be used for > caseless matching. > > Casefolding is similar to lowercasing but more aggressive because it is > intended to remove all case distinctions in a string. [...] Do not just use `lower`. If `casefold` is not available, doing `.upper().lower()` helps (but only somewhat). Then you should consider accents. If your font renderer is good, you probably think `"ê" == "ê"` - but it doesn't: ``` >>> "ê" == "ê" False ``` This is because the accent on the latter is a combining character. ``` >>> import unicodedata >>> [unicodedata.name(char) for char in "ê"] ['LATIN SMALL LETTER E WITH CIRCUMFLEX'] >>> [unicodedata.name(char) for char in "ê"] ['LATIN SMALL LETTER E', 'COMBINING CIRCUMFLEX ACCENT'] ``` The simplest way to deal with this is [`unicodedata.normalize`](https://docs.python.org/library/unicodedata.html#unicodedata.normalize). You probably want to use [**NFKD** normalization](http://www.unicode.org/reports/tr15/#Normalization_Forms_Table), but feel free to check the documentation. Then one does ``` >>> unicodedata.normalize("NFKD", "ê") == unicodedata.normalize("NFKD", "ê") True ``` To finish up, here this is expressed in functions: ``` import unicodedata def normalize_caseless(text): return unicodedata.normalize("NFKD", text.casefold()) def caseless_equal(left, right): return normalize_caseless(left) == normalize_caseless(right) ```
How do I do a case-insensitive string comparison?
[ "", "python", "comparison", "case-insensitive", "" ]
In php I need to get the contents of a url (source) search for a string "maybe baby love you" and if it does not contain this then do x.
Just read the contents of the page as you would read a file. PHP does the connection stuff for you. Then just look for the string via regex or simple string comparison. ``` $url = 'http://my.url.com/'; $data = file_get_contents( $url ); if ( strpos( 'maybe baby love you', $data ) === false ) { // do something } ```
``` //The Answer No 3 Is good But a small Mistake in the function strpos() I have correction the code bellow. $url = 'http://my.url.com/'; $data = file_get_contents( $url ); if ( strpos($data,'maybe baby love you' ) === false ) { // do something } ```
PHP Get URL Contents And Search For String
[ "", "php", "" ]
I am trying to determine the best directory structure of my application i have: UI Data Interfaces but i dont know where to put delegates.. should there be a seperate Delegates folder or should i store the delegates in the same classes where they are being used . .
If you have an common use for your delegates, you should store them on a common place, but if you only use it in your class then put it in the same class.
You don't have a Classes, Structs, and Enums folder. Why have a Delegates folder? Also, if you're using C# 3.0, you generally should be using Generic Delegates - System.Action and System.Func - instead of named delegates.
Where to put your delegates . .
[ "", "c#", "delegates", "directory-structure", "" ]
I'm able to get cells to format as Dates, but I've been unable to get cells to format as currency... Anyone have an example of how to create a style to get this to work? My code below show the styles I'm creating... the styleDateFormat works like a champ while styleCurrencyFormat has no affect on the cell. ``` private HSSFWorkbook wb; private HSSFCellStyle styleDateFormat = null; private HSSFCellStyle styleCurrencyFormat = null; ``` ...... ``` public CouponicsReportBean(){ wb = new HSSFWorkbook(); InitializeFonts(); } public void InitializeFonts() { styleDateFormat = wb.createCellStyle(); styleDateFormat.setDataFormat(HSSFDataFormat.getBuiltinFormat("m/d/yy")); styleCurrencyFormat = wb.createCellStyle(); styleCurrencyFormat.setDataFormat(HSSFDataFormat.getBuiltinFormat("$#,##0.00")); } ```
After digging through the documentation a bit more, I found the answer: <http://poi.apache.org/apidocs/org/apache/poi/hssf/usermodel/HSSFDataFormat.html> Just need to find an appropriate pre-set format and supply the code. ``` styleCurrencyFormat.setDataFormat((short)8); //8 = "($#,##0.00_);[Red]($#,##0.00)" ``` Here are more examples: <http://www.roseindia.net/java/poi/setDataFormat.shtml>
For at least Excel 2010: Go into Excel. Format a cell they way you want it. ![enter image description here](https://i.stack.imgur.com/LjLvV.png) Then go back into the format dialogue. Select custom. ![enter image description here](https://i.stack.imgur.com/GuqV2.png) Copy paste the text it has on the top row under Type: into ``` createHelper.createDataFormat().getFormat("<here>"); ``` Example: ``` createHelper.createDataFormat().getFormat("_($* #,##0.00_);_($* (#,##0.00);_($* \"-\"??_);_(@_)"); //is the "Accounting" format. ``` **Make sure you set your populate your cells by using a double.** Using the index may cause problems with different versions of Excel. Note that the new format you create above ends up in the custom dialogue from step two.
Basic Excel currency format with Apache POI
[ "", "java", "apache-poi", "" ]
I'm new to PHP and I'm trying to do something that may be bad practise and may well be impossible. I'm basically just hacking something together to test my knowledge and see what PHP can do. I have one webpage with a form that collects data. That is submited to a PHP script that does a bunch of processing - but doesn't actually display anything important. What I want is that once the processing is done, the script then tells the browser to open another page, where the results are displayed. I know I can use *header('Location: page.php');* but I can't work out how to provide POST data with this. How can I do that? Alternatively, is there another way to tell the browser to open another page? EDIT: What I'm taking from the responses is that it's *possible* to do this using various hacks but I'd be better off to just have the processing and the display code in one file. I'm happy with that; this was an experiment more than anything.
Is it really necessary to call another page after the processing is done? I'd probably do the following: ``` <form method="post" action="display.php"> ... </form> ``` display.php: ``` if ($_POST) { require_once(process.php); process($_POST); display_results; } ``` with process.php containing the code necessary for processing the post request. Alternatively, you could use something like the cURL library to pass the results of the processing to a page specified by yourself. Don't know if that's really what you're after though.
You could store that data in the session e.g. in the first file that handles the post ``` session_start(); $_SESSION['formdata'] = $_POST; //or whatever ``` then you can read it on the next page like ``` session_start(); print_r($_SESSION['formdata']); ``` or you could pass it through GET: (but as per comments this is a bad idea) ``` header('Location: page.php?' . http_build_query($_POST)); ``` If you do that make sure you do additional processing/validation on page.php as a malicious user could change the variables. also you may not need the whole post transmitted to the next page **Edit** I should make clear that I think the second option is possibly worse, as you are limited by the size of data you can send through get and it is possibly less secure as users can more obviously manipulate the data.
PHP open another webpage with POST data
[ "", "php", "post", "redirect", "header", "" ]
My application caches some data on disk. Because the cache may be large, it should not be stored on a network drive. It should persist between invocations of the application. I have a mechanism for the user to choose a location, but would like the default to be sensible and "the right thing" for the platform. What is the appropriate location for such a cache? Is there an API for determining the appropriate location? How do I call it from Python?
Have a look here: <http://en.wikipedia.org/wiki/Environment_variable#User_management_variables>. Anything that's under the users directory is good. If its for all users, then it should be: %ALLUSERSPROFILE%. If its for a specific user, make sure the permissions are right. Check out MSDN for more info about other Windows Versions. Environment variables can vary from systems to systems.
The standard location for Windows application to store their (permanent) application data is referenced by the `%APPDATA%` (current user) or `%ALLUSERSPROFILE%` (all users) environment variables. You can access them using, e.g. (only rudimentary and not very elegant error checking!): ``` import os app_path = os.getenv("APPDATA") + "\\MyApplicationData" try: os.mkdir(app_path) except WindowsError: # already exists ``` Now you have your own directory for your app.
Appropriate location for my application's cache on Windows
[ "", "python", "windows", "" ]
I've seen this syntax a couple times now, and it's beginning to worry me, For example: ``` iCalendar iCal = new iCalendar(); Event evt = iCal.Create<Event>(); ```
It's a Generic Method, Create is declared with type parameters, and check this links for more information: * [An Introduction to C# Generics](http://msdn.microsoft.com/en-us/library/ms379564(vs.80).aspx) * [Generics (C# Programming Guide)](https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/generics/) * [Generic Methods](https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/generics/generic-methods)
It's calling a generic method - so in your case, the method may be declared like this: ``` public T Create<T>() ``` You can specify the type argument in the angle brackets, just as you would for creating an instance of a generic type: ``` List<Event> list = new List<Event>(); ``` Does that help? One difference between generic *methods* and generic *types* is that the compiler can try to infer the type argument. For instance, if your `Create` method were instead: ``` public T Copy<T>(T original) ``` you could just call ``` Copy(someEvent); ``` and the compiler would infer that you meant: ``` Copy<Event>(someEvent); ```
What does Method<ClassName> mean?
[ "", "c#", "class", "oop", "generics", "syntax", "" ]
I have a couple of questions about generic wildcards in Java: 1. What is the difference between `List<? extends T>` and `List<? super T>`? 2. What is a bounded wildcard and what is an unbounded wildcard?
In your first question, `<? extends T>` and `<? super T>` are examples of bounded wildcards. An unbounded wildcard looks like `<?>`, and basically means `<? extends Object>`. It loosely means the generic can be any type. A bounded wildcard (`<? extends T>` or `<? super T>`) places a restriction on the type by saying that it either has to *extend* a specific type (`<? extends T>` is known as an upper bound), or has to be an ancestor of a specific type (`<? super T>` is known as a lower bound). The Java Tutorials have some pretty good explanations of generics in the articles [Wildcards](http://java.sun.com/docs/books/tutorial/java/generics/wildcards.html) and [More Fun with Wildcards](http://java.sun.com/docs/books/tutorial/extra/generics/morefun.html).
If you have a class hierarchy `A`, `B` is a subclass of `A`, and `C` and `D` are both subclasses of `B` like below ``` class A {} class B extends A {} class C extends B {} class D extends B {} ``` Then ``` List<? extends A> la; la = new ArrayList<B>(); la = new ArrayList<C>(); la = new ArrayList<D>(); List<? super B> lb; lb = new ArrayList<A>(); //fine lb = new ArrayList<C>(); //will not compile public void someMethod(List<? extends B> lb) { B b = lb.get(0); // is fine lb.add(new C()); //will not compile as we do not know the type of the list, only that it is bounded above by B } public void otherMethod(List<? super B> lb) { B b = lb.get(0); // will not compile as we do not know whether the list is of type B, it may be a List<A> and only contain instances of A lb.add(new B()); // is fine, as we know that it will be a super type of A } ``` A bounded wildcard is like `? extends B` where `B` is some type. That is, the type is unknown but a "bound" can be placed on it. In this case, it is bounded by some class, which is a subclass of B.
Java Generics (Wildcards)
[ "", "java", "generics", "bounded-wildcard", "" ]
I have an already large table that my clients are asking for me to extend the length of the notes field. The notes field is already an NVARCHAR(1000) and I am being asked to expand it to 3000. The long term solution is to move notes out of the table and create a notes table that uses an NVARCHAR(max) field that is only joined in when necessary. My question is about the short term. Knowing that this field will be moved out in the future what problems could I have if I just increase the field to an NVARCHAR(3000) for now?
text and ntext are deprecated in favor of varchar(max) and nvarchar(max). So nvarchar(3000) should be fine.
You probably already know this, but just make sure that the increased length doesn't drive your total record length over 8000. I pretty sure that still applies for 2005/2008.
What problems can an NVARCHAR(3000) cause
[ "", "sql", "sql-server", "sql-server-2005", "" ]
I am looking to use quartz to schedule emails, but I'm not sure which approach to take: 1. Create a new job and trigger whenever an email is scheduled OR 2. Create a single job, and create a new trigger each time an email is scheduled I need to pass the message/recipient etc either way, and I'm not sure whether creating heaps of jobs will start adding considerable memory overheads, as there will quite possibly be thousands of emails scheduled. **Update**: These emails will be scheduled by users, not by me - so I will be adding these programmatically at runtime, they aren't scheduled to go out at any particular time.
Quartz is intended to handle tens of thousands of triggers. The main limit to scalability here is the space available in your JobStore. A JDBCJobStore backed with a reasonable database should be able to handle hundreds of thousands of triggers. If a single job can be parameterized through the trigger's job data map, create a single job and one trigger for each email. Quartz polls the job store periodically to look for triggers that are ready to fire. Quartz is designed to safely handle arbitrarily large result sets from this query. What matters—and this really has nothing to do Quartz itself—is that you have the necessary bandwidth to execute peak loads. If users tend to schedule mails in clumps, you need to make sure that you have the computing resources to get the emails out. This would include network bandwidth, processing, and enough worker threads configured to utilize the available resources. Note that you can configure what Quartz should do with a trigger if it does get too far behind in executing jobs. You can keep trying, skip the trigger, etc.
Are the triggers to be based on a time schedule? You can use a [CronTrigger](http://www.opensymphony.com/quartz/wikidocs/CronTriggers%20Tutorial.html) to set up a more complex time based schedule rather than individual triggers.
Should I create a new quartz job and trigger or one job and many triggers?
[ "", "java", "scheduling", "quartz-scheduler", "" ]
I have a static class that I would like to raise an event as part of a try catch block within a static method of that class. For example in this method I would like to raise a custom event in the catch. ``` public static void saveMyMessage(String message) { try { //Do Database stuff } catch (Exception e) { //Raise custom event here } } ``` Thank you.
Important: be very careful about subscribing to a static event from instances. Static-to-static is fine, but a subscription from a static event to an instance handler is a great (read: very dangerous) way to keep that instance alive forever. GC will see the link, and will not collect the instance unless you unsubscribe (or use something like a WeakReference). The pattern for creating static events is the same as instance events, just with `static`: ``` public static event EventHandler SomeEvent; ``` To make life easier (re null checking), a useful trick here is to add a trivial handler: ``` public static event EventHandler SomeEvent = delegate {}; ``` Then you can simply invoke it without the null-check: ``` SomeEvent(null, EventArgs.Empty); ``` Note that because delegate instances are immutable, and de-referencing is thread-safe, there is never a race condition here, and no need to lock... who-ever is subscribed when we de-reference gets invoked. (adjust for your own event-args etc). This trick applies equally to instance events.
Your event would also need to be static: ``` public class ErrorEventArgs : EventArgs { private Exception error; private string message; public ErrorEventArgs(Exception ex, string msg) { error = ex; message = msg; } public Exception Error { get { return error; } } public string Message { get { return message; } } } public static class Service { public static EventHandler<ErrorEventArgs> OnError; public static void SaveMyMessage(String message) { EventHandler<ErrorEventArgs> errorEvent = OnError; if (errorEvent != null) { errorEvent(null, new ErrorEventArgs(null, message)); } } } ``` And Usage: ``` public class Test { public void OnError(object sender, ErrorEventArgs args) { Console.WriteLine(args.Message); } } Test t = new Test(); Service.OnError += t.OnError; Service.SaveMyMessage("Test message"); ```
How to raise custom event from a Static Class
[ "", "c#", "asp.net", "" ]
Are there any libraries out there for Java that will accept two strings, and return a string with formatted output as per the \*nix diff command? e.g. feed in ``` test 1,2,3,4 test 5,6,7,8 test 9,10,11,12 test 13,14,15,16 ``` and ``` test 1,2,3,4 test 5,6,7,8 test 9,10,11,12,13 test 13,14,15,16 ``` as input, and it would give you ``` test 1,2,3,4 test 1,2,3,4 test 5,6,7,8 test 5,6,7,8 test 9,10,11,12 | test 9,10,11,12,13 test 13,14,15,16 test 13,14,15,16 ``` Exactly the same as if I had passed the files to `diff -y expected actual` I found [this question](https://stackoverflow.com/questions/132478/how-to-perform-string-diffs-in-java), and it gives some good advice on general libraries for giving you programmatic output, but I'm wanting the straight string results. I could call `diff` directly as a system call, but this particular app will be running on unix and windows and I can't be sure that the environment will actually have `diff` available.
I ended up rolling my own. Not sure if it's the best implementation, and it's ugly as hell, but it passes against test input. It uses [java-diff](http://www.incava.org/projects/java/java-diff/) to do the heavy diff lifting (any apache commons StrBuilder and StringUtils instead of stock Java StringBuilder) ``` public static String diffSideBySide(String fromStr, String toStr){ // this is equivalent of running unix diff -y command // not pretty, but it works. Feel free to refactor against unit test. String[] fromLines = fromStr.split("\n"); String[] toLines = toStr.split("\n"); List<Difference> diffs = (new Diff(fromLines, toLines)).diff(); int padding = 3; int maxStrWidth = Math.max(maxLength(fromLines), maxLength(toLines)) + padding; StrBuilder diffOut = new StrBuilder(); diffOut.setNewLineText("\n"); int fromLineNum = 0; int toLineNum = 0; for(Difference diff : diffs) { int delStart = diff.getDeletedStart(); int delEnd = diff.getDeletedEnd(); int addStart = diff.getAddedStart(); int addEnd = diff.getAddedEnd(); boolean isAdd = (delEnd == Difference.NONE && addEnd != Difference.NONE); boolean isDel = (addEnd == Difference.NONE && delEnd != Difference.NONE); boolean isMod = (delEnd != Difference.NONE && addEnd != Difference.NONE); //write out unchanged lines between diffs while(true) { String left = ""; String right = ""; if (fromLineNum < (delStart)){ left = fromLines[fromLineNum]; fromLineNum++; } if (toLineNum < (addStart)) { right = toLines[toLineNum]; toLineNum++; } diffOut.append(StringUtils.rightPad(left, maxStrWidth)); diffOut.append(" "); // no operator to display diffOut.appendln(right); if( (fromLineNum == (delStart)) && (toLineNum == (addStart))) { break; } } if (isDel) { //write out a deletion for(int i=delStart; i <= delEnd; i++) { diffOut.append(StringUtils.rightPad(fromLines[i], maxStrWidth)); diffOut.appendln("<"); } fromLineNum = delEnd + 1; } else if (isAdd) { //write out an addition for(int i=addStart; i <= addEnd; i++) { diffOut.append(StringUtils.rightPad("", maxStrWidth)); diffOut.append("> "); diffOut.appendln(toLines[i]); } toLineNum = addEnd + 1; } else if (isMod) { // write out a modification while(true){ String left = ""; String right = ""; if (fromLineNum <= (delEnd)){ left = fromLines[fromLineNum]; fromLineNum++; } if (toLineNum <= (addEnd)) { right = toLines[toLineNum]; toLineNum++; } diffOut.append(StringUtils.rightPad(left, maxStrWidth)); diffOut.append("| "); diffOut.appendln(right); if( (fromLineNum > (delEnd)) && (toLineNum > (addEnd))) { break; } } } } //we've finished displaying the diffs, now we just need to run out all the remaining unchanged lines while(true) { String left = ""; String right = ""; if (fromLineNum < (fromLines.length)){ left = fromLines[fromLineNum]; fromLineNum++; } if (toLineNum < (toLines.length)) { right = toLines[toLineNum]; toLineNum++; } diffOut.append(StringUtils.rightPad(left, maxStrWidth)); diffOut.append(" "); // no operator to display diffOut.appendln(right); if( (fromLineNum == (fromLines.length)) && (toLineNum == (toLines.length))) { break; } } return diffOut.toString(); } private static int maxLength(String[] fromLines) { int maxLength = 0; for (int i = 0; i < fromLines.length; i++) { if (fromLines[i].length() > maxLength) { maxLength = fromLines[i].length(); } } return maxLength; } ```
# [java-diff-utils](http://code.google.com/p/java-diff-utils/) > The DiffUtils library for computing > diffs, applying patches, generationg > side-by-side view in Java > > Diff Utils library is an OpenSource > library for performing the comparison > operations between texts: computing > diffs, applying patches, generating > unified diffs or parsing them, > generating diff output for easy future > displaying (like side-by-side view) > and so on. > > Main reason to build this library was > the lack of easy-to-use libraries with > all the usual stuff you need while > working with diff files. Originally it > was inspired by JRCS library and it's > nice design of diff module. > > **Main Features** > > * computing the difference between two texts. > * capable to hand more than plain ascci. Arrays or List of any type that > implements hashCode() and equals() > correctly can be subject to > differencing using this library > * patch and unpatch the text with the given patch > * parsing the unified diff format > * producing human-readable differences
Generate formatted diff output in Java
[ "", "java", "diff", "" ]
What are the hidden features of Maven2?
You can use the settings.xml to force ALL maven builds running on your local machine to also use a locally installed maven proxy. Saving yourself and the network time. ``` <settings xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/settings-1.0.0.xsd"> <profile> <id>localcacheproxies</id> <activation> <activeByDefault>true</activeByDefault> </activation> <repositories> <repository> <id>localCacheProxy</id> <url>http://my-local-proxy.com/maven-proxy</url> </repository> </repositories> </profile> </profiles> ``` Note that the namespace headings in this settings.xml also gives a decent intellisense as opposed to other examples posted here. (create in your home directory .m2 folder on windows, linux and mac and all os'es)
Take a look at dependency:analyze as well.
What are the hidden features of Maven2?
[ "", "java", "apache", "maven-2", "dependency-management", "" ]
I am working on a tool where I need to convert string values to their proper object types. E.g. convert a string like `"2008-11-20T16:33:21Z"` to a `DateTime` value. Numeric values like `"42"` and `"42.42"` must be converted to an `Int32` value and a `Double` value respectively. What is the best and most efficient approach to detect if a string is an integer or a number? Are `Int32.TryParse` or `Double.TryParse` the way to go?
In terms of efficiency, yes, TryParse is generally the preferred route. If you can know (for example, by reflection) the target type in advance - but don't want to have to use a big `switch` block, you might be interested in using `TypeConverter` - for example: ``` DateTime foo = new DateTime(2008, 11, 20); TypeConverter converter = TypeDescriptor.GetConverter(foo); string s = converter.ConvertToInvariantString(foo); object val = converter.ConvertFromInvariantString(s); ```
`Int.TryParse` and `Double.TryParse` have the benefit of actually returning the number. Something like `Regex.IsMatch("^\d+$")` has the drawback that you still have to parse the string again to get the value out.
How to determine if a string is a number in C#
[ "", "c#", ".net", "string", "value-type", "" ]
I am trying to come up with a best practices on project directory structure. my latest thought is that there should be no classes in the root directory of a project. All classes must go under one of the following directories * UI * BusinessObjects * BusinessLogic * DataAccess i would like to hear other people thought on if there are use cases for putting things at the root level or find classes that wouldn't fit into
If you're talking about C# then I would separate your DAL, BLL, GUI to different projects instead of one project. And have one solution. This will force each code file to be inside of one of the projects. I've added an example: * Solution: ProjectName + Project: DAL (Namespace: ProjectName.DAL) - Folder: Repositories (Namespace: ProjectName.DAL.Repositories) - Folder: Contracts (Namespace: ProjectName.DAL.Contracts) - Files: Your Entity Mapping configuration + Project: BLL (Namespace: ProjectName.BLL) - Folder: Services (Namespace: Project.BLL.Services) - Folder: Entities (Namespace: Project.BLL.Entities) - Files: IoC configuration classes/general Business Logic + Project: Shared (Namespace: ProjectName.Shared) - Files: General shared logic throught your whole application (for instance an InvalidIdentifier constant) - This project should not reference other projects in the solution.. + Project: Website (Namespace: ProjectName.Website) - Your asp.net website UI + Project: Winforms (Namespace: ProjectName.Winforms) - Your winforms UI If possible you should give the website and winforms project a name relative to your application.
This [blog](http://www.hanselman.com/blog/howdoyouorganizeyourcode.aspx) should provide you with some interesting reading, despite being three years old. It might give you ideas besides those of just directory structure.
Is it OK to have code in the root of a project?
[ "", "c#", "directory", "structure", "" ]
Similar to [List<> OrderBy Alphabetical Order](https://stackoverflow.com/questions/188141/c-list-orderby-alphabetical-order), we want to sort by one element, then another. we want to achieve the functional equivalent of ``` SELECT * from Table ORDER BY x, y ``` We have a class that contains a number of sorting functions, and we have no issues sorting by one element. For example: ``` public class MyClass { public int x; public int y; } List<MyClass> MyList; public void SortList() { MyList.Sort( MySortingFunction ); } ``` And we have the following in the list: ``` Unsorted Sorted(x) Desired --------- --------- --------- ID x y ID x y ID x y [0] 0 1 [2] 0 2 [0] 0 1 [1] 1 1 [0] 0 1 [2] 0 2 [2] 0 2 [1] 1 1 [1] 1 1 [3] 1 2 [3] 1 2 [3] 1 2 ``` Stable sort would be preferable, but not required. Solution that works for .Net 2.0 is welcome.
Do keep in mind that you don't need a stable sort if you compare all members. The 2.0 solution, as requested, can look like this: ``` public void SortList() { MyList.Sort(delegate(MyClass a, MyClass b) { int xdiff = a.x.CompareTo(b.x); if (xdiff != 0) return xdiff; else return a.y.CompareTo(b.y); }); } ``` Do note that this 2.0 solution is still preferable over the popular 3.5 Linq solution, it performs an in-place sort and does not have the O(n) storage requirement of the Linq approach. Unless you prefer the original List object to be untouched of course.
For versions of .Net where you can use LINQ `OrderBy` and [`ThenBy`](http://msdn.microsoft.com/en-us/library/vstudio/bb534743(v=vs.100).aspx) (or `ThenByDescending` if needed): ``` using System.Linq; .... List<SomeClass>() a; List<SomeClass> b = a.OrderBy(x => x.x).ThenBy(x => x.y).ToList(); ``` --- Note: for .Net 2.0 (or if you can't use LINQ) see [Hans Passant answer](https://stackoverflow.com/a/289040/477420) to this question.
C# List<> Sort by x then y
[ "", "c#", ".net", "sorting", "" ]
There are many editions of Eclipse for Java development. I am trying out MyEclipse and am pretty impressed with the out-of-box experience. Before I get too comfortable with it, I would like to find out if it is the best edition available. Feel free to list free or commercial packages, but for the sake of other readers, please mention if there is a cost. ## Considerations I am mostly concerned with the code editing experience. Here is a list of *some* factors that would affect my decision: * Extensive support for refactoring * Code suggestions (like suggesting refactorings) * Easily configurable keyboard shortcuts * Easily configurable colours (I use dark colour schemes, and setting this up with MyEclipse was hell; that said, I only really need to do it once) * Excellent debugging support * Source control plugins (SVN or git if one exists) * Don't care about GUI designers I am aware that there is a thread discussing the best IDE for Java development; however, most of the responses do not detail recommended editions of Eclipse.
all of the above except the color stuff works great with **vanilla Eclipse 3.4 + Subclipse**. if you find an easy way to customize colors in Eclipse, please let us know. Until then you're stuck with having to manually change each color.
I'm always just downloading **classic** edition and just add plugins I need. That way I keep Eclipse as lean as possible.
Best Eclipse version for Java development
[ "", "java", "eclipse", "ide", "" ]
If have a set of classes that all implement an interface. ``` interface IMyinterface<T> { int foo(T Bar); } ``` I want to shove them all in a list and enumerate through them. ``` List<IMyinterface> list foreach(IMyinterface in list) // etc... ``` but the compiler wants to know what T is. Can I do this? How can I overcome this issue?
There is no IMyinterface type there is only a IMyinterface`1 type which will require a type argument. You could create an IMyinterface type:- ``` interface IMyinterface { ... } ``` then inherit from it ``` interface IMyinterface<T> : IMyinterface { ... } ``` You would need to move any members you would like to use in the foreach loop to the IMyinterface definition.
If you plan to invoke a method with T in the signature, the answer is that you cannot. Otherwise you can do as anthonywjones suggests
generics and interfaces enumeration
[ "", "c#", ".net", "generics", "interface", "ienumerable", "" ]
In Java, is there a way to have a window that is "Always on top" regardless if the user switches focus to another application? I've searched the web, and all of the solutions lean to some sort of JNI interface with native bindings. Truly this can't be the only way to do it?.. or is it?
Try this method of the `Window` class: [Window.setAlwaysOnTop(boolean)](http://java.sun.com/javase/6/docs/api/java/awt/Window.html#setAlwaysOnTop%28boolean%29) It works the same way as the default in the Windows TaskManager: switch to another app but it shows always on top. This was added in Java 1.5 Sample code: ``` import javax.swing.JFrame; import javax.swing.JLabel; public class Annoying { public static void main(String[] args) { JFrame frame = new JFrame("Hello!!"); // Set's the window to be "always on top" frame.setAlwaysOnTop( true ); frame.setLocationByPlatform( true ); frame.add( new JLabel(" Isn't this annoying?") ); frame.pack(); frame.setVisible( true ); } } ``` ![alt text](https://i.stack.imgur.com/od2Zo.png) Window remains on top even when is not active
From my observation I found that AlwaysOnTop privilege is given to the latest process which requested to be always on top. So, if you have an application which `setAlwaysOnTop(true)` and later another application uses this option, the privilege is given to the second application. In order to work around this I have set the `setAlwaysOnTop(false)` and again `setAlwaysOnTop(true)` whenever any window comes on top of the current window. I've checked it with `wordweb` in `windows`. WordWeb is one of the applications which uses `AlwaysOnTop` option from the `OS` I'm not sure about if it works properly with your game scenario. **Warning**: I'm not aware of the side effects. Here is the code example: ``` import java.awt.event.*; import javax.swing.*; public class MainWindow extends JFrame implements WindowFocusListener { public MainWindow() { addWindowFocusListener(this); setAlwaysOnTop(true); this.setFocusable(true); // this.setFocusableWindowState(true); panel = new JPanel(); //setSize(WIDTH,HEIGHT); setUndecorated(true); setLocation(X,Y); setExtendedState(MAXIMIZED_BOTH); setVisible(true); } public void windowGainedFocus(WindowEvent e){} public void windowLostFocus(WindowEvent e) { if(e.getNewState()!=e.WINDOW_CLOSED){ //toFront(); //requestFocus(); setAlwaysOnTop(false); setAlwaysOnTop(true); //requestFocusInWindow(); System.out.println("focus lost"); } } private JPanel panel; private static final int WIDTH = 200; private static final int HEIGHT = 200; private static final int X = 100; private static final int Y = 100; public static void main(String args[]){ new MainWindow();} } ```
"Always on Top" Windows with Java
[ "", "java", "user-interface", "swing", "awt", "" ]
I need a fast container with only two operations. Inserting keys on from a very sparse domain (all 32bit integers, and approx. 100 are set at a given time), and iterating over the inserted keys. It should deal with *a lot of* insertions which hit the same entries (like, 500k, but only 100 different ones). Currently, I'm using a std::set (only insert and the iterating interface), which is decent, but still not fast enough. std::unordered\_set was twice as slow, same for the Google Hash Maps. I wonder what data structure is optimized for this case?
Depending on the distribution of the input, you might be able to get some improvement without changing the structure. If you tend to get a lot of runs of a single value, then you can probably speed up insertions by keeping a record of the last value you inserted, and don't bother doing the insertion if it matches. It costs an extra comparison per input, but saves a lookup for each element in a run beyond the first. So it could improve things no matter what data structure you're using, depending on the frequency of repeats and the relative cost of comparison vs insertion. If you don't get runs, but you tend to find that values aren't evenly distributed, then a splay tree makes accessing the most commonly-used elements cheaper. It works by creating a deliberately-unbalanced tree with the frequent elements near the top, like a Huffman code.
I'm not sure I understand "a lot of insertions which hit the same entries". Do you mean that there are only 100 values which are ever members, but 500k mostly-duplicate operations which insert one of those 100 values? If so, then I'd guess that the fastest container would be to generate a collision-free hash over those 100 values, then maintain an array (or vector) of flags (int or bit, according to what works out fastest on your architecture). I leave generating the hash as an exercise for the reader, since it's something that I'm aware exists as a technique, but I've never looked into it myself. The point is to get a fast hash over as small a range as possible, such that for each n, m in your 100 values, hash(n) != hash(m). So insertion looks like `array[hash(value)] = 1;`, deletion looks like `array[hash(value)] = 0;` (although you don't need that), and to enumerate you run over the array, and for each set value at index n, inverse\_hash(n) is in your collection. For a small range you can easily maintain a lookup table to perform the inverse hash, or instead of scanning the whole array looking for set flags, you can run over the 100 potentially-in values checking each in turn. Sorry if I've misunderstood the situation and this is useless to you. And to be honest, it's not very much faster than a regular hashtable, since realistically for 100 values you can easily size the table such that there will be few or no collisions, without using so much memory as to blow your caches.
Fast container for setting bits in a sparse domain, and iterating (C++)?
[ "", "c++", "containers", "" ]
Which GUI framework/library would you choose if you were to start your new project **now** or in the near future? It has to be free for commercial use and cross platform. I have been a happy swing user, but Sun seems like pushing **swing** to deprecation, while pushing **Javafx**, which is not yet ready for prime time. There's also **SWT**, but it seems like it has issues on Linux. What is your Gui library/framework of choice? EDIT: Sun has canceled **swingx** project. From the forum comments on <http://swingx.dev.java.net> seems like majority of Sun resources that previously worked on core swing are now developing JavaFx full time.
I think that despite Sun's mismanagement, Swing is still an excellent framework. You can do a *lot* with it, especially if that "lot" involves custom rendered UI controls. If your application needs a branded LAF, or even just a few complex custom controls here and there, Swing is exactly what you want. On the other side of the coin, I do like SWT quite a lot. It gets a bad rap because everyone used to think it was IBM's ploy to take over Java, but it's really just another UI framework that is quite complementary to Swing. I would not advise using SWT for super-complex graphics rendering (specifically: compositing) or for creating really non-trivial custom controls, but for everything else it is really dandy. The API itself gets a lot of criticism because of things like reliance on bit masks and a user-managed event dispatch loop, but most of those things are pretty transparent once you get used to them. The components themselves are a lot simpler than Swing's (in terms of extensibility and similar), which means that the API can be proportionally simpler. I can actually remember how to create and populate a table in SWT; whereas I don't think I have *ever* handled that in Swing without Google's assistance. SWT's biggest problem right now is the stable version depends on Carbon on Mac OS X. This means that SWT apps can only run 32bit on Java 5 (or 32bit on SoyLatte). As for other platforms, SWT is phenomenal on Windows (Vista and XP) and almost as good on GTK Linux. I have not (in recent past) had any issues with SWT on Linux, so I'm a bit surprised that you would mention it as a sore point. Coming back to your question: it all depends on what your application needs. If it's a flashy custom-styled application with tons of custom controls and complex compositing, Swing is the only game in town. However, if a simpler API is more important to you, or if your users demand the ultimate in platform LAF fidelity, SWT is the best choice.
Right now, I'm either using SWT or Qt (Jambi). Swing didn't evolve in the last, say, 10 years, bugs aren't fixed, the development has stopped in favor of JavaFX, so you won't ever see any new features, too. JavaFX will probably look great but is still vaporware and it's made by the people who let Swing starve to death, so I'm not putting any money on it. Between SWT and Qt, I prefer to use Qt because it's a very mature and powerful framework made by people who know what they are doing (well, most of the time anyway :)) and SWT if the license for the new project wasn't compatible to Qt's.
Which Java GUI framework to choose now?
[ "", "java", "user-interface", "cross-platform", "gui-toolkit", "" ]
Here are two chunks of code that accomplish (what I think is) the same thing. I basically am trying to learn how to use Java 1.5's concurrency to get away from Thread.sleep(long). The first example uses ReentrantLock, and the second example uses CountDownLatch. The jist of what I am trying to do is put one thread to sleep until a condition is resolved in another thread. The ReentrantLock provides a lock on the boolean I'm using to decide whether to wake the other thread or not, and then I use the Condition with await/signal to sleep the other thread. As far as I can tell, the only reason I would need to use locks is if more than one thread required write access to the boolean. The CountDownLatch seems to provide the same functionality as the ReentrantLock but without the (unnecessary?) locks. However, it feels like I am kind of hijacking its intended use by initializing it with only one countdown necessary. I think it's supposed to be used when multiple threads are going to be working on the same task, not when multiple threads are waiting on one task. So, questions: 1. Am I using locks for "the right thing" in the ReentrantLock code? If I am only writing to the boolean in one thread, are the locks necessary? As long as I reset the boolean before waking up any other threads I can't cause a problem, can I? 2. Is there a class similar to CountDownLatch I can use to avoid locks (assuming I should be avoiding them in this instance) that is more naturally suited to this task? 3. Are there any other ways to improve this code I should be aware of? EXAMPLE ONE: ``` import java.util.concurrent.locks.*; public class ReentrantLockExample extends Thread { //boolean - Is the service down? boolean serviceDown; // I am using this lock to synchronize access to sDown Lock serviceLock; // and this condition to sleep any threads waiting on the service. Condition serviceCondition; public static void main(String[] args) { Lock l = new ReentrantLock(); Condition c = l.newCondition(); ReentrantLockExample rle = new ReentrantLockExample(l, c); //Imagine this thread figures out the service is down l.lock(); try { rle.serviceDown = true; } finally { l.unlock(); } int waitTime = (int) (Math.random() * 5000); System.out.println("From main: wait time is " + waitTime); rle.start(); try { //Symbolizes some random time that the service takes to come back up. Thread.sleep(waitTime); } catch (InterruptedException e) { e.printStackTrace(); } //Imagine this thread figures out that the service is back up. l.lock(); try { rle.serviceDown = false; c.signal(); } finally { l.unlock(); } } //Constructor public ReentrantLockExample(Lock l, Condition c) { this.serviceLock = l; this.serviceCondition = c; } /* * Should wait for this imaginary service to come back online. */ public void run() { System.out.println("Thread: start awaiting"); serviceLock.lock(); try { while (isServiceDown()) { serviceCondition.await(); } } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { serviceLock.unlock(); } System.out.println("Thread: done awaiting"); } private boolean isServiceDown() { return serviceDown; } } ``` EXAMPLE TWO: ``` import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import java.util.concurrent.locks.*; public class CountDownLatchExample extends Thread { //boolean - Is the service down? boolean serviceDown; // I am using this latch to wait on the service. CountDownLatch serviceLatch; public static void main(String[] args) { CountDownLatch cdl = new CountDownLatch(1); CountDownLatchExample cdle = new CountDownLatchExample(cdl); //Service goes down. cdle.serviceDown = true; int waitTime = (int) (Math.random() * 5000); System.out.println("From main: wait time is " + waitTime); cdle.start(); try { //Symbolizes some random time that the service takes to come back up. Thread.sleep(waitTime); } catch (InterruptedException e) { e.printStackTrace(); } //Service comes back up. cdle.serviceDown = false; cdl.countDown(); } //Constructor public CountDownLatchExample(CountDownLatch cdl) { this.serviceLatch = cdl; } /* * Should wait for this imaginary service to come back online. */ public void run() { System.out.println("Thread: start awaiting"); try { while (isServiceDown()) { serviceLatch.await(); } } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println("Thread: done awaiting"); } private boolean isServiceDown() { return serviceDown; } } ```
Either approach is roughly equivalent, except that a [CountDownLatch](http://java.sun.com/javase/6/docs/api/java/util/concurrent/CountDownLatch.html) can only be released once. After that all [await()](http://java.sun.com/javase/6/docs/api/java/util/concurrent/CountDownLatch.html#await()) calls return instantly. So a [CyclicBarrier](http://java.sun.com/javase/6/docs/api/java/util/concurrent/CyclicBarrier.html) may actually be more appropriate if you are working with a service that may go down and up. If your condition really is a one-shot deal, then a [FutureTask](http://java.sun.com/javase/6/docs/api/java/util/concurrent/FutureTask.html) would be more appropriate. You could call [get()](http://java.sun.com/javase/6/docs/api/java/util/concurrent/FutureTask.html#get()) which would wait for the service to become available, and then you could use the service as soon as get() returns. You mention that CountDownLatch allows waiting without using Locks. However, both CountDownLatch and [ReentrantLock](http://java.sun.com/javase/6/docs/api/java/util/concurrent/locks/ReentrantLock.html) are implemented using [AbstractQueuedSynchronizer](http://java.sun.com/javase/6/docs/api/java/util/concurrent/locks/AbstractQueuedSynchronizer.html). Under the hood, they provide identical synchronization and visibility semantics.
The lock/condition variable approach is better for this task in my opinion. There is a similar example to yours here: <http://java.sun.com/j2se/1.5.0/docs/api/java/util/concurrent/locks/Condition.html> In response to protecting a boolean. You could use volatile(<http://www.ibm.com/developerworks/java/library/j-jtp06197.html>). However the problem with not using Locks is that depending on how long your service is down for you will be spinning on while(isServiceDown()). By using a condition wait you tell the OS to sleep your thread until a spurious wake up (talked about in the java docs for Condition), or until the condition is signaled in the other thread.
Put one thread to sleep until a condition is resolved in another thread
[ "", "java", "concurrency", "locking", "conditional-statements", "countdownlatch", "" ]
I have started using Linq to SQL in a (bit DDD like) system which looks (overly simplified) like this: ``` public class SomeEntity // Imagine this is a fully mapped linq2sql class. { public Guid SomeEntityId { get; set; } public AnotherEntity Relation { get; set; } } public class AnotherEntity // Imagine this is a fully mapped linq2sql class. { public Guid AnotherEntityId { get; set; } } public interface IRepository<TId, TEntity> { Entity Get(TId id); } public class SomeEntityRepository : IRepository<Guid, SomeEntity> { public SomeEntity Get(Guid id) { SomeEntity someEntity = null; using (DataContext context = new DataContext()) { someEntity = ( from e in context.SomeEntity where e.SomeEntityId == id select e).SingleOrDefault<SomeEntity>(); } return someEntity; } } ``` Now, I got a problem. When I try to use SomeEntityRepository like this ``` public static class Program { public static void Main(string[] args) { IRepository<Guid, SomeEntity> someEntityRepository = new SomeEntityRepository(); SomeEntity someEntity = someEntityRepository.Get(new Guid("98011F24-6A3D-4f42-8567-4BEF07117F59")); Console.WriteLine(someEntity.SomeEntityId); Console.WriteLine(someEntity.Relation.AnotherEntityId); } } ``` everything works nicely until the program gets to the last WriteLine, because it throws an `ObjectDisposedException`, because the DataContext does not exist any more. I do see the actual problem, but how do I solve this? I guess there are several solutions, but none of those I have thought of to date would be good in my situation. * Get away from the repository pattern and using a new DataContext for each atomic part of work. + I really would not want to do this. A reason is that I do not want to be the applications to be aware of the repository. Another one is that I do not think making linq2sql stuff COM visible would be good. + Also, I think that doing `context.SubmitChanges()` would probably commit much more than I intended to. * Specifying DataLoadOptions to fetch related elements. + As I want my Business Logic Layer to just reply with some entities in some cases, I do not know which sub-properties they need to use. * Disabling lazy loading/delayed loading for all properties. + Not an option, because there are quite a few tables and they are heavily linked. This could cause a lot of unnecessary traffic and database load. * Some post on the internet said that using .Single() should help. + Apparently it does not ... Is there any way to solve this misery? BTW: We decided to use Linq t0 SQL because it is a relatively lightweight ORM solution and included with the .NET framework and Visual Studio. If the .NET Entity Framework would fit better in this pattern, it may be an option to switch to it. (We are not that far in the implementation, yet.)
Rick Strahl has a nice article about DataContext lifecycle management here: <http://www.west-wind.com/weblog/posts/246222.aspx>. Basically, the atomic action approach is nice in theory but you're going to need to keep your DataContext around to be able to track changes (and fetch children) in your data objects. See also: [Multiple/single instance of Linq to SQL DataContext](https://stackoverflow.com/questions/226127/multiplesingle-instance-of-linq-to-sql-datacontext) and [LINQ to SQL - where does your DataContext live?](https://stackoverflow.com/questions/196253/linq-to-sql-where-does-your-datacontext-live).
You have to either: 1) Leave the context open because you haven't fully decided what data will be used yet (aka, Lazy Loading). or 2) Pull more data on the initial load if you know you will need that other property. Explaination of the latter: [here](http://www.singingeels.com/Blogs/Nullable/2008/10/27/EntityFramework_Include_Equivalent_in_LINQ_to_SQL.aspx)
Problem using LINQ to SQL with one DataContext per atomic action
[ "", "c#", "linq-to-sql", "persistence", "ddd-repositories", "" ]
We're creating a web system using Java and Servlet technology (actually Wicket for the presentation layer) and we need our system to be available nearly always as our customers will be quite dependent on it. This has lead us to look for a good book focusing on the subject or another resource which explains how to set up a more redundant and fail safe architecture for our system. A non exclusive list of questions we have at the moment: * How do you have one domain name (like <http://www.google.com>) which are actually served by several servers with load balancing to distribute the users? Isn't there always a point which is weaker in such a solution(the two [as there can't be more] DNS servers for google.com in their case)? * It seems like a good idea to have several database servers for redundancy and load balancing. How is that set up? * If one of our web servers goes down we would like to have some kind of fail over and let users use one that is still up. Amongst other things the sessions have to be synchronized in some way. How is that set up? * Do we need some kind of synchronized transactions too? * Is Amazon Computer Cloud a good option for us? How do we set it up there? Are there any alternatives which are cost effective? * Do we need to run in a Java EE container like JBoss or Glassfish?
Regarding GlassFish, centralized administration through the admin GUI is a big help for environments with more than one appserver instance to manage. "Always available" is overloaded. It can be service availability with no session retention on failure, or it can mean data availability with session information backed up. Of course, GlassFish can do both. A couple of resources that may be of help regarding GlassFish and high availability: Guide to GlassFish High Availability: <http://www.sun.com/offers/details/glassfish_HAref_config.html> Setting up a GlassFish Cluster in 10 minutes: <http://blogs.oracle.com/jclingan/entry/glassfish_clustering_in_under_10> John Clingan, GlassFish Group Product Manager
The Liferay wiki has a [high availability guide](https://www.liferay.com/web/guest/community/wiki/-/wiki/Main/High+Availability+Guide) entry outlining an architecture that could serve as a starting point.
Book/Resource about setting up load balancing and fail over for Servlet based Java web application
[ "", "java", "web-applications", "load-balancing", "redundancy", "failovercluster", "" ]
I need to match (case insensitive) "abcd" and an optional trademark symbol Regex: `/abcd(™)?/gi` See example: ``` preg_match("/abcd(™)?/gi","AbCd™ U9+",$matches); print_r($matches); ``` When I run this, `$matches` isn't populated with anything... Not even created as an empty array. Any ideas?
How is your file encoded? PHP has got issues when it comes to unicode. In your case, try using the escape sequence `\x99` instead of directly embedding the TM symbol.
**Note:** I'm not a PHP guru. However, this seems to be an issue about character encodings. For example, your PHP file could be encoded as win-1252 (where ™ is encoded as `\x99`), and the data you are trying to match could be encoded as UTF-8 (where ™ is encoded as `\xe2\x84\xa2`), or vice versa (i.e. your file is UTF-8 and your data is win-1252). Try looking in this direction, and give us more information about what you are doing.
Why doesn't this regular expression work in PHP?
[ "", "php", "regex", "" ]
I've got the a SQL Server stored procedure with the following T-SQL code contained within: ``` insert into #results ([ID], [Action], [Success], [StartTime], [EndTime], [Process]) select 'ID' = aa.[ActionID], 'Action' = cast(aa.[Action] as int), 'Success' = aa.[Success], 'StartTime' = aa.[StartTime], 'EndTime' = aa.[EndTime], 'Process' = cast(aa.[Process] as int) from [ApplicationActions] aa with(nolock) where 0 = case when (@loggingLevel = 0) then 0 when (@loggingLevel = 1 and aa.[LoggingLevel] = 1) then 0 end and 1 = case when (@applicationID is null) then 1 when (@applicationID is not null and aa.[ApplicationID] = @applicationID) then 1 end and 2 = case when (@startDate is null) then 2 when (@startDate is not null and aa.[StartTime] >= @startDate) then 2 end and 3 = case when (@endDate is null) then 3 when (@endDate is not null and aa.[StartTime] <= @endDate) then 3 end and 4 = case when (@success is null) then 4 when (@success is not null and aa.[Success] = @success) then 4 end and 5 = case when (@process is null) then 5 when (@process is not null and aa.[Process] = @process) then 5 end ``` It's that "dynamic" WHERE clause that is bothering me. The user doesn't have to pass in every parameter to this stored procedure. Just the ones that they are interested in using as a filter for the output. How would I go about using SQL Server Studio or Profiler to test whether or not this store procedure is recompiling every time?
The following article explains how to find out if your stored procedure is recompiling: <http://it.toolbox.com/blogs/programming-life/sql-performance-abnormal-stored-procedure-recompiles-8105> Here's a quote from the appropriate section: > start SQL Profiler and start a new > trace, connect to our server and give > an appropriate trace name, select the > events tab and remove the already > existing events on the "Selected event > classes" list box. Now choose the > "Stored Procedures" node in the > "Available event classes" and add > SPComplete, SPRecompile, SPStarting, > SP:StmtStarting and SP:StmtCompleted. > Now choose the "data columns" tab and > select just about the right amount of > events and data columns that you need. > Add filters to reduce the number of > events you collect. I would filter by the name of your stored procedure.
Just offhand, you can simplify these: ``` 2 = case when (@startDate is null) then 2 when (@startDate is not null and aa.[StartTime] >= @startDate) then 2 end ``` to this: ``` (@startDate is null OR aa.[StartTime] >= @startDate) ``` As far as the recompile - is it declared `WITH RECOMPILE`?
How can I determine whether or not a stored procedure is recompiling every time?
[ "", "sql", "sql-server", "t-sql", "" ]
I have a couple of array's: ``` const string a_strs[] = {"cr=1", "ag=2", "gnd=U", "prl=12", "av=123", "sz=345", "rc=6", "pc=12345"}; const string b_strs[] = {"cr=2", "sz=345", "ag=10", "gnd=M", "prl=11", "rc=6", "cp=34", "cv=54", "av=654", "ct=77", "pc=12345"}; ``` which i then need to parse out for '=' and then put the values in the struct. (the rc key maps to the fc key in the struct), which is in the form of: ``` struct predict_cache_key { pck() : av_id(0), sz_id(0), cr_id(0), cp_id(0), cv_id(0), ct_id(0), fc(0), gnd(0), ag(0), pc(0), prl_id(0) { } int av_id; int sz_id; int cr_id; int cp_id; int cv_id; int ct_id; int fc; char gnd; int ag; int pc; long prl_id; }; ``` The problem I am encountering is that the array's are not in sequence or in the same sequence as the struct fields. So, I need to check each and then come up with a scheme to put the same into the struct. Any help in using C or C++ to solve the above?
This shouldn't be too hard. Your first problem is that you don't have a fixed sized array, so you'd have to pass the size of the array, or what I'd prefer you make the arrays NULL-terminated, e.g. `const string a_strs[] = {"cr=1", "ag=2", "gnd=U", NULL};` Then I would write a (private) helper function that parse the string: ``` bool parse_string(const string &str, char *buffer, size_t b_size, int *num) { char *ptr; strncpy(buffer, str.c_str(), b_size); buffer[b_size - 1] = 0; /* find the '=' */ ptr = strchr(buffer, '='); if (!ptr) return false; *ptr = '\0'; ptr++; *num = atoi(ptr); return true; } ``` then you can do what qrdl has suggested. in a simple for loop: ``` for (const string *cur_str = array; *cur_str; cur_str++) { char key[128]; int value = 0; if (!parse_string(*cur_string, key, sizeof(key), &value) continue; /* and here what qrdl suggested */ if (!strcmp(key, "cr")) cr_id = value; else if ... } ``` EDIT: you should probably use long instead of int and atol instead of atoi, because your prl\_id is of the type long. Second if there could be wrong formated numbers after the '=', you should use strtol, which can catch errors.
Probably I didn't get it correctly, but obvious solutions is to split each array element into `key` and `value` and then write lo-o-ong `if-else-if-else ...` sequence like ``` if (!strcmp(key, "cr")) my_struct.cr = value; else if (!strcmp(key, "ag")) my_struct.ag = value; ... ``` You can automate the creation of such sequence with the help of C preprocessor, e.g. `#define PROC_KEY_VALUE_PAIR(A) else if (!strcmp(key,#A)) my_struct.##A = value` Because of leading `else` you write the code this way: ``` if (0); PROC_KEY_VALUE_PAIR(cr); PROC_KEY_VALUE_PAIR(ag); ... ``` The only problem that some of you struct fields have `_id` sufffix - for them you'd need to create a bit different macro that will paste `_id` suffix
Initializing struct, using an array
[ "", "c++", "c", "parsing", "" ]
I'm looking to generate a random number and issue it to a table in a database for a particular user\_id. The catch is, the same number can't be used twice. There's a million ways to do this, but I'm hoping someone very keen on algorithms has a clever way of solving the problem in an elegant solution in that the following criteria is met: 1) The least amount of queries to the database are made. 2) The least amount of crawling through a data structure in memory is made. Essentially the idea is to do the following 1) Create a random number from 0 to 9999999 2) Check the database to see if the number exists OR 2) Query the database for all numbers 3) See if the returned result matches whatever came from the db 4) If it matches, repeat step 1, if not, problem is solved. Thanks.
No your algorithm is not scalable. What I've done before is to issue numbers serially (+1 each time) and then pass them through an XOR operation to jumble the bits thus giving me a seemingly random numbers. Of course they aren't really random, but they look so to users eyes. --- **[Edit]** Additional information This algorithm's logic goes like this you use a known sequence to generate unique numbers and then you deterministically manipulate them, so they don't look serial anymore. The general solution is to use some form of encryption, which in my case was an XOR flipflop, because its as fast as it can get, and it fulfills the guarantee that numbers will never collide. However you can use other forms of encryption, if you want prefer even more random looking numbers, over speed (say you don't need to generate many ids at a time). Now the important point in choosing an encryption algorithm is "the guarantee that numbers will never collide". And a way to prove if an encryption algorithm can fulfill this guarantee is to check if both the original number and the result of the encryption have the same number of bits, and that the the algorithm is reversible (bijection). [Thanks to **Adam Liss** & **CesarB** for exapanding on the solution]
Why don't you just use a GUID? Most languages should have a built-in way to do this. It's guaranteed to be unique (with very reasonable bounds).
Algorithm for generating a random number
[ "", "php", "mysql", "algorithm", "random", "pseudocode", "" ]
For example, I hate typing things like: ``` $x = mysql_escape_string(stripslashes($_GET['x'])); ``` Is there a way to alias those two functions in init.php or something without writing a separate function that takes one argument and returns that argument with those functions applied to it? My C/C++ is not very good, but I think this is sort of like #typedef but for functions?
This should do the trick : ``` // Macros $mes = "mysql_escape_string"; $ss = "stripslashes"; // Using your macros $x = $mes($ss($_GET['x'])); ``` Though I don't recommend coding like this at all. I'm just answering the question since you said you didn't want to create any new function and get a "#define"-like functionality.
I hope your example is not representative of your project. 1. `stripslashes()` shouldn't be necessary - if you find it is, turn off `magic_quotes_gpc` in your php.ini. 2. You should be using `mysql_real_escape_string()` (or a `prepare`/`execute` pair) instead of `mysql_escape_string()` and it should be where your SQL is being assembled, not where you are retrieving values off the URL. Fix those two problems and your code degenerates to ``` $x = $_GET['x']; ```
Is it possible to "symlink" a function in PHP easily - or alias the name to something else?
[ "", "php", "" ]
We have a dotnet web service that a java using customer wants to connect to. What is the best technology for them to use? Axis or Metro, or something else?
Theoretically you could do this with any standards compliant framework. In practice, the generated code (with the default settings) by some tools may not work for you. You may need for example to modify a namespace or add a SOAP header. You can do this for example with Axis2 and CXF, but some extra configuration is needed. I would recommend CXF over Axis2, because I think it's easier to configure. It also requires fewer megabytes of jar files to re-distribute.
WSDL is a standard language following the protocol in a correct way the technology shouldn't mind. only if this implementation requires to meet the time to market of your client. in that case use the one that can be implement more quickly.
What is the best way to connect to a DotNet web service from java?
[ "", "java", ".net", "web-services", "wsdl", "" ]
How can I open a web-page and receive its cookies using PHP? **The motivation**: I am trying to use [feed43](http://www.feed43.com) to create an RSS feed from the non-RSS-enabled HighLearn website (remote learning website). I found the web-page that contains the feed contents I need to parse, however, it requires to login first. Luckily, logging in can be done via a GET request so it's as easy as fopen()ing "<http://highlearn.website/login_page.asp?userID=foo&password=bar>" for example. But I still need to **get the cookies generated when I logged in**, pass the cookies to the real client (using setcookie() maybe?) and then redirect.
For a server-side HTTP client you should use the [cURL](https://www.php.net/curl) module. It will allow you to persist cookies across multiple requests. It also does some other neat things like bundling requests (curl\_multi) and transparently handling redirects. When it comes to returning a session to your user, I don't think this is possible. You would need to be able to overwrite the cookies of other domains. This would cause massive security issues, so no browser would implement it.
I've used the [Scriptable Browser](http://simpletest.sourceforge.net/en/browser_documentation.html) component from Simpletest for this kind of screen scraping before. It does a pretty good job of simulating a browser. You don't need to pass the session on to the real client (Even though it *may* be possible, depending on the site's security level) - You can simply let your PHP-script be a proxy between the target site and your end-user.
Simulating a cookie-enabled browser in PHP
[ "", "php", "curl", "curl-multi", "redirectwithcookies", "" ]
I'm working on an app that takes data from our DB and outputs an xml file using the FOR XML AUTO, ELEMENTS on the end of the generated query, followed by an XSLT to transform it the way we want. However in a particular case where we are generating some data using an sql scalar function, it always puts that element into a sub-table node named the same as the table node it's already in (so say it's a table xyz, it'd be `print("<xyz><node1></node1><xyz><generated-node-from-function></generated-node-from-function></xyz>");` No matter what I try (even directly manipulating a copy of the sql as generated by the app) it always seems to create this extra node layer, which causes problems later when we try to process this xml to extract the data later. Is there any particular property causing the xml generator in sql server to work this way, and is there any way to prevent it so I can keep the generated data node on the same level as the rest of the data for the table it's associated with? Edit: renamed columns/tables in some cases but otherwise should be the same sql. ``` SELECT * FROM (SELECT column1,column2,column3,iduser,jstart,jstop,jbatchperiod,jinactive,processed,column4,lock,column5,batchticketmicr,machineid,sjobopex,szopexrefid,jreceived,jstartopex,jstopopex,idspecialmicr,idp2batchoriginal,stateflags,bcrossrefid,bidentifier1,bidentifier2,bidentifier3,bidentifier4,bidentifier5,idexport,idimport,rsahash FROM table1) table1 LEFT JOIN (SELECT column21,ienvelope,isort,column1,idtemplate,processed,column4,lock,envelopetypecode,szqueuesvisitedunique,exportdate,jcompleted,status,ipriority,idbankaccount,iprioritybeforerzbump,fstoredrecondata,cscountyid,column10,column11,checkbox1,checkbox2,column12,column13,column14,xxxempfein,column15,column16,originalenvelopeid,column17,column18,xxxoag,trackingnumber,csldc,ecrossrefid,postmark,routingflags,eidentifier1,eidentifier2,eidentifier3,eidentifier4,eidentifier5,idexport FROM envelope) envelope ON table1.column1=Envelope.column1 LEFT JOIN (SELECT column21,column22,isort,column23,processed,side,pagetypecode,rawmicrline,rawscanline,rawbarcode,exportid,szlocandconf,szlocandconfpagefields,idformtemplate,szparms,rawmarksense,audittrail,audittrailelectronic,pixheight,pixwidth,ocrattemptcounter,idspecialmicr,idpageexception,pagemodifierflags,column10,csldc,rejectdate,rejectuser,rejectqueue,fsupervisorreject,xxxempno,xxxtraceno,xxxemplcnt,checkbox1,keyword,templatealtered,templateflags,pidentifier1,pidentifier2,pidentifier3,pidentifier4,pidentifier5,isscanlinevalid,idexport,clickcount FROM Table2) Table2 ON Envelope.column21=Page.column21 LEFT JOIN (select column22, column21, dbo.Fileimagepath(column21, column22) as path from Table2) Fileimg ON Table2.column21=FileImg.column21 AND Table2.column22=FileImg.column22 WHERE Envelope.column21 = 8 FOR XML AUTO, ELEMENTS ``` Another edit: basically FileImg's results are getting wrapped in an extra set of Table2 tags inside existing table2 tab with the rest of the data. Yet another Edit: Testing against another database with the same sql it worked correctly, it appears there is a bad setting in my database or the stored proc is different *goes to investigate farther*. If that doesn't work I'll try some of the other suggestions above, thanks for the help so far :)
Doing some further reserach, as of now it appears running a db in 2000 compat mode while on a 2005 sql server this problem is created, will not pin this until confirmed.
I would try to get rid of the sub query parts "(SELECT..." and do regular joins, like: ``` SELECT table1.column1, table1.column2, ..., envelope.column21, ... FROM table1 LEFT JOIN envelope on table1.column1 = envelope.column1 ... WHERE envelope.column21 = 8 FOR XML AUTO, ELEMENTS ``` To be clearer I ommitted most of your columns and joins. Just insert the columns you need and the njoins which are necessary. Does this return you the right XML or am I missing the point?
SQL Server and generatd xml with xml auto, elements
[ "", "sql", "sql-server", "xml", "t-sql", "" ]