Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
i am trying to compile this very simple piece of code ``` class myList { public: std::vector<std::string> vec; class Items { public: void Add(std::string str) { myList::vec.push_back(str); }; }items; }; int main() { myList newList; newList.items.Add("A"); } ``` what can i do to make this work without creating more objects that needed or overcomplicating stuff...
Add a couple of constructors and a pointer to the parent class. ``` #include <string> #include <vector> class myList { public: std::vector<std::string> vec; myList(): items(this) {} // Added class Items { public: Items(myList *ml): self(ml) {} // Added void Add(std::string str) { self->vec.push_back(str); // Changed }; myList *self; //Added }items; }; int main() { myList newList; newList.items.Add("A"); } ``` You need the myList() constructor, so it registers instances of itself with the instance of the inner class member variable. Then you need the Items constructor to store the pointer to the outer myList class instance. Finally in the Add method, you need to reference vec in the stored myList instance. As Catskul points out, the Item constructor mustn't actually do anything with the myList pointer it receives. I'd also like to say that though this answer is closer to the original intent, steveth45's answer is closer to what you would want to do in a real program.
This way you aren't exposing your class members directly. Your example seems over-architected a bit. Why put a std::vector into a class and then expose it as public? ``` class myList { private: std::vector<std::string> vec; public: void Add(std::string str) { vec.push_back(str); }; }; int main() { myList newList; newList.Add("A"); } ```
C++ Nested classes driving me crazy
[ "", "c++", "class", "nested", "" ]
I've got a PHP script that needs to invoke a shell script but doesn't care at all about the output. The shell script makes a number of SOAP calls and is slow to complete, so I don't want to slow down the PHP request while it waits for a reply. In fact, the PHP request should be able to exit without terminating the shell process. I've looked into the various `exec()`, `shell_exec()`, `pcntl_fork()`, etc. functions, but none of them seem to offer exactly what I want. (Or, if they do, it's not clear to me how.) Any suggestions?
If it "doesn't care about the output", couldn't the exec to the script be called with the `&` to background the process? **EDIT** - incorporating what @[AdamTheHut](https://stackoverflow.com/users/1103/adamthehutt) commented to this post, you can add this to a call to `exec`: ``` " > /dev/null 2>/dev/null &" ``` That will redirect both `stdio` (first `>`) and `stderr` (`2>`) to `/dev/null` and run in the background. There are other ways to do the same thing, but this is the simplest to read. --- An alternative to the above double-redirect: ``` " &> /dev/null &" ```
I used **at** for this, as it is really starting an independent process. ``` <?php `echo "the command"|at now`; ?> ```
Asynchronous shell exec in PHP
[ "", "php", "asynchronous", "shell", "" ]
I'm *considering* migrating my c# application from using custom GDI+ drawn controls to a WPF application with custom controls etc. I would like to know what's involved and what to expect. Are there any resources people can recommend that might help? Or indeed any personal experiences that might be beneficial?
*(I apologize in advance for the long post ... there was just so much I wanted to convey ... I hope it helps you.)* This is what we are doing now (migrating a Windows Forms application with heavy use of custom (GDI+) drawn controls to WPF). In fact, my role on the team was to build these GDI+ controls ... and now to build the WPF ones. I agree with Bijington that making your application completely 100% WPF from the ground up is the way to go ... if you can convince the powers that be to go that route. However, we ourselves are converting our Windows Forms application in-place, taking advantage of the [WPF interop](http://msdn.microsoft.com/en-us/library/ms742522.aspx) capabilities. There are some limitations, but overall it has been an effective approach (and not as frustrating as I would have expected). **What I would suggest is that you take one of your GDI+ controls and build the same control in WPF.** And then, when you are finished, throw it away and do it again. You will invariably learn something during the first effort ... and discover that there is a better way to do it instead. I would start with something small ... a custom button is a good place to begin. Doing the above will give you a taste for what is going to be required for everything else you want to do. One thing I would warn you about is WPF's learning curve, especially if you are coming from a Windows Forms background ... and especially if you are going to be building custom looking controls. As Abe has mentioned, it is a completely different world. WPF definitely brings a lot of power, but that power comes at a cost of learning how to use it. Abe mentions how custom controls in WPF are 'lookless' and that their 'look' can be provided with a ControlTemplate. This is just one of many ways in WPF to provide custom looking pieces of your user interface. Let me enumerate some of those additional ways: 1. Style an existing control using the styling capabilities of WPF. 2. Take advantage of WPF's content model and/or controls derived from ContentControl. This allow you to stick arbitrary looking 'content' into visuals of a control (e.g. maybe sticking a custom drawn shape into the middle of a button). 3. Compose a control out of other controls/elements by taking advantage of UserControl. 4. Derive from an existing control/class in WPF, extending it's behavior and providing a different default set of visuals. 5. Derive from FrameworkElement, creating a custom WPF element, by overriding some or all of the MeasureOverride, ArrangeOverride, and OnRender methods. 6. And more .... if you can believe it. In Windows Forms, it was like they gave you a hammer (UserControl) and a screwdriver (Control). However, in WPF ... they have given you the whole toolbox with all 100 tools. And this is part of the reason for the bigger than normal learning curve. However, now you can take that saw that you never had before and use it to saw off the end of a 2x4 instead of using the hammer and/or screwdriver to try and do the same thing. ### Resources *(The good news is that there are a lot out of resources out there to help you.)* 1. **Books** * Programming WPF by Chris Sells & Ian Griffiths (in particular, chapter 18) * Pro WPF by Matthew MacDonald (in particular, chapter 24) * WPF Unleashed by Adam Nathan (in particular, chapter 16) * Applications = Code + Markup by Charles Petzold (in particular, chapters 10, 11, & 12) * Essential WPF by Chris Anderson (in particular, chapter 3) My favorite books are Charles Petzold's book and Adam Nathan's book. However, chapter 18 of Programming WPF by Sells & Griffiths is really great overview of the subject, and in particular coverage of the question: Do I really need a custom control? 2. **Forums** * The [WPF Forum](http://social.msdn.microsoft.com/Forums/en-US/wpf/threads/) * StackOverflow Here are two posts in particular that you will want to take a look at ([one](https://stackoverflow.com/questions/183315/what-are-the-best-resources-for-learning-wpf-net), [two](https://stackoverflow.com/questions/129772/how-to-begin-wpf-development)). 3. **MSDN** I agree with Bijington that the [MSDN documentation](http://msdn.microsoft.com/en-us/library/ms754130.aspx) excellent. 4. **Blogs** In [one](https://stackoverflow.com/questions/129772/how-to-begin-wpf-development#154252) of the two StackOverflow posts that I reference in the Forums section above, I point to a set of blogs on my 'must read' list. In particular, I would especially point to the blogs of [Pavan Podila](http://blog.pixelingene.com/) and [Kevin Moore](http://work.j832.com/). Kevin Moore used to be the WPF program manger for the WPF controls and he has a nice set of controls called the [WPF Bag-o-Tricks](http://j832.com/bagotricks/) that are useful, but more importantly, controls that you can learn from. 5. **Samples, Samples, and more Samples** There are just a ton of samples out there. Almost too many! I would point to [Family.Show](http://www.codeplex.com/familyshow) (it was created as an end-to-end reference sample for WPF) and I would point to the [WPF SDK samples](http://msdn.microsoft.com/en-us/library/ms771633.aspx) and in particular to the [Control Customization samples](http://msdn.microsoft.com/en-us/library/ms771268.aspx) within that section.
There is a paradigm shift in how you develop controls for WPF. Instead of defining all the behavior and look for a control, you only define the intended behavior. This is the hardest aspect of migrating to WPF. Your control class defines a contract of behavior, and exposes properties that will be used to render, and a ControlTemplate is used to define how the control looks. This is also one of the most powerful features of WPF; at any point in the future, a consumer of your control can change how it looks without changing how it behaves. This allows for much easier theming of your controls.
C# transition between GDI+ and WPF
[ "", "c#", "wpf", "gdi+", "" ]
I could write myself a helper class that does this when given a functor, but I was wondering if there's a better approach, or if there's something already in the standard library (seems like there should be). Answers I've found on StackOverflow are all for C# which doesn't help me. Thanks
No - there isn't. Apache `commons-collections` has predicates for this sort of thing but the resultant code (using anonymous inner classes) is usually ugly and a pain to debug. Just use a basic **for-loop** until they bring [closures](http://javac.info) into the language
By using the [lambdaj](http://code.google.com/p/lambdaj/) library, for example you could find the top reputation users as it follows: ``` List<User> topUsers = select(users, having(on(User.class).getReputation(), greaterThan(20000))); ``` It has some advantages respect the Quaere library because it doesn't use any magic string, it is completely type safe and in my opinion it offers a more readable DSL.
Cleanest way to find objects matching certain criteria in a java.util.List?
[ "", "java", "list", "" ]
I maintain a vb.net forms application that prints various labels to label printers. (Label printers are just like any printer, just smaller print area/lower resolution) The system uses a legacy printing method that's supported in the printer hardware, but has been out of general use for over a decade. I'm adding logic to print from the PrintDocument class. I like the flexibility of the class, but layout is a bit tedious. (Defining the sizes/locations of each DrawString command, etc.) Are there any software products or open source UI designers for generating print document layout? The designer output must be something I can integrate into my code (dll is OK, just not a separate executable) and can not have a per user license. (Lots of users on my system)
Since what I need is fairly simple I went ahead and rolled my own simple desinger. Found at [a great little class](http://www.codeproject.com/KB/dotnet/Resize_Control_at_Runtime.aspx) that makes controls movable/resizable which saved a bunch of time. Thanks all for the ideas.
Have a look at this thread [Visual Print Design for .NET](https://stackoverflow.com/questions/182670/visual-print-design-for-net). Also, you might consider a PDF template that you can inject with the values, then print the PDF, not perfect, but it could work depending on your needs.
Printing in VB.Net/C# Forms Application -- Layout Designer?
[ "", "c#", ".net", "vb.net", "printing", "" ]
I want to have a function that will return the reverse of a list that it is given -- using recursion. How can I do that?
Append the first element of the list to a reversed sublist: ``` mylist = [1, 2, 3, 4, 5] backwards = lambda l: (backwards (l[1:]) + l[:1] if l else []) print backwards (mylist) ```
A bit more explicit: ``` def rev(l): if len(l) == 0: return [] return [l[-1]] + rev(l[:-1]) ``` --- This turns into: ``` def rev(l): if not l: return [] return [l[-1]] + rev(l[:-1]) ``` Which turns into: ``` def rev(l): return [l[-1]] + rev(l[:-1]) if l else [] ``` Which is the same as another answer. --- Tail recursive / CPS style (which python doesn't optimize for anyway): ``` def rev(l, k): if len(l) == 0: return k([]) def b(res): return k([l[-1]] + res) return rev(l[:-1],b) >>> rev([1, 2, 3, 4, 5], lambda x: x) [5, 4, 3, 2, 1] ```
How do I reverse a list using recursion in Python?
[ "", "python", "list", "recursion", "" ]
Here's the core problem: I have a .NET application that is using [COM interop](http://en.wikipedia.org/wiki/COM_Interop) in a separate AppDomain. The COM stuff seems to be loading assemblies back into the default domain, rather than the AppDomain from which the COM stuff is being called. What I want to know is: is this expected behaviour, or am I doing something wrong to cause these COM related assemblies to be loaded in the wrong AppDomain? Please see a more detailed description of the situation below... The application consists of 3 assemblies: - the main EXE, the entry point of the application. - common.dll, containing just an interface IController (in the IPlugin style) - controller.dll, containing a Controller class that implements IController and MarshalByRefObject. This class does all the work and uses COM interop to interact with another application. The relevant part of the main EXE looks like this: ``` AppDomain controller_domain = AppDomain.CreateDomain("Controller Domain"); IController c = (IController)controller_domain.CreateInstanceFromAndUnwrap("controller.dll", "MyNamespace.Controller"); result = c.Run(); AppDomain.Unload(controller_domain); ``` The common.dll only contains these 2 things: ``` public enum ControllerRunResult{FatalError, Finished, NonFatalError, NotRun} public interface IController { ControllerRunResult Run(); } ``` And the controller.dll contains this class (which also calls the COM interop stuff): ``` public class Controller: IController, MarshalByRefObject ``` When first running the application, Assembly.GetAssemblies() looks as expected, with common.dll being loaded in both AppDomains, and controller.dll only being loaded into the controller domain. After calling c.Run() however I see that assemblies related to the COM interop stuff have been loaded into the default AppDomain, and NOT in the AppDomain from which the COM interop is taking place. Why might this be occurring? And if you're interested, here's a bit of background: Originally this was a 1 AppDomain application. The COM stuff it interfaces with is a server API which is not stable over long periods of use. When a COMException (with no useful diagnostic information as to its cause) occurs from the COM stuff, the entire application has to restarted before the COM connection will work again. Simply reconnecting to the COM app server results in immediate COM exceptions again. To cope with this I have tried to move the COM interop stuff into a seperate AppDomain so that when the mystery COMExceptions occur I can unload the AppDomain in which it occurs, create a new one and start again, all without having to manually restart the application. That was the theory anyway...
Unfortunately, A COM component is loaded within Process Space and not within the context of an AppDomain. Thus, you will need to manually tear-down (Release and Unload) your Native DLLs (applies to both COM and P/Invoke). Simply destroying an appdomain will do you no good, but respawning the whole process shouldn't be necessary to reset COM state (simply recreating the COM object(s) should also normally work, this sounds like a bug within the component providers code, perhaps they can address it?) **References** [(TechNet) Process Address Space](http://msdn.microsoft.com/en-us/library/vstudio/kt21t9h7(v=vs.100).aspx) [(MSDN) Application Domains](http://msdn.microsoft.com/en-us/library/2bh4z9hs(v=vs.110).aspx) [(MSDN) Boundaries: Processes and AppDomains](http://technet.microsoft.com/en-us/library/ms189334(v=sql.105).aspx)
Here's the proof that Shaun Wilson's answer is correct ![Com App Domain](https://i.stack.imgur.com/BbYrE.png)
Does COM interop respect .NET AppDomain boundaries for assembly loading?
[ "", "c#", "com", "interop", "com-interop", "appdomain", "" ]
I have the following classes ``` public interface InterfaceBase { } public class ImplementA:InterfaceBase { } public class ImplementB:InterfaceBase { } public void TestImplementType<T>(T obj) where T: InterfaceBase { } ``` How to infer what the T is whether ImplementA or ImplementB? I tried to use ``` typeof(T) is ImplementA ``` but this expression is always evaluated to false. Edit: And how am I going to cast obj to ImplementA or ImplementB?
`obj is ImplementA`
Strictly, you should avoid too much specialization within generics. It would be cleaner to put any specialized logic in a member on the interface, so that any implementation can do it differently. However, there are a number of ways: You can test "obj" (assuming it is non-null) ``` bool testObj = obj is ImplementA; ``` You can test T for being typeof(ImplementA): ``` bool testEq = typeof(T) == typeof(ImplementA); ``` Likewise you can test it for being ImplementA or a subclass: ``` bool testAssign = typeof(ImplementA).IsAssignableFrom(typeof(T)); ```
Get the type of the generic parameter
[ "", "c#", "generics", "" ]
Is there a way to get the count of rows in all tables in a MySQL database without running a `SELECT count()` on each table?
``` SELECT SUM(TABLE_ROWS) FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = '{your_db}'; ``` [Note from the docs though:](https://dev.mysql.com/doc/refman/5.7/en/tables-table.html) For InnoDB tables, **the row count is only a rough estimate** used in SQL optimization. You'll need to use COUNT(\*) for exact counts (which is more expensive).
You can probably put something together with [Tables table](http://dev.mysql.com/doc/refman/5.0/en/tables-table.html). I've never done it, but it looks like it has a column for *TABLE\_ROWS* and one for *TABLE NAME*. To get rows per table, you can use a query like this: ``` SELECT table_name, table_rows FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = '**YOUR SCHEMA**'; ```
Get record counts for all tables in MySQL database
[ "", "mysql", "sql", "rowcount", "" ]
Say I have a struct "s" with an int pointer member variable "i". I allocate memory on the heap for i in the default constructor of s. Later in some other part of the code I pass an instance of s by value to some function. Am I doing a shallow copy here? Assume I didn't implement any copy constructors or assignment operators or anything for s... just the default constructor.
To follow up on what @[don.neufeld.myopenid.com] said, it is not only a shallow copy, but it is either (take your pick) a memory leak or a dangling pointer. ``` // memory leak (note that the pointer is never deleted) class A { B *_b; public: A() : _b(new B) { } }; // dangling ptr (who deletes the instance?) class A { B *_b; public: A() ... (same as above) ~A() { delete _b; } }; ``` To resolve this, there are several methods. **Always implement a copy constructor and operator= in classes that use raw memory pointers.** ``` class A { B *_b; public: A() ... (same as above) ~A() ... A(const A &rhs) : _b(new B(rhs._b)) { } A &operator=(const A &rhs) { B *b=new B(rhs._b); delete _b; _b=b; return *this; }; ``` Needless to say, this is a major pain and there are quite a few subtleties to get right. I'm not even totally sure I did it right here and I've done it a few times. Don't forget you have to copy all of the members - if you add some new ones later on, don't forget to add them in too! **Make the copy constructor and operator= private in your class.** This is the "lock the door" solution. It is simple and effective, but sometimes over-protective. ``` class A : public boost::noncopyable { ... }; ``` **Never use raw pointers.** This is simple and effective. There are lots of options here: * Use string classes instead of raw char pointers * Use std::auto\_ptr, boost::shared\_ptr, boost::scoped\_ptr etc Example: ``` // uses shared_ptr - note that you don't need a copy constructor or op= - // shared_ptr uses reference counting so the _b instance is shared and only // deleted when the last reference is gone - admire the simplicity! // it is almost exactly the same as the "memory leak" version, but there is no leak class A { boost::shared_ptr<B> _b; public: A() : _b(new B) { } }; ```
Yes, that's a shallow copy. You now have two copies of s (one in the caller, one on the stack as a parameter), each which contain a pointer to that same block of memory.
Question about shallow copy in C++
[ "", "c++", "memory-management", "constructor", "" ]
I am currently working in C/C++ in a Unix environment and am new to Linux environments. I would like to learn about the Linux OS and learn C# as the next level of programming language for my career. I decided to put Ubuntu Linux on my laptop. But I am not sure whether we can write, compile and run C# programs in Linux environments or not. The only IDE I know for C# is MS Visual Studio. Is there are any possible way to work in C# in a Linux environment? If I have no other option, I'll have both operating systems on my laptop - Vista to learn C# and Linux for the other OS.
Learn [Mono](http://www.mono-project.com/Main_Page). > The Mono Project is an open > development initiative sponsored by > Novell to develop an open source, UNIX > version of the Microsoft .NET > development platform. Its objective is > to enable UNIX developers to build and > deploy cross-platform .NET > Applications. The project implements > various technologies developed by > Microsoft that have now been submitted > to the ECMA for standardization. You can use the [MonoDevelop](http://monodevelop.com/Main_Page) IDE. > MonoDevelop is a free GNOME IDE > primarily designed for C# and other > .NET languages.
[Mono](http://www.mono-project.com) is an open source .NET compiler, runtime and library. [Monodevelop](http://monodevelop.com/) is an open source C# IDE, primarily intended for linux development. It includes a GUI designer.
C# in linux environment
[ "", "c#", "linux", "installation", "" ]
When working with my .Net 2.0 code base ReSharper continually recommends applying the latest c# 3.0 language features, most notably; convert simple properties into auto-implement properties or declaring local variables as var. Amongst others. When a new language feature arrives do you go back and religiously apply it across your existing code base or do you leave the code as originally written accepting that if new code is written using new language features there will be inconsistencies across your code?
If it ain't broke, don't fix it. Of course, if you have confidence in your unit tests, you can give it a whirl, but you shouldn't really go randomly changing code "just because". Of course - in some cases, simplifying code is a valid reason to make a change - but even something as innocent as switching to an auto-implemented property could break code that makes assumptions and uses reflection to update the fields directly. Or it could break serialization. Changing to "var" can actually give you a different (more specific) type, which might cause a different method overload to get selected, etc. So again; it comes down to your confidence in the unit tests. Other considerations: * does the rest of the team understand the new syntax yet? * does your project need to support C# 2.0 (for example, some open source projects might want to retain compatibility with C# 2.0). If neither of these are an issue, you should be OK to use the new features in new code... just be a *little* cautious before hitting "update all" on old code... Here's a trivial example of "var" as a breaking change: ``` static void Main() { using (TextReader reader = File.OpenText("foo.bar")) { // [HERE] Write(reader); } } static void Write(TextReader reader) { Console.Write(reader.ReadToEnd()); } static void Write(StreamReader reader) { throw new NotImplementedException(); } ``` Now switch to `var reader` on the line marked `[HERE]`...
I would simply maintain the code as I go. Eventually a large portion of the app will have been cleaned or tuned to the new features and improvements. Don't change something for the sake of changing it. If you don't get any performance or stability improvements there is no need to waste time updating code. C# 3 building on C# 2 and both are quite compatible. Hence each update should be reflected upon.
Retro fitting new language features C# (or any other language)
[ "", "c#", "resharper", "" ]
When I try to create a new task in the task scheduler via the Java ProcessBuilder class I get an access denied error an Windows Vista. On XP it works just fine. When I use the "Run as adminstrator" option it runs on Vista as well.. However this is a additional step requeried an the users might not know about this. When the user just double clicks on the app icon it will fail with access denied. My question is how can I force a java app to reuest admin privileges right after startup?
I'm not sure you can do it programmatically. If you have an installer for your app, you can add the registry key to force run as admin: > Path: > HKEY\_CURRENT\_USER\Software\Microsoft\Windows > NT\Currentversion\Appcompatflags\layers > > Key: << Full path to exe >> > > Value: RUNASADMIN > > Type: REG\_SZ
Have you considered wrapping your Java application in an .exe using launch4j? By doing this you can embed a manifest file that allows you to specify the "execution level" for your executable. In other words, you control the privileges that should be granted to your running application, effectively telling the OS to "Run as adminstrator" without requiring the user to manually do so. For example... build.xml: ``` <target name="wrapMyApp" depends="myapp.jar"> <launch4j configFile="myappConfig.xml" /> </target> ``` myappConfig.xml: ``` <launch4jConfig> <dontWrapJar>false</dontWrapJar> <headerType>gui</headerType> <jar>bin\myapp.jar</jar> <outfile>bin\myapp.exe</outfile> <priority>normal</priority> <downloadUrl>http://java.com/download</downloadUrl> <customProcName>true</customProcName> <stayAlive>false</stayAlive> <manifest>myapp.manifest</manifest> <jre> <path></path> <minVersion>1.5.0</minVersion> <maxVersion></maxVersion> <jdkPreference>preferJre</jdkPreference> </jre> </launch4jConfig> ``` myapp.manifest: ``` <?xml version="1.0" encoding="UTF-8" standalone="yes"?> <assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0"> <trustInfo xmlns="urn:schemas-microsoft-com:asm.v3"> <security> <requestedPrivileges> <requestedExecutionLevel level="highestAvailable" uiAccess="False" /> </requestedPrivileges> </security> </trustInfo> </assembly> ``` See <http://msdn.microsoft.com/en-us/library/bb756929.aspx> and the launch4j website for mode details.
Request admin privileges for Java app on Windows Vista
[ "", "java", "windows-vista", "scheduler", "access-denied", "" ]
I'm looking for a Java library that is geared towards network math and already tested. Nothing particularly fancy, just something to hold ips and subnets, and do things like print a subnet mask or calculate whether an IP is within a given subnet. Should I roll my own, or is there already a robust library for this?
We developed a Java IPv4 arithmetic library ourselves. See it here: <http://tufar.com/ipcalculator/> It is under BSD license.
[org.apache.lenya.ac.IPRange](http://lenya.apache.org/apidocs/2.0/org/apache/lenya/ac/IPRange.html) appears to have these features. The Apache Lenya project is an open-source content management system. It uses the Apache License, so you may be able to reuse just the code you need. (But as always, read the [license](http://lenya.apache.org/index/license.html) yourself; don't trust legal advice from some guy on the internet! :-)
A good Java library for network math
[ "", "java", "math", "networking", "" ]
The point of this question is to create the shortest **not abusively slow** Sudoku solver. This is defined as: **don't recurse when there are spots on the board which can only possibly be one digit**. Here is the shortest I have so far in python: ``` r=range(81) s=range(1,10) def R(A): bzt={} for i in r: if A[i]!=0: continue; h={} for j in r: h[A[j]if(j/9==i/9 or j%9==i%9 or(j/27==i/27)and((j%9/3)==(i%9/3)))else 0]=1 bzt[9-len(h)]=h,i for l,(h,i)in sorted(bzt.items(),key=lambda x:x[0]): for j in s: if j not in h: A[i]=j if R(A):return 1 A[i]=0;return 0 print A;return 1 R(map(int, "080007095010020000309581000500000300400000006006000007000762409000050020820400060")) ``` The last line I take to be part of the cmd line input, it can be changed to: ``` import sys; R(map(int, sys.argv[1]); ``` This is similar to other sudoku golf challenges, except that I want to eliminate unnecessary recursion. Any language is acceptable. The challenge is on!
I haven't really made much of a change - the algorithm is identical, but here are a few further micro-optimisations you can make to your python code. * No need for !=0, 0 is false in a boolean context. * a if c else b is more expensive than using [a,b][c] if you don't need short-circuiting, hence you can use `h[ [0,A[j]][j/9.. rest of boolean condition]`. Even better is to exploit the fact that you want 0 in the false case, and so multiply by the boolean value (treated as either `0*A[j]` (ie. 0) or `1*A[j]` (ie. `A[j]`). * You can omit spaces between digits and identifiers. eg "`9 or`" -> "`9or`" * You can omit the key to sorted(). Since you're sorting on the first element, a normal sort will produce effectively the same order (unless you're relying on stability, which it doesn't look like) * You can save a couple of bytes by omitting the .items() call, and just assign h,i in the next line to z[l] * You only use s once - no point in using a variable. You can also avoid using range() by selecting the appropriate slice of r instead (r[1:10]) * `j not in h` can become `(j in h)-1` (relying on True == 1 in integer context) * **[Edit]** You can also replace the first for loop's construction of h with a dict constructor and a generator expression. This lets you compress the logic onto one line, saving 10 bytes in total. More generally, you probably want to think about ways to change the algorithm to reduce the levels of nesting. Every level gives an additional byte per line within in python, which accumulates. Here's what I've got so far (I've switched to 1 space per indent so that you can get an accurate picture of required characters. Currently it's weighing in at 288 278, which is still pretty big. ``` r=range(81) def R(A): z={} for i in r: if 0==A[i]:h=dict((A[j]*(j/9==i/9or j%9==i%9or j/27==i/27and j%9/3==i%9/3),1)for j in r);z[9-len(h)]=h,i for l in sorted(z): h,i=z[l] for j in r[1:10]: if(j in h)-1: A[i]=j if R(A):return A A[i]=0;return[] return A ```
``` r=range(81) def R(A): if(0in A)-1:yield A;return def H(i):h=set(A[j]for j in r if j/9==i/9or j%9==i%9or j/27==i/27and j%9/3==i%9/3);return len(h),h,i l,h,i=max(H(i)for i in r if not A[i]) for j in r[1:10]: if(j in h)-1: A[i]=j for S in R(A):yield S A[i]=0 ``` 269 characters, and it finds all solutions. Usage (not counted in char count): ``` sixsol = map(int, "300000080001093000040780003093800012000040000520006790600021040000530900030000051") for S in R(sixsol): print S ```
Smart Sudoku Golf
[ "", "python", "perl", "code-golf", "sudoku", "" ]
I'm just concerned about Windows, so there's no need to go into esoterica about Mono compatibility or anything like that. I should also add that the app that I'm writing is WPF, and I'd prefer to avoid taking a dependency on `System.Windows.Forms` if at all possible.
Give this a shot... ``` using System; using System.Collections.Generic; using System.Text; using System.Management; namespace WMITestConsolApplication { class Program { static void Main(string[] args) { AddInsertUSBHandler(); AddRemoveUSBHandler(); while (true) { } } static ManagementEventWatcher w = null; static void AddRemoveUSBHandler() { WqlEventQuery q; ManagementScope scope = new ManagementScope("root\\CIMV2"); scope.Options.EnablePrivileges = true; try { q = new WqlEventQuery(); q.EventClassName = "__InstanceDeletionEvent"; q.WithinInterval = new TimeSpan(0, 0, 3); q.Condition = "TargetInstance ISA 'Win32_USBControllerdevice'"; w = new ManagementEventWatcher(scope, q); w.EventArrived += USBRemoved; w.Start(); } catch (Exception e) { Console.WriteLine(e.Message); if (w != null) { w.Stop(); } } } static void AddInsertUSBHandler() { WqlEventQuery q; ManagementScope scope = new ManagementScope("root\\CIMV2"); scope.Options.EnablePrivileges = true; try { q = new WqlEventQuery(); q.EventClassName = "__InstanceCreationEvent"; q.WithinInterval = new TimeSpan(0, 0, 3); q.Condition = "TargetInstance ISA 'Win32_USBControllerdevice'"; w = new ManagementEventWatcher(scope, q); w.EventArrived += USBInserted; w.Start(); } catch (Exception e) { Console.WriteLine(e.Message); if (w != null) { w.Stop(); } } } static void USBInserted(object sender, EventArgs e) { Console.WriteLine("A USB device inserted"); } static void USBRemoved(object sender, EventArgs e) { Console.WriteLine("A USB device removed"); } } } ```
There are much less cumbersome ways of doing this than using WMI polling - just capture WM\_DEVICECHANGE: <http://msdn.microsoft.com/en-us/library/aa363215.aspx>
How do I detect when a removable disk is inserted using C#?
[ "", "c#", "wpf", "windows", "" ]
I'm trying to submit a form with javascript. Firefox works fine but IE complains that "Object doesn't support this property or method" on the submit line of this function: ``` function submitPGV(formName, action) { var gvString = ""; pgVisibilities.each(function(pair) { gvString += pair.key + ":" + pair.value + ","; }); $('pgv_input').value = gvString; var form = $(formName); form.action = action; form.submit(); } ``` Called here: ``` <a href="javascript:submitPGV('ProductGroupVisibility','config/productgroupvis/save')"> ``` Here's the form: ``` <form id="ProductGroupVisibility" action="save" method="post"> <input type="hidden" name="ows_gv..PGV" id="pgv_input" value=""/> </form> ``` Any ideas?
Try checking the type of the element IE is selecting: ``` // For getting element with id you must use # alert( typeof( $( '#ProductGroupVisibility' ))); ``` It is possible there is something else on the page with that ID that IE selects before the form.
What `name` does your `<input type="submit">` have? If you called it "submit", you have overridden the `form.submit()` function, much the same way an input called "foo" would generate a `form.foo` property. That would explain the behavior.
Javascript form submit: Object doesn't support this property or method (IE7)
[ "", "javascript", "internet-explorer", "" ]
Just wondering if anyone has any favourite SQL references they to use when creating new queries. Possibly something that shows syntax, or available functions?
If you're looking for one with just very basic functions you can try this to see if it fits your need. <http://www.sql.su/> You might have to paste the parts that you want into a better printing format as the top of the page has google ads =(
<http://blog.sqlauthority.com/2008/10/02/sql-server-2008-cheat-sheet-one-page-pdf-download/>
SQL Cheatsheet?
[ "", "sql", "" ]
How can I check if a string ends with a particular character in JavaScript? Example: I have a string ``` var str = "mystring#"; ``` I want to know if that string is ending with `#`. How can I check it? 1. Is there a `endsWith()` method in JavaScript? 2. One solution I have is take the length of the string and get the last character and check it. Is this the best way or there is any other way?
**UPDATE (Nov 24th, 2015):** This answer is originally posted in the year 2010 (SIX years back.) so please take note of these insightful comments: * [Shauna](https://stackoverflow.com/users/570040/shauna) - > Update for Googlers - Looks like ECMA6 adds this function. The MDN article also shows a polyfill. <https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/endsWith> * [T.J. Crowder](https://stackoverflow.com/users/157247/t-j-crowder) - > Creating substrings isn't expensive on modern browsers; it may well have been in 2010 when this answer was posted. These days, the simple `this.substr(-suffix.length) === suffix` approach is fastest on Chrome, the same on IE11 as indexOf, and only 4% slower (fergetaboutit territory) on Firefox: <https://jsben.ch/OJzlM> And faster across the board when the result is false: [jsperf.com/endswith-stackoverflow-when-false](http://jsperf.com/endswith-stackoverflow-when-false) **Of course, with ES6 adding endsWith, the point is moot. :-)** --- **ORIGINAL ANSWER:** I know this is a year old question... but I need this too and I need it to work cross-browser so... **combining everyone's answer and comments** and simplifying it a bit: ``` String.prototype.endsWith = function(suffix) { return this.indexOf(suffix, this.length - suffix.length) !== -1; }; ``` * Doesn't create a substring * Uses native `indexOf` function for fastest results * Skip unnecessary comparisons using the second parameter of `indexOf` to skip ahead * Works in Internet Explorer * NO Regex complications --- Also, if you don't like stuffing things in native data structure's prototypes, here's a standalone version: ``` function endsWith(str, suffix) { return str.indexOf(suffix, str.length - suffix.length) !== -1; } ``` --- **EDIT:** As noted by @hamish in the comments, if you want to err on the safe side and check if an implementation has already been provided, you can just adds a `typeof` check like so: ``` if (typeof String.prototype.endsWith !== 'function') { String.prototype.endsWith = function(suffix) { return this.indexOf(suffix, this.length - suffix.length) !== -1; }; } ```
``` /#$/.test(str) ``` will work on all browsers, doesn't require monkey patching `String`, and doesn't require scanning the entire string as `lastIndexOf` does when there is no match. If you want to match a constant string that might contain regular expression special characters, such as `'$'`, then you can use the following: ``` function makeSuffixRegExp(suffix, caseInsensitive) { return new RegExp( String(suffix).replace(/[$%()*+.?\[\\\]{|}]/g, "\\$&") + "$", caseInsensitive ? "i" : ""); } ``` and then you can use it like this ``` makeSuffixRegExp("a[complicated]*suffix*").test(str) ```
endsWith in JavaScript
[ "", "javascript", "string", "ends-with", "" ]
I have just noticed that a multidimensional array in C# does not implement `IEnumerable<T>`, while it does implement `IEnumerable`. For single-dimensional arrays, both `IEnumerable<T>` and `IEnumerable` are implemented. Why this difference? If a multi-dimensional array is `IEnumerable`, surely it should also implement the generic version? I noticed this because I tried to use an extension method on a multidimensional array, which fails unless you use `Cast<T>` or similar; so I can definitely see the an argument for making multidimensional arrays implement `IEnumerable<T>`. To clarify my question in code, I would expect the following code to print `true` four times, while it actually prints `true`, `false`, `true`, `true`: ``` int[] singleDimensionArray = new int[10]; int[,] multiDimensional = new int[10, 10]; Debug.WriteLine(singleDimensionArray is IEnumerable<int>); Debug.WriteLine(multiDimensional is IEnumerable<int>); Debug.WriteLine(singleDimensionArray is IEnumerable); Debug.WriteLine(multiDimensional is IEnumerable); ```
The CLR has two different kinds of arrays: *vectors* which are guaranteed to be one-dimensional with a lower bound of 0, and more general arrays which can have non-zero bounds and a rank other than 0. From section 8.9.1 of the CLI spec: > Additionally, a created vector with > element type T, implements the > interface > `System.Collections.Generic.IList<U>` > (§8.7), where U := T. I have to say it seems pretty weird to me. Given that it already implements `IEnumerable` I don't see why it shouldn't implement `IEnumerable<T>`. It wouldn't make as much sense to implement `IList<T>`, but the simple generic interface would be fine. If you want this, you could either call `Cast<T>` (if you're using .NET 3.5) or write your own method to iterate through the array. To avoid casting you'd have to write your own method which found the lower/upper bounds of each dimension, and fetched things that way. Not terribly pleasant.
There is a workaround: you can convert any multidimensional array to an IEnumerable ``` public static class ArrayExtensions { public static IEnumerable<T> ToEnumerable<T>(this Array target) { foreach (var item in target) yield return (T)item; } } ```
Why do C# multidimensional arrays not implement IEnumerable<T>?
[ "", "c#", ".net", "arrays", "multidimensional-array", "" ]
What is the best way to get the application name (i.e MyApplication.exe) of the executing assembly from a referenced class library in C#? I need to open the application's app.config to retrieve some appSettings variables for the referenced DLL.
If you want to get the current appdomain's config file, then all you need to do is: `ConfigurationManager.AppSettings`.... (this requires a reference to System.Configuration of course). To answer your question, you can do it as Ray said (or use `Assembly.GetExecutingAssembly().FullName`) but I think the problem is easier solved using `ConfigurationManager`.
To get the answer to the question title: ``` // Full-name, e.g. MyApplication, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null string exeAssembly = Assembly.GetEntryAssembly().FullName; // or just the "assembly name" part (e.g. "MyApplication") string exeAssemblyName = Assembly.GetEntryAssembly().GetName().Name; ``` As mentioned by @Ben, since you mention wanting to get the configuration information, use the `ConfigurationManager` class.
Get executing assembly name from referenced DLL in C#
[ "", "c#", ".net", "" ]
I have two lists that are of the same length, is it possible to loop through these two lists at once? I am looking for the correct syntax to do the below ``` foreach itemA, itemB in ListA, ListB { Console.WriteLine(itemA.ToString()+","+itemB.ToString()); } ``` do you think this is possible in C#? And if it is, what is the lambda expression equivalent of this?
# Modern Answer LINQ now has a [built-in Zip method](https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable.zip), so you don't need to create your own. The resulting sequence is as long as the shortest input. Zip currently (as of .NET Core 3.0) has 2 overloads. The simpler one returns a sequence of tuples. It lets us produce some very terse code that's close to the original request: ``` int[] numbers = { 1, 2, 3, 4 }; string[] words = { "one", "two", "three" }; foreach (var (number, word) in numbers.Zip(words)) Console.WriteLine($"{number}, {word}"); // 1, one // 2, two // 3, three ``` Or, the same thing but without tuple unpacking: ``` foreach (var item in numbers.Zip(words)) Console.WriteLine($"{item.First}, {item.Second}"); ``` The other overload (which appeared earlier than Core 3.0) takes a mapping function, giving you more control over the result. This example returns a sequence of strings, but you could return a sequence of whatever (e.g. some custom class). ``` var numbersAndWords = numbers.Zip(words, (number, word) => $"{number}, {word}"); foreach (string item in numbersAndWords) Console.WriteLine(item); ``` If you are using LINQ on regular objects (as opposed to using it to generate SQL), you can also check out [MoreLINQ](https://github.com/morelinq/MoreLINQ), which provides several zipping methods. Each of those methods takes up to 4 input sequences, not just 2: * `EquiZip` - An exception is thrown if the input sequences are of different lengths. * `ZipLongest` - The resulting sequence will always be as long as the longest of input sequences where the default value of each of the shorter sequence element types is used for padding. * `ZipShortest` - The resulting sequence is as short as the shortest input sequence. See their [examples](https://github.com/morelinq/examples) and/or [tests](https://github.com/morelinq/MoreLINQ/tree/master/MoreLinq.Test) for usage. It seems MoreLINQ's zipping came before regular LINQ's, so if you're stuck with an old version of .NET, it might be a good option.
[edit]: to clarify; this is useful in the generic LINQ / `IEnumerable<T>` context, where you **can't use** an indexer, because a: it doesn't exist on an enumerable, and b: you can't guarantee that you can read the data more than once. Since the OP mentions lambdas, it occurs that LINQ might not be too far away (and yes, I do realise that LINQ and lambdas are not quite the same thing). It sounds like you need the missing `Zip` operator; you can spoof it: ``` static void Main() { int[] left = { 1, 2, 3, 4, 5 }; string[] right = { "abc", "def", "ghi", "jkl", "mno" }; // using KeyValuePair<,> approach foreach (var item in left.Zip(right)) { Console.WriteLine("{0}/{1}", item.Key, item.Value); } // using projection approach foreach (string item in left.Zip(right, (x,y) => string.Format("{0}/{1}", x, y))) { Console.WriteLine(item); } } // library code; written once and stuffed away in a util assembly... // returns each pais as a KeyValuePair<,> static IEnumerable<KeyValuePair<TLeft,TRight>> Zip<TLeft, TRight>( this IEnumerable<TLeft> left, IEnumerable<TRight> right) { return Zip(left, right, (x, y) => new KeyValuePair<TLeft, TRight>(x, y)); } // accepts a projection from the caller for each pair static IEnumerable<TResult> Zip<TLeft, TRight, TResult>( this IEnumerable<TLeft> left, IEnumerable<TRight> right, Func<TLeft, TRight, TResult> selector) { using(IEnumerator<TLeft> leftE = left.GetEnumerator()) using (IEnumerator<TRight> rightE = right.GetEnumerator()) { while (leftE.MoveNext() && rightE.MoveNext()) { yield return selector(leftE.Current, rightE.Current); } } } ```
Looping through 2 lists at once
[ "", "c#", "list", "" ]
I have this Array i wrote a function MostFreq that takes an array of integers and return 2 values : the more frequent number in the array and its frequency check this code i worte what do you think ? is there a better way to do it? ``` static void Main() { int [] M={4,5,6,4,4,3,5,3}; int x; int f=MyMath.MostFreq(M,out x ); console.WriteLine("the most Frequent Item = {0} with frequency = {1}",x,f); } ``` ===== in the class Mymath ``` public static int MostFreq(int[] _M, out int x) { //First I need to sort the array in ascending order int Max_Freq, No_Freq, i, k; Array.Sort(_M); k = _M[0]; Max_Freq = 0; i = 0; x = 0; while (i < _M.Length) { //No_Freq= the frequency of the current number No_Freq = 0; //X here is the number which is appear in the array Frequently while (k == _M[i]) { No_Freq++; i++; if (i == _M.Length) break; } if (No_Freq > Max_Freq) { //so it will be printed the same Max_Freq = No_Freq; x = k; } if (i < _M.Length) k = _M[i]; } return (Max_Freq); } ```
LINQ it up. I know this is in VB but you should be able to convert it to C#: ``` Dim i = From Numbers In ints _ Group Numbers By Numbers Into Group _ Aggregate feq In Group Into Count() _ Select New With {.Number = Numbers, .Count = Count} ``` EDIT: Now in C# too: ``` var i = from numbers in M group numbers by numbers into grouped select new { Number = grouped.Key, Freq = grouped.Count()}; ```
Assuming you can't use LINQ, I'd probably approach the algorithm like this: * Create Key/Value dictionary * Iterate your array, add a key the dictionary for each unique elem, increment the value each time that element is repeated. * Walk the dictionary keys, and return the elem with the highest value. This isn't a great solution but it is simple, ContainsKey is an O(1) lookup, so you'll be at most iterating your array twice.
The Most frequent Number in an array
[ "", "c#", "algorithm", "" ]
If I have a key set of 1000, what is a suitable size for my Hash table, and how is that determined?
It depends on the load factor (the "percent full" point where the table will increase its size and re-distribute its elements). If you know you have exactly 1000 entries, and that number will never change, you can just set the load factor to 1.0 and the initial size to 1000 for maximum efficiency. If you weren't sure of the exact size, you could leave the load factor at its default of 0.75 and set your initial size to 1334 (expected size/LF) for *really* good performance, at a cost of extra memory. You can use the following constructor to set the load factor: ``` Hashtable(int initialCapacity, float loadFactor) ```
You need to factor in the hash function as well. one rule of thumb suggests make the table size about double, so that there is room to expand, and hopefully keep the number of collisions small. Another rule of thumb is to assume that you are doing some sort of modulo related hashing, then round your table size up to the next largest prime number, and use that prime number as the modulo value. What kind of things are you hashing? More detail should generate better advice.
Chosing a suitable table size for a Hash
[ "", "java", "hash", "hashtable", "" ]
What is the best way to read and/or set Internet Explorer options from a web page in Javascript? I know that these are in registry settings. For example, I'm using the [JavaScript Diagram Builder](http://www.lutanho.net/diagram/) to dynamically generate bar charts within a web page. This uses the background color in floating DIVs to generate the bars. I would like to be able to read the browser setting for printing background colors, and if not checked, either warn the user that the colors won't print, or programatically select this option. EDIT: As I think about the products that do something similar, I think they mostly just test whether Java or JavaScript or Cookies are disabled, which can be done without reading the registry. So I guess the consensus is that what I want to do shouldn't be attempted.
Web pages have no business reading users' settings, therefore there is no interface for this.
You can style the bars using a whopping left border instead of using a background colour. Like this: ``` <style> div.bar { width:1px; border-left:10px solid red; } </style> <div class="bar" style="height:100px"></div> ``` Obviously depends on the versatility of the product you're using. But I don't see why it would hurt to do this in a print style sheet at least.
Best way to read/set IE options?
[ "", "javascript", "internet-explorer", "settings", "registry", "" ]
We have a JavaScript function named "move" which does just "windows.location.href = *any given anchor*". This function works on IE, Opera and Safari, but somehow is ignored in Firefox. Researching on Google doesn't produce a satisfactory answer **why** it doesn't work. Does any JavaScript guru knows about this behavior, and what would be the best practice to jump to an anchor via JavaScript?
Have you tried just using ``` window.location = 'url'; ``` In some browsers, `window.location.href` is a read-only property and is not the best way to set the location (even though technically it should allow you to). If you use the `location` property on its own, that should redirect for you in all browsers. Mozilla's documentation has a pretty detailed explanation of how to use the `window.location` object. <https://developer.mozilla.org/en/DOM/window.location>
If you are trying to call this javascript code after an event that is followed by a callback then you must add another line to your function: ``` function JSNavSomewhere() { window.location.href = myUrl; return false; } ``` in your markup for the page, the control that calls this function on click must return this function's value ``` <asp:button ........ onclick="return JSNavSomewhere();" /> ``` The false return value will cancel the callback and the redirection will now work. Why this works in IE? Well I guess they were thinking differently on the issue when they prioritized the redirection over the callback. Hope this helps!
windows.location.href not working on Firefox3
[ "", "javascript", "firefox", "" ]
What is the best way to set the time on a remote machine remotely? The machine is running Windows XP and is receiving the new time through a web service call. The goal is to keep the remote machines in synch with the server. The system is locked down so that our web service is the only access, so I cannot use a time server on each remote machine.
I would use Windows built-in internet time abilities. You can set up a [time server](http://en.wikipedia.org/wiki/Time_server) on your server, have it get time from a 2nd-tier timeserver, and have all your client machines get time from it. I've been down the application-setting-system-time road before.
This is the Win32 API call for setting system time: ``` [StructLayout(LayoutKind.Sequential)] public struct SYSTEMTIME { public short wYear; public short wMonth; public short wDayOfWeek; public short wDay; public short wHour; public short wMinute; public short wSecond; public short wMilliseconds; } [DllImport("kernel32.dll", SetLastError=true)] public static extern bool SetSystemTime(ref SYSTEMTIME theDateTime ); ``` I'm not exactly sure how you would get the security worked out such that you could execute that function on the client, though. You can get a lot more detail on setting system time at [PInvoke](http://www.pinvoke.net/default.aspx/kernel32/SetSystemTime.html).
Set time programmatically using C#
[ "", "c#", "time", "" ]
I have a Java maven project which includes XSLT transformations. I load the stylesheet as follows: ``` TransformerFactory tFactory = TransformerFactory.newInstance(); DocumentBuilderFactory dFactory = DocumentBuilderFactory .newInstance(); dFactory.setNamespaceAware(true); DocumentBuilder dBuilder = dFactory.newDocumentBuilder(); ClassLoader cl = this.getClass().getClassLoader(); java.io.InputStream in = cl.getResourceAsStream("xsl/stylesheet.xsl"); InputSource xslInputSource = new InputSource(in); Document xslDoc = dBuilder.parse(xslInputSource); DOMSource xslDomSource = new DOMSource(xslDoc); Transformer transformer = tFactory.newTransformer(xslDomSource); ``` The stylesheet.xsl has a number of statements. These appear to be causing problems, when I try to run my unit tests I get the following errors: ``` C:\Code\workspace\app\dummy.xsl; Line #0; Column #0; Had IO Exception with stylesheet file: footer.xsl C:\Code\workspace\app\dummy.xsl; Line #0; Column #0; Had IO Exception with stylesheet file: topbar.xsl ``` The include statements in the XSLT are relative links ``` xsl:include href="footer.xsl" xsl:include href="topbar.xsl" ``` I have tried experimenting and changing these to the following - but I still get the error. ``` xsl:include href="xsl/footer.xsl" xsl:include href="xsl/topbar.xsl" ``` Any ideas? Any help much appreciated.
Solved my problem using a URIResolver. ``` class MyURIResolver implements URIResolver { @Override public Source resolve(String href, String base) throws TransformerException { try { ClassLoader cl = this.getClass().getClassLoader(); java.io.InputStream in = cl.getResourceAsStream("xsl/" + href); InputSource xslInputSource = new InputSource(in); Document xslDoc = dBuilder.parse(xslInputSource); DOMSource xslDomSource = new DOMSource(xslDoc); xslDomSource.setSystemId("xsl/" + href); return xslDomSource; } catch (... ``` And assigning this with the TransformerFactory ``` tFactory.setURIResolver(new MyURIResolver()); ```
URIResolver can also be used in a more straightforward way as below: ``` class XsltURIResolver implements URIResolver { @Override public Source resolve(String href, String base) throws TransformerException { try{ InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("xslts/" + href); return new StreamSource(inputStream); } catch(Exception ex){ ex.printStackTrace(); return null; } } } ``` Use the URIResolver with TransformerFactory as shown below: ``` TransformerFactory transFact = TransformerFactory.newInstance(); transFact.setURIResolver(new XsltURIResolver()); ``` Or with a lambda expression: ``` transFact.setURIResolver((href, base) -> { final InputStream s = this.getClass().getClassLoader().getResourceAsStream("xslts/" + href); return new StreamSource(s); }); ```
Transformation Failing due to xsl:include
[ "", "java", "xslt", "" ]
On a recent project I have been working on in C#/ASP.NET I have some fairly complicated JavaScript files and some nifty Style Sheets. As these script resources grow in size it [is advisable to minify the resources](http://developer.yahoo.com/yui/compressor/) and keep your web pages as light as possible, of course. I know many developers who hand-feed their JavaScript resources into compressors after debugging and then deploy their applications. When it comes to source control and automated builds in the satisfying world of continuous integration (thank you [CruiseControl.NET](http://confluence.public.thoughtworks.org/display/CCNET/Welcome+to+CruiseControl.NET)); hand compression will simply not do. The only way to maintain source control and offer compressed resources is to keep JS/CSS source & their minified brethren in a separate directory structure. Then register only one set of resources or the other in code-behind. However, if a developer makes a change to JS/CSS source and then fails to re-compact it and check in both versions, then you’re code-line is now out of sync. Not to mention inelegant. I am thinking that it would be nice to write a custom executable (if one does not exist yet) for the CC.NET task block which would find and compress all JavaScript and CSS resources in the target directory after the build action but before the asp.net publish to target. This way, developers would only work on JS and CSS source and users would only get the minified resources. **Is there an application that already performs this task and if not, what kind of resource(s) should I look to install on the build server to have CC.NET execute?** (The [closest question](https://stackoverflow.com/questions/258781/best-packing-strategy-for-js-during-continuous-integration) I could find here to this one required NAnt, which is not an option in my case.) **EDIT:** Dave Ward now has a great article on [how to automatically minify in Visual Studio](http://encosia.com/2009/05/20/automatically-minify-and-combine-javascript-in-visual-studio/) at his site.
The [MSBuildCommunityTasks Project](https://github.com/loresoft/msbuildtasks/) has a few MSBuild tasks that may do what you are looking for including Merge and JSCompress. You could add these into your MSBuild project in the AfterBuild target to allow the project to perform this action every time the project is built and nothing would ever be out of sync. Your web application could then reference the compacted version for run but the developers would edit the full versions. Nothing else would be needed on the server except the MSBuild community tasks assembly. You can put this assembly in your own source tree and reference from there and your CI build should get that assembly and everything it needs when it builds.
Another JS (and CSS!) compression library for MSBuild: <http://www.codeplex.com/YUICompressor> This is a .NET port of the java-based [Yahoo! compressor](http://developer.yahoo.com/yui/compressor/).
Script Minification and Continuous Integration with MSBuild
[ "", "javascript", "msbuild", "continuous-integration", "build-automation", "minify", "" ]
As the title says really. I've had a look at inheriting from TextBox, but the only sensible override was "OnKeyDown", but that just gives me a key from the Key enum (with no way to use Char.IsNumeric()).
Take a look at NumericUpDown in the Toolkit <http://codeplex.com/Silverlight> and maybe you can use that or look at the source to implement your own numeric textbox.
I took Nidhal's suggested answer and edited it a bit to handle the shift case for the characters above the digits (ie. !@#$%^&\*()) since that solution will still allow those characters in the textbox. ``` private void NumClient_KeyDown(object sender, KeyEventArgs e) { // Handle Shift case if (Keyboard.Modifiers == ModifierKeys.Shift) { e.Handled = true; } // Handle all other cases if (!e.Handled && (e.Key < Key.D0 || e.Key > Key.D9)) { if (e.Key < Key.NumPad0 || e.Key > Key.NumPad9) { if (e.Key != Key.Back) { e.Handled = true; } } } } ```
How to create a numeric textbox in Silverlight?
[ "", "c#", ".net", "silverlight", "textbox", "silverlight-2.0", "" ]
Imagine I have a process that starts several child processes. The parent needs to know when a child exits. I can use `waitpid`, but then if/when the parent needs to exit I have no way of telling the thread that is blocked in `waitpid` to exit gracefully and join it. It's nice to have things clean up themselves, but it may not be that big of a deal. I can use `waitpid` with `WNOHANG`, and then sleep for some arbitrary time to prevent a busy wait. However then I can only know if a child has exited every so often. In my case it may not be super critical that I know when a child exits right away, but I'd like to know ASAP... I can use a signal handler for `SIGCHLD`, and in the signal handler do whatever I was going to do when a child exits, or send a message to a different thread to do some action. But using a signal handler obfuscates the flow of the code a little bit. What I'd really like to do is use `waitpid` on some timeout, say 5 sec. Since exiting the process isn't a time critical operation, I can lazily signal the thread to exit, while still having it blocked in `waitpid` the rest of the time, always ready to react. *Is there such a call in linux? Of the alternatives, which one is best?* --- EDIT: Another method based on the replies would be to block `SIGCHLD` in all threads with `pthread` \ `_sigmask()`. Then in one thread, keep calling `sigtimedwait()` while looking for `SIGCHLD`. This means that I can time out on that call and check whether the thread should exit, and if not, remain blocked waiting for the signal. Once a `SIGCHLD` is delivered to this thread, we can react to it immediately, and in line of the wait thread, without using a signal handler.
The function can be interrupted with a signal, so you could set a timer before calling waitpid() and it will exit with an EINTR when the timer signal is raised. Edit: It should be as simple as calling alarm(5) before calling waitpid().
Don't mix `alarm()` with `wait()`. You can lose error information that way. Use the self-pipe trick. This turns any signal into a `select()`able event: ``` int selfpipe[2]; void selfpipe_sigh(int n) { int save_errno = errno; (void)write(selfpipe[1], "",1); errno = save_errno; } void selfpipe_setup(void) { static struct sigaction act; if (pipe(selfpipe) == -1) { abort(); } fcntl(selfpipe[0],F_SETFL,fcntl(selfpipe[0],F_GETFL)|O_NONBLOCK); fcntl(selfpipe[1],F_SETFL,fcntl(selfpipe[1],F_GETFL)|O_NONBLOCK); memset(&act, 0, sizeof(act)); act.sa_handler = selfpipe_sigh; sigaction(SIGCHLD, &act, NULL); } ``` Then, your waitpid-like function looks like this: ``` int selfpipe_waitpid(void) { static char dummy[4096]; fd_set rfds; struct timeval tv; int died = 0, st; tv.tv_sec = 5; tv.tv_usec = 0; FD_ZERO(&rfds); FD_SET(selfpipe[0], &rfds); if (select(selfpipe[0]+1, &rfds, NULL, NULL, &tv) > 0) { while (read(selfpipe[0],dummy,sizeof(dummy)) > 0); while (waitpid(-1, &st, WNOHANG) != -1) died++; } return died; } ``` You can see in `selfpipe_waitpid()` how you can control the timeout and even mix with other `select()`-based IO.
Waitpid equivalent with timeout?
[ "", "c++", "c", "linux", "" ]
I currently have 2 `BufferedReader`s initialized on the same text file. When I'm done reading the text file with the first `BufferedReader`, I use the second one to make another pass through the file from the top. Multiple passes through the same file are necessary. I know about `reset()`, but it needs to be preceded with calling `mark()` and `mark()` needs to know the size of the file, something I don't think I should have to bother with. Ideas? Packages? Libs? Code? Thanks TJ
What's the disadvantage of just creating a new `BufferedReader` to read from the top? I'd expect the operating system to cache the file if it's small enough. If you're concerned about performance, have you proved it to be a bottleneck? I'd just do the simplest thing and not worry about it until you have a specific reason to. I mean, you could just read the whole thing into memory and then do the two passes on the result, but again that's going to be more complicated than just reading from the start again with a new reader.
The Buffered readers are meant to read a file sequentially. What you are looking for is the [java.io.RandomAccessFile](http://docs.oracle.com/javase/8/docs/api/java/io/RandomAccessFile.html), and then you can use `seek()` to take you to where you want in the file. The random access reader is implemented like so: ``` try{ String fileName = "c:/myraffile.txt"; File file = new File(fileName); RandomAccessFile raf = new RandomAccessFile(file, "rw"); raf.readChar(); raf.seek(0); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } ``` The `"rw"` is a mode character which is [detailed here](http://docs.oracle.com/javase/8/docs/api/java/io/RandomAccessFile.html#RandomAccessFile-java.io.File-java.lang.String-). The reason the sequential access readers are setup like this is so that they can implement their buffers and that things can not be changed beneath their feet. For example the file reader that is given to the buffered reader should only be operated on by that buffered reader. If there was another location that could affect it you could have inconsistent operation as one reader advanced its position in the file reader while the other wanted it to remain the same now you use the other reader and it is in an undetermined location.
Java BufferedReader back to the top of a text file?
[ "", "java", "file", "file-io", "text-files", "bufferedinputstream", "" ]
I've got a bunch of properties which I am going to use read/write locks on. I can implement them either with a `try finally` or a `using` clause. In the `try finally` I would acquire the lock before the `try`, and release in the `finally`. In the `using` clause, I would create a class which acquires the lock in its constructor, and releases in its Dispose method. I'm using read/write locks in a lot of places, so I've been looking for ways that might be more concise than `try finally`. I'm interested in hearing some ideas on why one way may not be recommended, or why one might be better than another. Method 1 (`try finally`): ``` static ReaderWriterLock rwlMyLock_m = new ReaderWriterLock(); private DateTime dtMyDateTime_m public DateTime MyDateTime { get { rwlMyLock_m .AcquireReaderLock(0); try { return dtMyDateTime_m } finally { rwlMyLock_m .ReleaseReaderLock(); } } set { rwlMyLock_m .AcquireWriterLock(0); try { dtMyDateTime_m = value; } finally { rwlMyLock_m .ReleaseWriterLock(); } } } ``` Method 2: ``` static ReaderWriterLock rwlMyLock_m = new ReaderWriterLock(); private DateTime dtMyDateTime_m public DateTime MyDateTime { get { using (new ReadLock(rwlMyLock_m)) { return dtMyDateTime_m; } } set { using (new WriteLock(rwlMyLock_m)) { dtMyDateTime_m = value; } } } public class ReadLock : IDisposable { private ReaderWriterLock rwl; public ReadLock(ReaderWriterLock rwl) { this.rwl = rwl; rwl.AcquireReaderLock(0); } public void Dispose() { rwl.ReleaseReaderLock(); } } public class WriteLock : IDisposable { private ReaderWriterLock rwl; public WriteLock(ReaderWriterLock rwl) { this.rwl = rwl; rwl.AcquireWriterLock(0); } public void Dispose() { rwl.ReleaseWriterLock(); } } ```
From MSDN, [using Statement (C# Reference)](http://msdn.microsoft.com/en-us/library/yh598w02.aspx) > The using statement ensures that Dispose is called even if an exception occurs while you are calling methods on the object. You can achieve the same result by putting the object inside a try block and then calling Dispose in a finally block; in fact, this is how the using statement is translated by the compiler. The code example earlier expands to the following code at compile time (note the extra curly braces to create the limited scope for the object): ``` { Font font1 = new Font("Arial", 10.0f); try { byte charset = font1.GdiCharSet; } finally { if (font1 != null) ((IDisposable)font1).Dispose(); } } ``` So basically, **it is the same code but with a nice automatic null-checks and an extra scope for your variable**. The documentation also states that it "ensures the correct use of IDisposable object" so you might as well gets even better framework support for any obscure cases in the future. So go with option 2. Having the variable *inside a scope* that ends immediately after it's no longer needed is also a plus.
I definitely prefer the second method. It is more concise at the point of usage, and less error prone. In the first case someone editing the code has to be careful not to insert anything between the Acquire(Read|Write)Lock call and the try. (Using a read/write lock on individual properties like this is usually overkill though. They are best applied at a much higher level. A simple lock will often suffice here since the possibility of contention is presumably very small given the time the lock is held for, and acquiring a read/write lock is a more expensive operation than a simple lock).
'using' statement vs 'try finally'
[ "", "c#", ".net", "multithreading", "using-statement", "" ]
I seem to be losing a lot of precision with floats. For example I need to solve a matrix: ``` 4.0x -2.0y 1.0z =11.0 1.0x +5.0y -3.0z =-6.0 2.0x +2.0y +5.0z =7.0 ``` This is the code I use to import the matrix from a text file: ``` f = open('gauss.dat') lines = f.readlines() f.close() j=0 for line in lines: bits = string.split(line, ',') s=[] for i in range(len(bits)): if (i!= len(bits)-1): s.append(float(bits[i])) #print s[i] b.append(s) y.append(float(bits[len(bits)-1])) ``` I need to solve using gauss-seidel so I need to rearrange the equations for x, y, and z: ``` x=(11+2y-1z)/4 y=(-6-x+3z)/5 z=(7-2x-2y)/7 ``` Here is the code I use to rearrange the equations. `b` is a matrix of coefficients and `y` is the answer vector: ``` def equations(b,y): i=0 eqn=[] row=[] while(i<len(b)): j=0 row=[] while(j<len(b)): if(i==j): row.append(y[i]/b[i][i]) else: row.append(-b[i][j]/b[i][i]) j=j+1 eqn.append(row) i=i+1 return eqn ``` However the answers I get back aren't precise to the decimal place. For example, upon rearranging the second equation from above, I should get: ``` y=-1.2-.2x+.6z ``` What I get is: ``` y=-1.2-0.20000000000000001x+0.59999999999999998z ``` This might not seem like a big issue but when you raise the number to a very high power the error is quite large. Is there a way around this? I tried the `Decimal` class but it does not work well with powers (i.e, `Decimal(x)**2`). Any ideas?
I'm not familiar enough with the Decimal class to help you out, but your problem is due to the fact that decimal fractions can often not be accurate represented in binary, so what you're seeing is the closest possible approximation; there's no way to avoid this problem without using a special class (like Decimal, probably). `EDIT:` What about the decimal class isn't working properly for you? As long as I start with a string, rather than a float, powers seem to work fine. ``` >>> import decimal >>> print(decimal.Decimal("1.2") ** 2) 1.44 ``` The [module documentation](http://docs.python.org/library/decimal.html) explains the need for and usage of `decimal.Decimal` pretty clearly, you should check it out if you haven't yet.
IEEE floating point is binary, not decimal. There is no fixed length binary fraction that is exactly 0.1, or any multiple thereof. It is a repeating fraction, like 1/3 in decimal. Please read [What Every Computer Scientist Should Know About Floating-Point Arithmetic](http://docs.sun.com/source/806-3568/ncg_goldberg.html) Other options besides a Decimal class are * using Common Lisp or [Python 2.6](http://docs.python.org/whatsnew/2.6.html#the-fractions-module) or another language with exact rationals * converting the doubles to close rationals using, e.g., [frap](http://www.ics.uci.edu/~eppstein/numth/frap.c)
Decimal place issues with floats and decimal.Decimal
[ "", "python", "floating-point", "decimal", "floating-accuracy", "" ]
We have an application that installs SQL Server Express from the command line and specifies the service account as the LocalSystem account via the parameter SQLACCOUNT="NT AUTHORITY\SYSTEM". This doesn't work with different languages because the account name for LocalSystem is different. There's a table listing the differences here: <http://forums.microsoft.com/MSR/ShowPost.aspx?PostID=685354&SiteID=37> This doesn't seem to be complete (the Swedish version isn't listed). So I'd like to be able to determine the name programmatically, perhaps using the SID? I've found some VB Script to do this: ``` Set objWMI = GetObject("winmgmts:root\cimv2") Set objSid = objWMI.Get("Win32_SID.SID='S-1-5-18'") MsgBox objSid.ReferencedDomainName & "\" & objSid.AccountName ``` Does anyone know the equivalent code that can be used in C#?
You can use .NET's built-in [System.Security.Principal.SecurityIdentifier](http://msdn.microsoft.com/en-us/library/system.security.principal.securityidentifier.aspx) class for this purpose: by translating it into an instance of [NtAccount](http://msdn.microsoft.com/en-us/library/system.security.principal.ntaccount.aspx) you can obtain the account name: ``` using System.Security.Principal; SecurityIdentifier sid = new SecurityIdentifier("S-1-5-18"); NTAccount acct = (NTAccount)sid.Translate(typeof(NTAccount)); Console.WriteLine(acct.Value); ``` Later edit, in response to question in comments: you do not need any special privileges to do SID-to-name lookups on the local machine -- for example, even if the user account you're running under is only in the Guests group, this code should work. Things are a little bit different if the SID resolves to a domain account, but even that should work correctly in most cases, as long as you're logged on to the domain (and a domain controller is available at the time of the lookup).
Or you can use: ``` string localSystem = new SecurityIdentifier(WellKnownSidType.LocalSystemSid, null).Translate(typeof(NTAccount)).Value; ``` With `WellKnownSidType` you can look for other accounts, as `NetworkService` for example.
Determine the LocalSystem account name using C#
[ "", "c#", "sql-server", "localsystem", "" ]
In the .xsd file for a typed DataSet in .NET, there's a `<Connections>` section that contains a list of any data connections I've used to set up the DataTables and TableAdapters. There are times when I'd prefer not to have those there. For instance, sometimes I prefer to pass in a connection string to a custom constructor and use that rather than look for one in settings, .config, etc. But it seems like if I remove the connection strings from that section (leaving it empty), or remove the section entirely, the DataSet code-generation tool freaks out. Whereas if I *don't* remove them, the DataSet gripes when I put it in a different project because it can't find the settings for those connection strings. Is there any way I can tell a typed DataSet not to worry about any connections? (Obviously I'll have to give it a connection if I change any TableAdapter SQL or stored procs, but that should be *my* problem.)
This has bugged me for a long time as well and I did some testing recently. Here is what I came up with. For the record, I'm using VS 2008 SP1. * Datasets *will* store connection string information whether you want them to or not. * You *can* make sure datasets won't store passwords in their connection strings. * You can either have the connection string stored in the 'connections' section the .xsd file or you can have it stored in the app.config file and referenced from the 'connections' section of the .xsd file. Either way, the 'connections' section appears to be a requirement. If you find a way to make it work, please post here. Currently, I store the connection string in the xsd file and make sure I'm not storing the password. Then, when I use it it code, I always create my own connection and never use one stored in the dataset.
In a similar case I stored the connection string for the dataset in a settings file / app.config (default behaviour in Visual Studio when creating a dataset) with integrated security to a local development database. In order to be able to access this from external projects, I changed the settings file to be `public` instead of the default `internal` (in the visual designer). This resulted in code like (in Properties\Settings.Designer.cs): ``` public sealed partial class Settings { [...] [global::System.Configuration.DefaultSettingValueAttribute ("Data Source=.;Initial Catalog=MyDb;Integrated Security=True;")] public string MyConnectionString { get { return ((string)(this["MyConnectionString"])); } } } ``` Then I manually modified the property to include a public setter as well: ``` public string MyConnectionString { get { return ((string)(this["MyConnectionString"])); } set { this["MyConnectionString"] = value; } } ``` Finally I set the connection string from an external project like: ``` MyDataAccessLibrary.Properties.Settings.Default.MyConnectionString = ... ```
Typed DataSet connection - required to have one in the .xsd file?
[ "", "c#", ".net", "vb.net", "dataset", "" ]
I have a little pet web app project I'd like to show someone who doesn't have an application server themselves (and who has no clue about application servers). What is the easiest and quickest way for them to get my WAR file running with zero configuration, preferably something I could send along with or bundle with the WAR file? Is there a slimmed down version of Jetty, for example? Something else?
You can create the slimmed down version yourself easily. <http://docs.codehaus.org/display/JETTY/Embedding+Jetty> <http://jetty.mortbay.org/xref/org/mortbay/jetty/example/LikeJettyXml.html> To run embedded Jetty you need only the following jars on the classpath: ``` * servlet-api-2.5-6.x.jar * jetty-util-6.x.jar * jetty-6.x.jar /usr/local/jetty-6.1.4/lib> ls -la servlet-api-2.5-6.1.4.jar jetty-* -rw-rw-r-- 1 wwwrun admin 476213 2007-06-15 08:42 jetty-6.1.4.jar -rw-rw-r-- 1 wwwrun admin 128026 2007-06-15 08:40 jetty-util-6.1.4.jar -rw-rw-r-- 1 wwwrun admin 131977 2007-06-15 08:40 servlet-api-2.5-6.1.4.jar ``` Very light... Alternatively, the Maven [plugin](http://docs.codehaus.org/display/JETTY/Maven+Jetty+Plugin) can work as well.
If you don't know or do not want to mess with maven you could try Jetty-runner <https://svn.codehaus.org/jetty-contrib/trunk/jetty-runner> jetty-runner.jar is one jar file that you can run from command line like so: java -jar jetty-runner.jar my.war
Slim application server for demonstrating a web app?
[ "", "java", "application-server", "" ]
I am trying to compare two decimal values in Java script. I have two objects as one assogned value "3" and the other as "3.00". When i say if (obj1 == obj2) it does not pass the condition as it is does the string comparision. I would instead want it to do a decimal comparision where 3 = 3.00. Please let me know how to do this.
[This page](http://www.javascripter.net/faq/convert2.htm) describes how to convert a string to a floating-point number; I believe that is what you want. This would let you compare the numbers as numbers, which I think is what you mean by "decimally". Beware that doing an exact comparison between two floating-point numbers is often considered a bit "hazardous", since there are precision issues that might cause two numbers that you would consider "equal" to not compare as such. See, for instance, [What Every Computer Scientist Should Know About Floating-Point Arithmetic](http://docs.sun.com/source/806-3568/ncg_goldberg.html), which is a classic text on the topic. Perhaps a bit on the advanced side, but try searching for something more basic in that case.
You can also do type casting: ``` var a = "3.00"; var b = "3"; Number(a) == Number(b) // This will be true ```
Decimal comaprison in Java script
[ "", "asp.net", "javascript", "scripting", "" ]
I am working with a huge list of URL's. Just a quick question I have trying to slice a part of the URL out, see below: ``` http://www.domainname.com/page?CONTENT_ITEM_ID=1234&param2&param3 ``` How could I slice out: ``` http://www.domainname.com/page?CONTENT_ITEM_ID=1234 ``` Sometimes there is more than two parameters after the CONTENT\_ITEM\_ID and the ID is different each time, I am thinking it can be done by finding the first & and then slicing off the chars before that &, not quite sure how to do this tho. Cheers
Use the [urlparse](http://docs.python.org/2/library/urlparse.html#urlparse.urlsplit) module. Check this function: ``` import urlparse def process_url(url, keep_params=('CONTENT_ITEM_ID=',)): parsed= urlparse.urlsplit(url) filtered_query= '&'.join( qry_item for qry_item in parsed.query.split('&') if qry_item.startswith(keep_params)) return urlparse.urlunsplit(parsed[:3] + (filtered_query,) + parsed[4:]) ``` In your example: ``` >>> process_url(a) 'http://www.domainname.com/page?CONTENT_ITEM_ID=1234' ``` This function has the added bonus that it's easier to use if you decide that you also want some more query parameters, or if the order of the parameters is not fixed, as in: ``` >>> url='http://www.domainname.com/page?other_value=xx&param3&CONTENT_ITEM_ID=1234&param1' >>> process_url(url, ('CONTENT_ITEM_ID', 'other_value')) 'http://www.domainname.com/page?other_value=xx&CONTENT_ITEM_ID=1234' ```
The quick and dirty solution is this: ``` >>> "http://something.com/page?CONTENT_ITEM_ID=1234&param3".split("&")[0] 'http://something.com/page?CONTENT_ITEM_ID=1234' ```
Slicing URL with Python
[ "", "python", "url", "string", "" ]
I want to allow users to paste `<embed>` and `<object>` HTML fragments (video players) via an HTML form. The server-side code is PHP. How can I protect against malicious pasted code, JavaScript, etc? I could parse the pasted code, but I'm not sure I could account for all variations. Is there a better way?
I'm not really sure what parameters `EMBED` and `OBJECT` take as I've never really dealt with putting media on a page (which is actually kind of shocking to think about) but I would take a BB Code approach to it and do something like `[embed url="http://www.whatever.com/myvideo.whatever" ...]` and then you can parse out the URL and anything else, make sure they are legit and make your own `<EMBED>` tag. **edit:** Alright, something like this should be fine: ``` $youtube = '<object width="425" height="344"><param name="movie" value="http://www.youtube.com/v/Z75QSExE0jU&hl=en&fs=1"></param> </param><embed src="http://www.youtube.com/v/Z75QSExE0jU&hl=en&fs=1" type="application/x-shockwave-flash" allowfullscreen="true" width="425" height="344"></embed></object>'; $blip = '<embed src="http://blip.tv/play/AZ_iEoaIfA" type="application/x-shockwave-flash" width="640" height="510" allowscriptaccess="always" allowfullscreen="true"></embed>'; preg_match_all("/([A-Za-z]*)\=\"(.+?)\"/", $youtube, $matches1); preg_match_all("/([A-Za-z]*)\=\"(.+?)\"/", $blip, $matches2); print '<pre>' . print_r($matches1, true). '</pre>'; print '<pre>' . print_r($matches2, true). '</pre>'; ``` This will output: ``` Array ( [0] => Array ( [0] => width="425" [1] => height="344" [2] => name="movie" [3] => value="http://www.youtube.com/v/Z75QSExE0jU&hl=en&fs=1" [4] => src="http://www.youtube.com/v/Z75QSExE0jU&hl=en&fs=1" [5] => type="application/x-shockwave-flash" [6] => allowfullscreen="true" [7] => width="425" [8] => height="344" ) [1] => Array ( [0] => width [1] => height [2] => name [3] => value [4] => src [5] => type [6] => allowfullscreen [7] => width [8] => height ) [2] => Array ( [0] => 425 [1] => 344 [2] => movie [3] => http://www.youtube.com/v/Z75QSExE0jU&hl=en&fs=1 [4] => http://www.youtube.com/v/Z75QSExE0jU&hl=en&fs=1 [5] => application/x-shockwave-flash [6] => true [7] => 425 [8] => 344 ) ) Array ( [0] => Array ( [0] => src="http://blip.tv/play/AZ_iEoaIfA" [1] => type="application/x-shockwave-flash" [2] => width="640" [3] => height="510" [4] => allowscriptaccess="always" [5] => allowfullscreen="true" ) [1] => Array ( [0] => src [1] => type [2] => width [3] => height [4] => allowscriptaccess [5] => allowfullscreen ) [2] => Array ( [0] => http://blip.tv/play/AZ_iEoaIfA [1] => application/x-shockwave-flash [2] => 640 [3] => 510 [4] => always [5] => true ) ) ``` From then on it's pretty straight forward. For things like width/height you can verify them with [`is_numeric`](http://www.php.net/is_numeric) and with the rest you can run the values through [`htmlentities`](http://www.php.net/htmlentities) and construct your own `<embed>` tag from the information. I am pretty certain this would be safe. You can even make the full-fledged `<object>` one like YouTube (which I assume works in more places) with links from blip.tv, since you would have all the required data. I am sure you may see some quirks with links from other video-sharing websites but this will hopefully get you started. Good luck.
Your chances of detecting malicious code reliably by scanning inputted HTML are about nil. There are so many possible ways to inject script (including browser-specific malformed HTML), you won't be able to pick them all out. If big webmail providers are still after years finding new exploits there is no chance you'll be able to do it. Whitelisting is better than blacklisting. So you could instead require the input to be XHTML, and parse it using a standard XML parser. Then walk through the DOM and check that each of the elements and attributes is known-good, and if everything's OK, serialise back to XHTML, which, coming from a known-good DOM, should not be malformed. A proper XML parser with Unicode support should also filter out nasty 'overlong UTF-8 sequences' (a security hole affecting IE6 and older Operas) for free. However... if you allow embed/objects from any domain, you are already allowing full script access to your page from an external domains, so HTML injection is the least of your worries. Plug-ins such as Flash are likely to be able to execute JavaScript without any kind of trickery being necessary. So you should be limiting the source of objects to predetermined known-good domains. And if you're already doing that, it's probably easier to just allow the user to choose a video provider and clip ID, and then convert that into the proper, known-good embedding code for that provider. For example if you are using a bbcode-like markup, the traditional way to let users include a YouTube clip would be something [youtube]Dtzs7DSh[/youtube].
How to Safely Accept Pasted <embed> Code in PHP
[ "", "php", "validation", "embed", "" ]
What is the difference between `private` and `protected` members in C++ classes? I understand from best practice conventions that variables and functions which are not called outside the class should be made `private`—but looking at my MFC project, MFC seems to favor `protected`. What's the difference and which should I use?
Private members are only accessible within the class defining them. Protected members are accessible in the class that defines them and in classes that inherit from that class. Both are also accessible by friends of their class, and in the case of protected members, by friends of their derived classes. Use whatever makes sense in the context of your problem. You should try to make members private whenever you can to reduce coupling and protect the implementation of the base class, but if that's not possible, then use protected members. Check [C++ FAQ](https://isocpp.org/wiki/faq/basics-of-inheritance) for a better understanding of the issue. [This question about protected variables](https://stackoverflow.com/questions/37011/protected-member-variables) might also help.
**Public** members of a class A are accessible for all and everyone. **Protected** members of a class A are not accessible outside of A's code, but is accessible from the code of any class derived from A. **Private** members of a class A are not accessible outside of A's code, or from the code of any class derived from A. So, in the end, choosing between protected or private is answering the following questions: **How much trust are you willing to put into the programmer of the derived class?** **By default**, assume the derived class is not to be trusted, and **make your members private**. If you have a very good reason to give free access of the mother class' internals to its derived classes, then you can make them protected.
What is the difference between private and protected members of C++ classes?
[ "", "c++", "class", "oop", "private", "protected", "" ]
This is a question I have wondered about for quite some time, yet I have never found a suitable solution. If I run a script and I come across, let's say an IndexError, python prints the line, location and quick description of the error and exits. Is it possible to automatically start pdb when an error is encountered? I am not against having an extra import statement at the top of the file, nor a few extra lines of code.
You can use [traceback.print\_exc](http://docs.python.org/library/traceback.html#traceback.print_exc) to print the exceptions traceback. Then use [sys.exc\_info](http://docs.python.org/library/sys#sys.exc_info) to extract the traceback and finally call [pdb.post\_mortem](http://docs.python.org/library/pdb#pdb.post_mortem) with that traceback ``` import pdb, traceback, sys def bombs(): a = [] print a[0] if __name__ == '__main__': try: bombs() except: extype, value, tb = sys.exc_info() traceback.print_exc() pdb.post_mortem(tb) ``` If you want to start an interactive command line with [code.interact](http://docs.python.org/library/code#code.interact) using the locals of the frame where the exception originated you can do ``` import traceback, sys, code def bombs(): a = [] print a[0] if __name__ == '__main__': try: bombs() except: type, value, tb = sys.exc_info() traceback.print_exc() last_frame = lambda tb=tb: last_frame(tb.tb_next) if tb.tb_next else tb frame = last_frame().tb_frame ns = dict(frame.f_globals) ns.update(frame.f_locals) code.interact(local=ns) ```
``` python -m pdb -c continue myscript.py # or python -m pdb -c continue -m myscript ``` If you don't provide the `-c continue` flag then you'll need to enter 'c' (for Continue) when execution begins. Then it will run to the error point and give you control there. As [mentioned by eqzx](https://stackoverflow.com/questions/242485/starting-python-debugger-automatically-on-error#comment73725114_2438834), this flag is a new addition in python 3.2 so entering 'c' is required for earlier Python versions (see <https://docs.python.org/3/library/pdb.html>).
Starting python debugger automatically on error
[ "", "python", "debugging", "" ]
I'm currently running into some issues resizing images using GD. Everything works fine until i want to resize an animated gif, which delivers the first frame on a black background. I've tried using `getimagesize` but that only gives me dimensions and nothing to distinguish between just any gif and an animated one. Actual resizing is not required for animated gifs, just being able to skip them would be enough for our purposes. Any clues? PS. I don't have access to imagemagick. Kind regards, Kris
There is a brief snippet of code in the PHP manual page of the `imagecreatefromgif()` function that should be what you need: [`imagecreatefromgif` comment #59787 by ZeBadger](https://php.net/manual/en/function.imagecreatefromgif.php#59787)
While searching for a solution to the same problem I noticed that the php.net site has a follow-up to the code Davide and Kris are referring to, but, according to the author, less memory-intensive, and possibly less disk-intensive. I'll replicate it here, because it may be of interest. source: <http://www.php.net/manual/en/function.imagecreatefromgif.php#88005> ``` function is_ani($filename) { if(!($fh = @fopen($filename, 'rb'))) return false; $count = 0; //an animated gif contains multiple "frames", with each frame having a //header made up of: // * a static 4-byte sequence (\x00\x21\xF9\x04) // * 4 variable bytes // * a static 2-byte sequence (\x00\x2C) // We read through the file til we reach the end of the file, or we've found // at least 2 frame headers while(!feof($fh) && $count < 2) { $chunk = fread($fh, 1024 * 100); //read 100kb at a time $count += preg_match_all('#\x00\x21\xF9\x04.{4}\x00[\x2C\x21]#s', $chunk, $matches); } fclose($fh); return $count > 1; } ```
Can I detect animated gifs using php and gd?
[ "", "php", "gd", "" ]
I have several static factory patterns in my PHP library. However, memory footprint is getting out of hand and we want to reduce the number of files required during execution time. Here is an example of where we are today: ``` require_once('Car.php'); require_once('Truck.php'); abstract class Auto { // ... some stuff ... public static function Create($type) { switch ($type) { case 'Truck': return new Truck(); break; case 'Car': default: return new Car(); break; } } } ``` This is undesirable because Car.php AND Truck.php will need to be included even though only one or the other may be needed. As far as I know, require/include and their ...\_once variation include libraries at the same scope as it's call. Is this true? If so, I believe this would lead to a memory leak: ``` abstract class Auto { // ... some stuff ... public static function Create($type) { switch ($type) { case 'Truck': require_once('Truck.php'); return new Truck(); break; case 'Car': default: require_once('Car.php'); return new Car(); break; } } } ``` It looks to me that in the 2nd example, multiple calls to Create() would lead to multiple requires because of the scope of the call even though the require\_once flavor is used. Is this true? What is the best way to include libraries dynamically in php in an example such as these? Thanks!
The Autoload facility is often seen as Evil, but it works at these task quite nicely. If you can get a good filesystem <-> classname mapping so you can, when given a class to provide, find it, then it will save you overhead and only load classes when needed. It works for static classes too, so once the static class is in scope, it doesn't need to even call the "is file included yet" test of require once, because the Class is already in the symbol table. Then you can just create ``` require("autoloader.php"); $x = new Car(); $x = new Bike(); ``` and it will just bring them in when needed. See [Php.net/\_\_autoload](https://www.php.net/__autoload) for more details.
I would recommend using the [autoloader](http://php.net/autoload). That is, don't use `require_once()` to require either subclass, but allows the autoloader to call a function which can load the referenced class when you call `new Truck()` or `new Car()`. As for the memory leak question, no, `require_once` is not scoped by the code block.
What is the best way to include PHP libraries when using static factory pattern?
[ "", "php", "include", "polymorphism", "require", "require-once", "" ]
Given a class, [org.eclipse.ui.views.navigator.ResourceNavigator](http://help.eclipse.org/stable/index.jsp?topic=/org.eclipse.platform.doc.isv/reference/api/org/eclipse/ui/views/navigator/ResourceNavigator.html) for example, how do I find out which jar file to use? I know it's in org.eclipse.ui.ide, but how would I find that out? **Edit**: Thank you to all of you who answered. Like many things, there seems to be several ways to skin this cat. I wish javadoc contained this info. So far here are the different methods: 1. Without Internet, Eclipse or NetBeans: ``` for f in `find . -name '*.jar'`; do echo $f && jar tvf $f | grep -i $1; done ``` 2. If you want to find out locally using Eclipse: * [JAR Class Finder Plug-in](http://www.alphaworks.ibm.com/tech/jarclassfinder) * [Class Locator Plug-in](http://classlocator.sourceforge.net/) 3. If you want to find out from Internet or you do not have the jar yet: * [jarFinder](http://www.jarfinder.com/) * [findjar.com](http://findjar.com/)
You also have this eclipse plugin: [jarclassfinder](http://www.alphaworks.ibm.com/tech/jarclassfinder) The user enters the name of the class not found (or the name of the class that the Java project needs to access). The plug-in will search the selected directory (and subdirectories) for JAR files containing that class. All results are displayed in a table in a custom view. The user can then browse this table and select the JAR file to add to his Java project's build path. The user then right-clicks on the entry in the table and, from the context menu, selects the build path to which to add it. --- Update 2013, as I mention in "[searching through .jar files eclipse](https://stackoverflow.com/a/1086435/6309)", it is no longer maintained, and the alternatives are sparse. As [sunleo](https://stackoverflow.com/users/1755242/sunleo) comments [below](https://stackoverflow.com/questions/275120/java-how-do-i-know-which-jar-file-to-use-given-a-class-name/275141#comment36479092_275141): **with Eclipse, `Ctfl`+`Shift`+`T` remains the easiest alternative** to look for a type (with the jar name displayed in the status bar). --- [user862268](https://stackoverflow.com/users/862268/user862268) comments [below](https://stackoverflow.com/questions/275120/java-how-do-i-know-which-jar-file-to-use-given-a-class-name/275141#comment60625860_275141): > For mac, it is `cmd`+`shift`+`T` in Eclipse to find the class and associated jar.
If you have the jar in your class path / project path hit CTRL-SHIFT-T and type the name ... the jar will be displayed at the bottom. If you haven't the class in your build path a) put together a dummy project containing all the jars b) I think there is a plugin to find jars from IBM Alphaworks (but that might be kind of outdated)
Java: How do I know which jar file to use given a class name?
[ "", "java", "eclipse", "jar", "" ]
I'm inserting an img tag into my document with the new Element constructor like this (this works just fine): ``` $('placeholder').insert(new Element("img", {id:'something', src:myImage})) ``` I would like to trigger a function when this image loads, but I can't figure out the correct syntax. I'm guess it's something like this (which doesn't work). ``` $('placeholder').insert(new Element("img", {id:'something', src:myImage, onload:function(){alert("MOO")}})) ``` I'm hoping to do this in the same line of code and not to have to attach an event observer separately. **EDIT:** The event needs to be registered when the element is **created**, not after. If the image loads before the event is attached, the event will never fire.
In this case, the best solution is to not use Prototype or at least not exclusively. This works: ``` var img = new Element('img',{id:'logo',alt:'Hooray!'}); img.onload = function(){ alert(this.alt); }; img.src = 'logo.jpg'; ``` The key is setting the onload directly instead of letting Prototype's wrapper do it for you, and set the src last (actually not sure about that, but I do it last to be safe). One-liners are overrated. With proper use of local variables the above is just as good. If you must have a one-liner, create a wrapper function or hack the Prototype core to ensure proper assignment (submit a patch!).
Try ``` $('placeholder').insert(new Element("img", { id: 'something', src:myImage }).observe('load', function() { // onload code here })); ```
How to add event handler with Prototype new Element() constructor?
[ "", "javascript", "html", "prototypejs", "" ]
How do I set the date/time of the computer in C#?
You can set the date using [Microsoft.VisualBasic.Today](http://msdn.microsoft.com/en-us/library/9z20y6ha(VS.80).aspx) and [Microsoft.VisualBasic.TimeOfDay](http://msdn.microsoft.com/en-us/library/8hhbhw4c(VS.80).aspx), although they're subject to security restrictions. Yes, it's strange accessing the Microsoft,VisualBasic namespace, but there doesn't appear to be a C# equivalent.
You'll have to use a P/Invoke to the Windows API. Here's some [example code](http://pinvoke.net/default.aspx/kernel32.SetLocalTime) in C#
How to set the date/time in C#
[ "", "c#", "datetime", "" ]
Wanted to generate a UI diagram (with nice layout) depicting relationships amongst network components. Which is the best Java based API to do such layouts with minimum fuss and light codebase.
If you're logging for a Java API that can do layouts (e.g. arrange boxes in a hierarchical fashion without overlap), check out [JGraph](http://www.jgraph.com/).
yWorks. <http://www.yworks.com/en/index.html>
UI diagram layout
[ "", "java", "diagramming", "" ]
I'd like to warn users when they **try to close a browser window** if they **didn't save** the changes they made in the web form. I'm using ASP.NET 3.5 (with ASP.NET Ajax). Is there a common solution which I could easily implement? *EDIT: maybe my question wasn't clear:* I am specifically looking for a way which integrates gracefully in the **ASP.NET** Server Controls methodology.
Here is an ASP.NET extender control that will help you with this: <http://www.codeproject.com/KB/ajax/ajaxdirtypanelextender.aspx> Hope this helps. It may not perfectly fit your needs but it at least shows you how.
you'll want to leverage off the ``` window.onbeforeunload ``` event. Similar to Gmail if you attempt to close the window when you haven't saved a composed email. Theres some sample JS here. <http://forums.devarticles.com/javascript-development-22/how-to-stop-browser-from-closing-using-javascript-8458.html>
ASP.NET: Warning on changed data closing windows
[ "", "asp.net", "javascript", "asp.net-ajax", "" ]
I have been hearing a lot about Ruby and possibly even Javascript being "true" object oriented languages as opposed to C++ and C# which are class oriented (or template based) languages. What is meant by true OO and what are the advantages of this over the class/template approach?
It's a subjective term used to promote languages. I've seen it used to say C# and Java are true object oriented languages in comparison to C++ because everything must be in a class (no global functions or variables) and all objects inherit from one Object class. For Ruby, it may refers to how Ruby treats everything as an object, so you could write `1.to_s`, instead of something like `str(1)` or `String.valueOf(1)`. This is because Ruby makes no distinction between value and reference variables. In Javascript there are no classes and you just create extensible objects that could be cloned for reuse, this style of programming is known as [Prototype-based programming](http://en.wikipedia.org/wiki/Prototype-based_programming). C++ on the other hand is advertised as a multi-paradigm language that allows you to use several approaches such as object-oriented, generic and procedural programming. It doesn't stick to one paradigm. But yeah, it's just a subjective term that could mean anything. Generally it refers to whether the language puts more emphasis on objects as opposed to other language elements like functions, templates, etc. [Wikipedia's article on SmallTalk](http://en.wikipedia.org/wiki/Smalltalk) calls it a 'pure' object oriented language, and the description applies to Ruby as well: > Smalltalk is a 'pure' OO language, > meaning that, unlike Java and C++, > there is no difference between values > which are objects and values which are > primitive types. In Smalltalk, > primitive values such as integers, > booleans and characters are also > objects, in the sense that they are > instances of corresponding classes, > and operations on them are invoked by > sending messages. A programmer can > change the classes that implement > primitive values, so that new behavior > can be defined for their > instances--for example, to implement > new control structures--or even so > that their existing behavior will be > changed. This fact is summarised in > the commonly heard phrase "In > Smalltalk everything is an object" > (which would more accurately be > expressed as "all values are objects", > as variables aren't).
The C++ issue is the following. C++ classes exist only in the source syntax. There's no run-time class object with attributes and methods. In Python, everything's an object. An object's class is another object, with it's own methods and attributes. This is true of the smalltalk environment, also, which is a kind of benchmark of object-orientation. I think the "true" object-orientation refers to those environments where everything's an object. [Java falls short of this because it has primitive types.]
What is meant by the term "true" object orientation
[ "", "c#", "ruby", "oop", "" ]
When developing JavaScript, I tend to separate JavaScript code out into different files and then run a script to concatenate the files and compress or pack the resulting file. In the end, I have one file that I need to include on my production site. This approach has usually worked, but I've started to run into a problems with prototypal inheritance. Specifically, if one class inherits from another class, the file for the parent class needs to be included already for the inheritance to work. If the concatenation script I'm using is simply concatenating a directory full of files, the child class might occur in the code before the parent class. Like this: *parent\_class.js* ``` var Namespace = Namespace || {}; Namespace.Parent = function () { }; Namespace.Parent.prototype.doStuff = function () { ... }; ``` *child\_class.js* ``` var NameSpace = Namespace || {}; Namespace.Child = function () { ... }; Namespace.Child.prototype = new Namespace.Parent(); ``` The only way this works is if parent\_class.js is included before child\_class.js, which might not happen if the concatenation script places the child code before the parent code. Is there a way to write this code so that the functionality is the same, but the order in which the code is written no longer matters? Edit: I forgot that I'm using namespaces as well, so I added that to the code as well, which might change things a little bit.
> If the concatenation script I'm using is simply concatenating a directory full of files, the child class might occur in the code before the parent class. Is it too simple a solution to prepend a sort order value to each filename, and sort by name before performing the operation? eg: ``` 01_parent.js 02_child.js ``` Otherwise, perhaps maintaining a preordered list of files in a separate file. Maybe even go one step further and provide a hierarchical dependancy structure in xml to parse? This might be over-engineering the solution a bit :-D Some options for ways to deal with the problem if you had no way of determining how the javascript files are written.
When I've worked on large apps, I've use [requireJS](http://requirejs.org) to divide my code into modules, and make sure those modules are loaded in the correct order. Then I just mark my derived class as depending on the parent class. RequireJS comes with a tool that will combine and minify all your modules for production deployment as well.
How do you take advantage of prototypal inheritance without needing to include files in a specific order?
[ "", "javascript", "prototypal-inheritance", "" ]
Is there any way of doing parallel assignment in C++? Currently, the below compiles (with warnings) ``` #include <iostream> int main() { int a = 4; int b = 5; a, b = b, a; std::cout << "a: " << a << endl << "b: " << b << endl; return 0; } ``` and prints: ``` a: 4 b: 5 ``` What I'd like it to print ... if it weren't obvious, is: ``` a: 5 b: 4 ``` As in, say, ruby, or python.
That's not possible. Your code example ``` a, b = b, a; ``` is interpreted in the following way: ``` a, (b = b), a ``` It does nothing. The comma operator makes it return the value of a (the right most operand). Because assignment binds tighter, b = b is in parens. The proper way doing this is just ``` std::swap(a, b); ``` Boost includes a tuple class with which you can do ``` tie(a, b) = make_tuple(b, a); ``` It internally creates a tuple of references to a and b, and then assigned to them a tuple of b and a.
Parallel assignment is not supported in C++. Languages that support this usually treat `a,b,c` as a list on either side of the assignment operator, this isn't the way the comma operator works in C++. In C++, `a, b` evaluates a and then b, so `a, b = b, a` is the same as `a; b = b; a;`.
Parallel assignment in C++
[ "", "c++", "" ]
What's the best cross-platform way to get file creation and modification dates/times, that works on both Linux and Windows?
In Python 3.4 and above, you can use the object oriented [pathlib module](https://docs.python.org/3/library/pathlib.html) interface which includes wrappers for much of the os module. Here is an example of getting the file stats. ``` >>> import pathlib >>> fname = pathlib.Path('test.py') >>> assert fname.exists(), f'No such file: {fname}' # check that the file exists >>> print(fname.stat()) os.stat_result(st_mode=33206, st_ino=5066549581564298, st_dev=573948050, st_nlink=1, st_uid=0, st_gid=0, st_size=413, st_atime=1523480272, st_mtime=1539787740, st_ctime=1523480272) ``` For more information about what `os.stat_result` contains, refer to [the documentation](https://docs.python.org/3/library/os.html#os.stat_result). For the modification time you want `fname.stat().st_mtime`: ``` >>> import datetime >>> mtime = datetime.datetime.fromtimestamp(fname.stat().st_mtime, tz=datetime.timezone.utc) >>> print(mtime) datetime.datetime(2018, 10, 17, 10, 49, 0, 249980) ``` If you want the creation time on Windows, or the most recent metadata change on Unix, you would use `fname.stat().st_ctime`: ``` >>> ctime = datetime.datetime.fromtimestamp(fname.stat().st_ctime, tz=datetime.timezone.utc) >>> print(ctime) datetime.datetime(2018, 4, 11, 16, 57, 52, 151953) ``` [This article](https://realpython.com/python-pathlib/) has more helpful info and examples for the pathlib module.
Getting some sort of modification date in a cross-platform way is easy - just call [`os.path.getmtime(path)`](https://docs.python.org/library/os.path.html#os.path.getmtime) and you'll get the Unix timestamp of when the file at `path` was last modified. Getting file *creation* dates, on the other hand, is fiddly and platform-dependent, differing even between the three big OSes: * On **Windows**, a file's `ctime` (documented at <https://msdn.microsoft.com/en-us/library/14h5k7ff.aspx>) stores its creation date. You can access this in Python through [`os.path.getctime()`](https://docs.python.org/library/os.path.html#os.path.getctime) or the [`.st_ctime`](https://docs.python.org/3/library/os.html#os.stat_result.st_ctime) attribute of the result of a call to [`os.stat()`](https://docs.python.org/3/library/os.html#os.stat). This *won't* work on Unix, where the `ctime` [is the last time that the file's attributes *or* content were changed](http://www.linux-faqs.info/general/difference-between-mtime-ctime-and-atime). * On **Mac**, as well as some other Unix-based OSes, you can use the [`.st_birthtime`](https://docs.python.org/3/library/os.html#os.stat_result.st_birthtime) attribute of the result of a call to `os.stat()`. * On **Linux**, this is currently impossible, at least without writing a C extension for Python. Although some file systems commonly used with Linux [do store creation dates](https://unix.stackexchange.com/questions/7562/what-file-systems-on-linux-store-the-creation-time) (for example, `ext4` stores them in `st_crtime`) , the Linux kernel [offers no way of accessing them](https://unix.stackexchange.com/questions/91197/how-to-find-creation-date-of-file); in particular, the structs it returns from `stat()` calls in C, as of the latest kernel version, [don't contain any creation date fields](https://github.com/torvalds/linux/blob/v4.8-rc6/include/linux/stat.h). You can also see that the identifier `st_crtime` doesn't currently feature anywhere in the [Python source](https://github.com/python/cpython/search?utf8=%E2%9C%93&q=st_crtime). At least if you're on `ext4`, the data *is* attached to the inodes in the file system, but there's no convenient way of accessing it. The next-best thing on Linux is to access the file's `mtime`, through either [`os.path.getmtime()`](https://docs.python.org/library/os.path.html#os.path.getmtime) or the [`.st_mtime`](https://docs.python.org/3/library/os.html#os.stat_result.st_mtime) attribute of an `os.stat()` result. This will give you the last time the file's content was modified, which may be adequate for some use cases. Putting this all together, cross-platform code should look something like this... ``` import os import platform def creation_date(path_to_file): """ Try to get the date that a file was created, falling back to when it was last modified if that isn't possible. See http://stackoverflow.com/a/39501288/1709587 for explanation. """ if platform.system() == 'Windows': return os.path.getctime(path_to_file) else: stat = os.stat(path_to_file) try: return stat.st_birthtime except AttributeError: # We're probably on Linux. No easy way to get creation dates here, # so we'll settle for when its content was last modified. return stat.st_mtime ```
How do I get file creation and modification date/times?
[ "", "python", "file", "" ]
How do I search the whole classpath for an annotated class? I'm doing a library and I want to allow the users to annotate their classes, so when the Web application starts I need to scan the whole classpath for certain annotation. I'm thinking about something like the new functionality for Java EE 5 Web Services or EJB's. You annotate your class with `@WebService` or `@EJB` and the system finds these classes while loading so they are accessible remotely.
Use [org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider](http://static.springsource.org/spring/docs/2.5.x/api/org/springframework/context/annotation/ClassPathScanningCandidateComponentProvider.html) API > A component provider that scans the classpath from a base package. It then applies exclude and include filters to the resulting classes to find candidates. ``` ClassPathScanningCandidateComponentProvider scanner = new ClassPathScanningCandidateComponentProvider(<DO_YOU_WANT_TO_USE_DEFALT_FILTER>); scanner.addIncludeFilter(new AnnotationTypeFilter(<TYPE_YOUR_ANNOTATION_HERE>.class)); for (BeanDefinition bd : scanner.findCandidateComponents(<TYPE_YOUR_BASE_PACKAGE_HERE>)) System.out.println(bd.getBeanClassName()); ```
And another solution is [ronmamo's](https://github.com/ronmamo) [Reflections](https://github.com/ronmamo/reflections). Quick review: * Spring solution is the way to go if you're using Spring. Otherwise it's a big dependency. * Using ASM directly is a bit cumbersome. * Using Java Assist directly is clunky too. * Annovention is super lightweight and convenient. No maven integration yet. * Reflections indexes everything and then is super fast.
Scanning Java annotations at runtime
[ "", "java", "annotations", "classloader", "" ]
I'm trying to code opposite action to this: ``` std::ostream outs; // properly initialized of course std::set<int> my_set; // ditto outs << my_set.size(); std::copy( my_set.begin(), my_set.end(), std::ostream_iterator<int>( outs ) ); ``` it should be something like this: ``` std::istream ins; std::set<int>::size_type size; ins >> size; std::copy( std::istream_iterator<int>( ins ), std::istream_iterator<int>( ins ) ???, std::inserter( my_set, my_set.end() ) ); ``` But I'm stuck with the 'end' iterator -- input interators can't use std::advance and neither I can use two streams with the same source... Is there any elegant way how to solve this? Of course I can use for loop, but maybe there's something nicer :)
You could derive from the istream\_iterator<T>. Though using [Daemin generator method](https://stackoverflow.com/questions/250096/how-to-read-arbitrary-number-of-bytes-using-stdcopy#250380) is another option, though I would generate directly into the set rather than use an intermediate vector. ``` #include <set> #include <iterator> #include <algorithm> #include <iostream> template<typename T> struct CountIter: public std::istream_iterator<T> { CountIter(size_t c) :std::istream_iterator<T>() ,count(c) {} CountIter(std::istream& str) :std::istream_iterator<T>(str) ,count(0) {} bool operator!=(CountIter const& rhs) const { return (count != rhs.count) && (dynamic_cast<std::istream_iterator<T> const&>(*this) != rhs); } T operator*() { ++count; return std::istream_iterator<T>::operator*(); } private: size_t count; }; int main() { std::set<int> x; //std::copy(std::istream_iterator<int>(std::cin),std::istream_iterator<int>(),std::inserter(x,x.end())); std::copy( CountIter<int>(std::cin), CountIter<int>(5), std::inserter(x,x.end()) ); } ```
Use: ``` std::copy( std::istream_iterator<int>(ins), std::istream_iterator<int>(), std::inserter(my_set, my_set.end()) ); ``` Note the empty parameter: ``` std::istream_iterator<int>(); ```
How to read arbitrary number of values using std::copy?
[ "", "c++", "iterator", "stl-algorithm", "istream-iterator", "" ]
Is there any performance reason to declare method parameters final in Java? As in: ``` public void foo(int bar) { ... } ``` Versus: ``` public void foo(final int bar) { ... } ``` Assuming that `bar` is only read and never modified in `foo()`.
The final keyword does not appear in the class file for local variables and parameters, thus it cannot impact the runtime performance. It's only use is to clarify the coders intent that the variable not be changed (which many consider dubious reason for its usage), and dealing with anonymous inner classes. There is a lot of argument over whether the final modifier on the method itself has any performance gain since the methods will be inlined by the optimizing compiler at runtime anyway, regardless of the modifier. In this case it should also only be used to restrict the overriding of the method.
The only benefit to a final parameter is that it can be used in anonymous nested classes. If a parameter is never changed, the compiler will already detect that as part of it's normal operation even without the final modifier. It's pretty rare that bugs are caused by a parameter being unexpectedly assigned - if your methods are big enough to need this level of engineering, make them smaller - methods you call can't change your parameters.
Is there any performance reason to declare method parameters final in Java?
[ "", "java", "performance", "final", "" ]
I would like to make my Java/Swing application compatible with the Services-menu available on Mac OS X. For example, so that the user could select some text in JTextArea and have it converted into speech by **Services -> Speech -> Start Speaking Text**. Is there a simple way to achieve that? (The application should still be able to run on platforms other than Mac OS X.)
This seems to work on Mac OS X Leopard, with no change to the original application. So I've lost interest in the answer (to how to make it work on Tiger). Thanks for your contribution, however.
Have a look at apple's [OSXAdapter package](https://developer.apple.com/samplecode/OSXAdapter/index.html) (link requires free apple developer login) for java development. The samples included in the package shows you how to integrate nicely to the OS X application menu in a way that is only activated when your application is running under OS X.
Using Mac OS X Services-menu from a Java/Swing application
[ "", "java", "macos", "swing", "" ]
How do you get the caret position in a `<textarea>` using JavaScript? For example: `This is| a text` This should return `7`. How would you get it to return the strings surrounding the cursor / selection? E.g.: `'This is', '', ' a text'`. If the word “is” is highlighted, then it would return `'This ', 'is', ' a text'`.
With Firefox, Safari (and other Gecko based browsers) you can easily use textarea.selectionStart, but for IE that doesn't work, so you will have to do something like this: ``` function getCaret(node) { if (node.selectionStart) { return node.selectionStart; } else if (!document.selection) { return 0; } var c = "\001", sel = document.selection.createRange(), dul = sel.duplicate(), len = 0; dul.moveToElementText(node); sel.text = c; len = dul.text.indexOf(c); sel.moveStart('character',-1); sel.text = ""; return len; } ``` ([complete code here](http://web.archive.org/web/20080214051356/http://www.csie.ntu.edu.tw/~b88039/html/jslib/caret.html)) I also recommend you to check the jQuery [FieldSelection](https://github.com/localhost/jquery-fieldselection) Plugin, it allows you to do that and much more... **Edit:** I actually re-implemented the above code: ``` function getCaret(el) { if (el.selectionStart) { return el.selectionStart; } else if (document.selection) { el.focus(); var r = document.selection.createRange(); if (r == null) { return 0; } var re = el.createTextRange(), rc = re.duplicate(); re.moveToBookmark(r.getBookmark()); rc.setEndPoint('EndToStart', re); return rc.text.length; } return 0; } ``` Check an example [here](http://jsbin.com/iwopa).
**Updated 5 September 2010** Seeing as everyone seems to get directed here for this issue, I'm adding my answer to a similar question, which contains the same code as this answer but with full background for those who are interested: [IE's document.selection.createRange doesn't include leading or trailing blank lines](https://stackoverflow.com/questions/3622818/ies-document-selection-createrange-doesnt-include-leading-or-trailing-blank-li) To account for trailing line breaks is tricky in IE, and I haven't seen any solution that does this correctly, including any other answers to this question. It is possible, however, using the following function, which will return you the start and end of the selection (which are the same in the case of a caret) within a `<textarea>` or text `<input>`. Note that the textarea must have focus for this function to work properly in IE. If in doubt, call the textarea's `focus()` method first. ``` function getInputSelection(el) { var start = 0, end = 0, normalizedValue, range, textInputRange, len, endRange; if (typeof el.selectionStart == "number" && typeof el.selectionEnd == "number") { start = el.selectionStart; end = el.selectionEnd; } else { range = document.selection.createRange(); if (range && range.parentElement() == el) { len = el.value.length; normalizedValue = el.value.replace(/\r\n/g, "\n"); // Create a working TextRange that lives only in the input textInputRange = el.createTextRange(); textInputRange.moveToBookmark(range.getBookmark()); // Check if the start and end of the selection are at the very end // of the input, since moveStart/moveEnd doesn't return what we want // in those cases endRange = el.createTextRange(); endRange.collapse(false); if (textInputRange.compareEndPoints("StartToEnd", endRange) > -1) { start = end = len; } else { start = -textInputRange.moveStart("character", -len); start += normalizedValue.slice(0, start).split("\n").length - 1; if (textInputRange.compareEndPoints("EndToEnd", endRange) > -1) { end = len; } else { end = -textInputRange.moveEnd("character", -len); end += normalizedValue.slice(0, end).split("\n").length - 1; } } } } return { start: start, end: end }; } ```
How to get the caret column (not pixels) position in a textarea, in characters, from the start?
[ "", "javascript", "textarea", "caret", "" ]
I have a written a Visual C++ console application (i.e. subsystem:console) that prints useful diagnositic messages to the console. However, I would like to keep the application minimized most of the time, and instead of minimizing to the taskbar, appear as a nice icon on the system tray. I would also like to restore the console when the system tray icon is clicked. How should I change my program to do this?
This is going to be an ugly hack. First, you have to retrieve the `hWnd` / `hInstance` of you console application. Right now, I can only come up with one way: * Create a Guid with `CoCreateGuid()` * Convert it to a string * Set the title of the console window to this guid with `SetConsoleTitle()` * Find the `hWnd` of the your window with the Guid as the tile with `FindWindow()` * And you can do it from the usual way from this point. [See http://www.gidforums.com/t-9218.html for more info.](http://www.gidforums.com/t-9218.html) * Don't forget the rename your console window to the original title once you're done. As you can see, even though this is possible to do, it's a horrible and painful solution. Please don't do it. Please do not minimize console applications to the system tray. **It is not something you are supposed to be able to do in the Windows API.**
You might want to write a separate gui to function as a log reader. You will then find it much easier to make this minimize to the tray. It would also let you do some other stuff you might find useful, such as changing which level of logging messages are visible on the fly.
How do I write a console application in Windows that would minimize to the system tray?
[ "", "c++", "c", "windows", "visual-c++", "" ]
I am not a fan of using SQL\*PLUS as an interface to Oracle. I usually use [yasql](http://sourceforge.net/projects/yasql/), but it hasn't been updated since 2005 and can do with some improvements. A quick [Google search](http://www.google.com/search?q=sql*plus+replacement) shows yasql and [SQLPal](http://www.sqlpal.com/). I am using linux, so SQLPal is not an option. Are there any alternatives out there, or am I stuck with an interface that I do not like or one that is no longer maintained?
I presume that you want a low-overhead method of knocking out queries, but want more functions than SQL\*Plus provides? Why not use Oracle's [SQL Developer](http://www.oracle.com/technetwork/developer-tools/sql-developer/overview/index.html)? It's free. Install, make a new connection to your database, then just start typing a script. Press F5 to run it (or just the part of the script that you've highlighted).
Take a look at [gqlplus](http://gqlplus.sourceforge.net/). It wraps sql\*plus on linux and makes it more user-friendly by adding things like command history, table name completion and so on.
Is there a good alternative to SQL*PLUS for Oracle?
[ "", "sql", "database", "oracle", "sqlplus", "" ]
I have a C library with numerous math routines for dealing with vectors, matrices, quaternions and so on. It needs to remain in C because I often use it for embedded work and as a Lua extension. In addition, I have C++ class wrappers to allow for more convenient object management and operator overloading for math operations using the C API. The wrapper only consists of a header file and as much use on inlining is made as possible. Is there an appreciable penalty for wrapping the C code versus porting and inlining the implementation directly into the C++ class? This library is used in time critical applications. So, does the boost from eliminating indirection compensate for the maintenance headache of two ports? Example of C interface: ``` typedef float VECTOR3[3]; void v3_add(VECTOR3 *out, VECTOR3 lhs, VECTOR3 rhs); ``` Example of C++ wrapper: ``` class Vector3 { private: VECTOR3 v_; public: // copy constructors, etc... Vector3& operator+=(const Vector3& rhs) { v3_add(&this->v_, this->v_, const_cast<VECTOR3> (rhs.v_)); return *this; } Vector3 operator+(const Vector3& rhs) const { Vector3 tmp(*this); tmp += rhs; return tmp; } // more methods... }; ```
Your wrapper itself will be inlined, however, your method calls to the C library typically will not. (This would require link-time-optimizations which are technically possible, but to AFAIK rudimentary at best in todays tools) Generally, a function call as such is not very expensive. The cycle cost has decreased considerably over the last years, and it can be predicted easily, so the the call penalty as such is negligible. However, inlining opens the door to more optimizations: if you have v = a + b + c, your wrapper class forces the generation of stack variables, whereas for inlined calls, the majority of the data can be kept in the FPU stack. Also, inlined code allows simplifying instructions, considering constant values, and more. So while the **measure before you invest** rule holds true, I would expect some room for improvements here. --- A typical solution is to bring the C implementaiton into a format that it can be used either as inline functions or as "C" body: ``` // V3impl.inl void V3DECL v3_add(VECTOR3 *out, VECTOR3 lhs, VECTOR3 rhs) { // here you maintain the actual implementations // ... } // C header #define V3DECL void V3DECL v3_add(VECTOR3 *out, VECTOR3 lhs, VECTOR3 rhs); // C body #include "V3impl.inl" // CPP Header #define V3DECL inline namespace v3core { #include "V3impl.inl" } // namespace class Vector3D { ... } ``` This likely makes sense only for selected methods with comparedly simple bodies. I'd move the methods to a separate namespace for the C++ implementation, as you will usually not need them directly. (Note that the inline is just a compiler hint, it doesn't force the method to be inlined. But that's good: if the code size of an inner loop exceeds the instruction cache, inlining easily hurts performance) Whether the pass/return-by-reference can be resolved depends on the strength of your compiler, I've seen many where foo(X \* out) forces stack variables, whereas X foo() does keep values in registers.
If you're just wrapping the C library calls in C++ class functions (in other words, the C++ functions do nothing but call C functions), then the compiler will optimize these calls so that it's not a performance penalty.
How to synchronize C & C++ libraries with minimal performance penalty?
[ "", "c++", "c", "optimization", "portability", "maintainability", "" ]
How can I test `Controller.ViewData.ModelState`? I would prefer to do it without any mock framework.
You don't have to use a Mock if you're using the Repository Pattern for your data, of course. Some examples: <http://www.singingeels.com/Articles/Test_Driven_Development_with_ASPNET_MVC.aspx> ``` // Test for required "FirstName". controller.ViewData.ModelState.Clear(); newCustomer = new Customer { FirstName = "", LastName = "Smith", Zip = "34275", }; controller.Create(newCustomer); // Make sure that our validation found the error! Assert.IsTrue(controller.ViewData.ModelState.Count == 1, "FirstName must be required."); ```
``` //[Required] //public string Name { get; set; } //[Required] //public string Description { get; set; } ProductModelEdit model = new ProductModelEdit() ; //Init ModelState var modelBinder = new ModelBindingContext() { ModelMetadata = ModelMetadataProviders.Current.GetMetadataForType( () => model, model.GetType()), ValueProvider=new NameValueCollectionValueProvider( new NameValueCollection(), CultureInfo.InvariantCulture) }; var binder=new DefaultModelBinder().BindModel( new ControllerContext(),modelBinder ); ProductController.ModelState.Clear(); ProductController.ModelState.Merge(modelBinder.ModelState); ViewResult result = (ViewResult)ProductController.CreateProduct(null,model); Assert.IsTrue(result.ViewData.ModelState["Name"].Errors.Count > 0); Assert.True(result.ViewData.ModelState["Description"].Errors.Count > 0); Assert.True(!result.ViewData.ModelState.IsValid); ```
How can I test ModelState?
[ "", "c#", "asp.net-mvc", "" ]
How do I remove all attributes which are `undefined` or `null` in a JavaScript object? (Question is similar to [this one](https://stackoverflow.com/questions/208105/how-to-remove-a-property-from-a-javascript-object) for Arrays)
You can loop through the object: ``` var test = { test1: null, test2: 'somestring', test3: 3, } function clean(obj) { for (var propName in obj) { if (obj[propName] === null || obj[propName] === undefined) { delete obj[propName]; } } return obj } console.log(test); console.log(clean(test)); ``` If you're concerned about this property removal not running up object's proptype chain, you can also: ``` function clean(obj) { var propNames = Object.getOwnPropertyNames(obj); for (var i = 0; i < propNames.length; i++) { var propName = propNames[i]; if (obj[propName] === null || obj[propName] === undefined) { delete obj[propName]; } } } ``` A few notes on null vs undefined: ``` test.test1 === null; // true test.test1 == null; // true test.notaprop === null; // false test.notaprop == null; // true test.notaprop === undefined; // true test.notaprop == undefined; // true ```
### ES10/ES2019 examples A simple one-liner (returning a new object). ``` let o = Object.fromEntries(Object.entries(obj).filter(([_, v]) => v != null)); ``` Same as above but written as a function. ``` function removeEmpty(obj) { return Object.fromEntries(Object.entries(obj).filter(([_, v]) => v != null)); } ``` This function uses *recursion* to remove items from nested objects. ``` function removeEmpty(obj) { return Object.fromEntries( Object.entries(obj) .filter(([_, v]) => v != null) .map(([k, v]) => [k, v === Object(v) ? removeEmpty(v) : v]) ); } ``` ### ES6/ES2015 examples A simple one-liner. Warning: This mutates the given object instead of returning a new one. ``` Object.keys(obj).forEach((k) => obj[k] == null && delete obj[k]); ``` A single declaration (not mutating the given object). ``` let o = Object.keys(obj) .filter((k) => obj[k] != null) .reduce((a, k) => ({ ...a, [k]: obj[k] }), {}); ``` Same as above but written as a function. ``` function removeEmpty(obj) { return Object.entries(obj) .filter(([_, v]) => v != null) .reduce((acc, [k, v]) => ({ ...acc, [k]: v }), {}); } ``` This function uses recursion to remove items from nested objects. ``` function removeEmpty(obj) { return Object.entries(obj) .filter(([_, v]) => v != null) .reduce( (acc, [k, v]) => ({ ...acc, [k]: v === Object(v) ? removeEmpty(v) : v }), {} ); } ``` Same as the function above, but written in an imperative (non-functional) style. ``` function removeEmpty(obj) { const newObj = {}; Object.entries(obj).forEach(([k, v]) => { if (v === Object(v)) { newObj[k] = removeEmpty(v); } else if (v != null) { newObj[k] = obj[k]; } }); return newObj; } ``` ### ES5/ES2009 examples In the old days things were a lot more verbose. This is a non recursive version written in a functional style. ``` function removeEmpty(obj) { return Object.keys(obj) .filter(function (k) { return obj[k] != null; }) .reduce(function (acc, k) { acc[k] = obj[k]; return acc; }, {}); } ``` This is a non recursive version written in an imperative style. ``` function removeEmpty(obj) { const newObj = {}; Object.keys(obj).forEach(function (k) { if (obj[k] && typeof obj[k] === "object") { newObj[k] = removeEmpty(obj[k]); } else if (obj[k] != null) { newObj[k] = obj[k]; } }); return newObj; } ``` And a recursive version written in a functional style. ``` function removeEmpty(obj) { return Object.keys(obj) .filter(function (k) { return obj[k] != null; }) .reduce(function (acc, k) { acc[k] = typeof obj[k] === "object" ? removeEmpty(obj[k]) : obj[k]; return acc; }, {}); } ```
Remove blank attributes from an Object in Javascript
[ "", "javascript", "" ]
There has been a flurry of updates released to Microsoft's Silverlight over the past couple of months (Silverlight 2 beta 2 runtime + dev tools, RC0 + dev tools which broke beta 2 apps), and recently Microsoft has released the RTM. I have been trying (unsuccessfully) to integrate Sharepoint 2007 and Silverlight. Many of the sharepoint/silverlight blogs i have read are outdated, meaning that they target SL Beta 2. So, my question is... **What steps are necessary in order to host a Silverlight 2.0 (RTM) application, in a web part, on Sharepoint Server 2007 ?**
I haven't tried this out but it seems like a good start: [Silverlight Blueprint for SharePoint](http://www.codeplex.com/SL4SP)
This isn't too difficult to do. There are a few steps you need to follow: 1. [Update IIS with the xap mime type](http://blogs.conchango.com/howardvanrooijen/archive/2008/03/10/configure-mime-type-for-silverlight-2-0-in-iis.aspx). 2. Put your files some that SharePoint can get them. In our case we developed a feature which deployed the silverlight javascript files and our xap out to folders in the ISAPI folder (%Program Files%\Common Files\Microsoft Shared\web server extensions\12\ISAPI). We created a folder called \_xaps to host these files. 3. Put the Silverlight object code in either the page itself or in a content web part. [EDIT: For some reason my object code isn't showing up. So [here is a link](http://msdn.microsoft.com/en-us/library/cc189089(VS.95).aspx) to an example instead] That's all there is to it. You're probably best off creating a feature to copy of the files and update whatever page you're hosting the control in. But to just stick silverlight in SharePoint the above should work.
How to host a Silverlight app in a Sharepoint 2007 Web Part
[ "", "c#", "silverlight", "sharepoint", "" ]
I'm looking for a good open source Windows FTP client library with a public domain or BSD-type license. Something that I have access to the source code and I can use it from C++ for Windows applications in a commercial app. We have used Wininet for years and it's buggy and horrible. The last straw is the IE8 beta 2 contains a new bug in InternetGetLastResponseInfo(). I can no longer justify using Wininet when our users can install the latest version of IE and break our app. I have looked at libcurl but it is way too heavy for our needs. The only thing I need is FTP support. I could spend a day stripping out all the code in libcurl I don't need, but I'd rather just start with a nice simple FTP client library, if possible. I looked at ftplib (<http://nbpfaus.net/~pfau/ftplib/>) but it's GPL and I need this for a closed-source commercial app. I've written FTP client code before, it's not that hard (unfortunately it was 15 years ago and I don't have the source code anymore). There must be a nice simple free client library that does nothing but FTP and has a license that can be used in closed-source commercial apps. (If you are curious, the bug is that if you attempt to FtpFindFirstFile() with an FTP site where you can't make a passive-mode connection, InternetGetLastResponseInfo() doesn't return the full response. This is just one of many bugs I've found over the years. Another is that Wininet's FTP support ignores all timeout values. That particular bug has existed for years.)
You need Ultimate TCP/IP which is now free! <http://www.codeproject.com/KB/MFC/UltimateTCPIP.aspx> You get FTP. HTTP, SMTP, POP and more. You won't regret it.
I have used [libCurl](http://curl.haxx.se/) to very good effect. The only disadvantage is that, to my knowledge, there is no support for parsing directory information that comes back from FTP servers (apparently, there is no standard directory format).
Good free FTP Client Library (for Windows C++ commercial apps)?
[ "", "c++", "windows", "ftp", "" ]
Is it at all possible to do database-agnostic table dumps/hydrates? I don't have any complicated constraints. I would also settle for db-specific ways, but the more pure jdbc it is the better (I don't want to resort to impdp/expdp).
Have a look at [DBUnit](http://dbunit.sourceforge.net/). DBUnit support exporting to a xml file, and importing from a xml file. Their [faq](http://dbunit.sourceforge.net/faq.html#streaming) has some advice on how to make the export / imports fast, be sure to check that out.
DBUnit looks good, however you probably are not going to beat the vendor tools for import/export. If you are going to be importing or exporting 100,000+ rows it's probably best to use impdp/expdp. I've also done strange things like building an insert statement from a sql query and then using sqlplus to process. [select 'insert into table values ( ...'||column||' ...) ] But i was being lazy and didn't want to create a sqlldr or jdbc insert program. I've used perl the same way for when i needed larger imports.
Database agnostic jdbc table import/export to files?
[ "", "sql", "mysql", "oracle", "jdbc", "dump", "" ]
1. **When an object is instantiated in Java, what is really going into memory?** 2. Are copies of parent constructors included? 3. Why do hidden data members behave differently than overridden methods when casting? I understand the abstract explanations that are typically given to get you use this stuff correctly, but how does the JVM really do it.
When an object is instantiated, only the non-static data is actually "Created", along with a reference to the type of object that created it. None of the methods are ever copied. The "Reference" to the class that created it is actually a pointer dispatch table. One pointer exists for each method that is available to the class. The pointers always point to the "correct" (usually the lowest/most specific in the object tree) implementation of the method. That way if you have a top-level call to another method, but the other method has been overridden, the overridden method will be called because that's where the pointer in the table points. Because of this mechanism, it shouldn't take more time to call an overridden method than a top-level one. The pointer table + member variables are the "Instance" of a class. The variable issue has to do with a completely different mechanism, "Name spaces". Variables aren't "Subclassed" at all (They don't go into the dispatch table), but public or protected variables can be hidden by local variables. This is all done by the compiler at compile time and has nothing to do with your runtime object instances. The compiler determines which object you really want and stuffs a reference to that into your code. The scoping rules are generally to favor the "Nearest" variable. Anything further away with the same name will just be ignored (shadowed) in favor of the nearer definition. To get a little more specific about memory allocation if you are interested: all "OBJECTS" are allocated on the "Heap" (Actually something amazingly more efficient and beautiful than a true heap, but same concept.) Variables are always pointers--Java will never copy an object, you always copy a pointer to that object. Variable pointer allocations for method parameters and local variables are done on the stack, but even though the variable (pointer) is created on the stack, the objects they point to are still never allocated on the stack. I'm tempted to write an example, but this is already too long. If you want me to type out a couple classes with an extends relationship and how their methods and data effect the code generated I can... just ask.
I think you'll find this to be a comprehensive example: <http://www.onjava.com/pub/a/onjava/2005/01/26/classloading.html>
Java Instantiation
[ "", "java", "oop", "jvm", "" ]
I have the following legacy code: ``` public class MyLegacyClass { private static final String jndiName = "java:comp/env/jdbc/LegacyDataSource" public static SomeLegacyClass doSomeLegacyStuff(SomeOtherLegacyClass legacyObj) { // do stuff using jndiName } } ``` This class is working in a J2EE-Container. Now I would like to test the class outside of the container. What is the best strategy? Refactoring is basically allowed. Accessing the LegacyDataSource is allowed (the test does not have to be a "pure" unit-test). EDIT: Introducing additional runtime-frameworks is not allowed.
Just to make @Robin's suggestion of a strategy pattern more concrete: (Notice that the public API of your original question remains unchanged.) ``` public class MyLegacyClass { private static Strategy strategy = new JNDIStrategy(); public static SomeLegacyClass doSomeLegacyStuff(SomeOtherLegacyClass legacyObj) { // legacy logic SomeLegacyClass result = strategy.doSomeStuff(legacyObj); // more legacy logic return result; } static void setStrategy(Strategy strategy){ MyLegacyClass.strategy = strategy; } } interface Strategy{ public SomeLegacyClass doSomeStuff(SomeOtherLegacyClass legacyObj); } class JNDIStrategy implements Strategy { private static final String jndiName = "java:comp/env/jdbc/LegacyDataSource"; public SomeLegacyClass doSomeStuff(SomeOtherLegacyClass legacyObj) { // do stuff using jndiName } } ``` ...and JUnit test. I'm not a big fan of having to do this setup/teardown maintenance, but that's an unfortunate side effect of having an API based on static methods (or Singletons for that matter). What I *do* like about this test is it does not use JNDI - that's good because (a) it'll run fast, and (b) the unit test should only be testing the business logic in doSomeLegacyStuff() method anyway, not testing the actual data source. (By the way, this assumes the test class is in the same package as MyLegacyClass.) ``` public class MyLegacyClassTest extends TestCase { private MockStrategy mockStrategy = new MockStrategy(); protected void setUp() throws Exception { MyLegacyClass.setStrategy(mockStrategy); } protected void tearDown() throws Exception { // TODO, reset original strategy on MyLegacyClass... } public void testDoSomeLegacyStuff() { MyLegacyClass.doSomeLegacyStuff(..); assertTrue(..); } static class MockStrategy implements Strategy{ public SomeLegacyClass doSomeStuff(SomeOtherLegacyClass legacyObj) { // mock behavior however you want, record state however // you'd like for test asserts. Good frameworks like Mockito exist // to help create mocks } } } ```
Refactor the code to use dependency injection. Then use you preferred DI framework (Spring, Guice, ...) to inject your resources. That will make it easy to switch between resource objects and strategies at runtime. In this case, you can inject your datasource. EDIT: Based on your new restriction, you can accomplish the same thing by using a strategy pattern to set your datasource at runtime. You can probably just use a properties file to distinguish which strategy to create and supply the datasource. This would require no new framework, you would just be hand coding the same basic functionality. We used this exact idea with a ServiceLocator to supply a mock datasource when testing outside of the Java EE container.
Refactoring static method / static field for Testing
[ "", "java", "testing", "refactoring", "static", "" ]
``` private const int THE_ANSWER = 42; ``` or ``` private const int theAnswer = 42; ``` Personally I think with modern IDEs we should go with camelCase as ALL\_CAPS looks strange. What do you think?
The recommended naming and capitalization convention is to use [**P**ascal**C**asing](https://en.wikipedia.org/wiki/Camel_case) for constants (Microsoft has a tool named [StyleCop](https://github.com/StyleCop) that documents all the preferred conventions and can check your source for compliance - though it is a little bit *too* anally retentive for many people's tastes). e.g. ``` private const int TheAnswer = 42; ``` The Pascal capitalization convention is also documented in Microsoft's [Framework Design Guidelines](https://learn.microsoft.com/en-us/dotnet/standard/design-guidelines/capitalization-conventions).
Visually, Upper Case is the way to go. It is so recognizable that way. For the sake of uniqueness and leaving no chance for guessing, I vote for UPPER\_CASE! ``` const int THE_ANSWER = 42; ``` **Note**: The Upper Case will be useful when constants are to be used within the same file at the top of the page and for intellisense purposes; however, if they were to be moved to an independent class, using Upper Case would not make much difference, as an example: ``` public static class Constant { public static readonly int Cons1 = 1; public static readonly int coNs2 = 2; public static readonly int cOns3 = 3; public static readonly int CONS4 = 4; } // Call constants from anywhere // Since the class has a unique and recognizable name, Upper Case might lose its charm private void DoSomething(){ var getCons1 = Constant.Cons1; var getCons2 = Constant.coNs2; var getCons3 = Constant.cOns3; var getCons4 = Constant.CONS4; } ```
C# naming convention for constants?
[ "", "c#", ".net", "visual-studio", "constants", "naming-conventions", "" ]
I know that in the original C++0x standard there was a feature called `export`. But I can't find a description or explanation of this feature. What is it supposed to do? Also: which compiler is supporting it?
Although Standard C++ has no such requirement, some compilers require that all function templates need to be made available in every translation unit that it is used in. In effect, for those compilers, the bodies of template functions must be made available in a header file. To repeat: that means those compilers won't allow them to be defined in non-header files such as .cpp files. To clarify, in C++ese this means that this: ``` // ORIGINAL version of xyz.h template <typename T> struct xyz { xyz(); ~xyz(); }; ``` would NOT be satisfied with these definitions of the ctor and dtors: ``` // ORIGINAL version of xyz.cpp #include "xyz.h" template <typename T> xyz<T>::xyz() {} template <typename T> xyz<T>::~xyz() {} ``` because using it: ``` // main.cpp #include "xyz.h" int main() { xyz<int> xyzint; return 0; } ``` will produce an error. For instance, with Comeau C++ you'd get: > ``` > C:\export>como xyz.cpp main.cpp > C++'ing xyz.cpp... > Comeau C/C++ 4.3.4.1 (May 29 2004 23:08:11) for MS_WINDOWS_x86 > Copyright 1988-2004 Comeau Computing. All rights reserved. > MODE:non-strict warnings microsoft C++ > > C++'ing main.cpp... > Comeau C/C++ 4.3.4.1 (May 29 2004 23:08:11) for MS_WINDOWS_x86 > Copyright 1988-2004 Comeau Computing. All rights reserved. > MODE:non-strict warnings microsoft C++ > > main.obj : error LNK2001: unresolved external symbol xyz<T1>::~xyz<int>() [with T1=int] > main.obj : error LNK2019: unresolved external symbol xyz<T1>::xyz<int>() [with T1=int] referenced in function _main > aout.exe : fatal error LNK1120: 2 unresolved externals > ``` because there is no use of the ctor or dtor within xyz.cpp, therefore, there is no instantiations that needs to occur from there. For better or worse, this is how templates work. One way around this is to explicitly request the instantiation of `xyz`, in this example of `xyz<int>`. In a brute force effort, this could be added to xyz.cpp by adding this line at the end of it: ``` template xyz<int>; ``` which requests that (all of) `xyz<int>` be instantiated. That's kind of in the wrong place though, since it means that everytime a new xyz type is brought about that the implementation file xyz.cpp must be modified. A less intrusive way to avoid that file is to create another: ``` // xyztir.cpp #include "xyz.cpp" // .cpp file!!!, not .h file!! template xyz<int>; ``` This is still somewhat painful because it still requires a manual intervention everytime a new xyz is brought forth. In a non-trivial program this could be an unreasonable maintenance demand. So instead, another way to approach this is to `#include "xyz.cpp"` into the end of xyz.h: ``` // xyz.h // ... previous content of xyz.h ... #include "xyz.cpp" ``` You could of course literally bring (cut and paste it) the contents of xyz.cpp to the end of xyz.h, hence getting rid of xyz.cpp; it's a question of file organization and in the end the results of preprocessing will be the same, in that the ctor and dtor bodies will be in the header, and hence brought into any compilation request, since that would be using the respective header. Either way, this has the side-effect that now every template is in your header file. It could slow compilation, and it could result in code bloat. One way to approach the latter is to declare the functions in question, in this case the ctor and dtor, as inline, so this would require you to modify xyz.cpp in the running example. As an aside, some compilers also require that some functions be defined inline inside a class, and not outside of one, so the setup above would need to be tweaked further in the case of those compilers. Note that this is a compiler issue, not one of Standard C++, so not all compilers require this. For instance, Comeau C++ does not, nor should it. Check out <http://www.comeaucomputing.com/4.0/docs/userman/ati.html> for details on our current setup. In short, Comeau C++ supports many models, including one which comes close to what the export keyword's intentions are (as an extension) as well as even supporting export itself. Lastly, note that the C++ export keyword is intended to alleviate the original question. However, currently Comeau C++ is the only compiler which is being publicized to support export. See <http://www.comeaucomputing.com/4.0/docs/userman/export.html> and <http://www.comeaucomputing.com/4.3.0/minor/win95+/43stuff.txt> for some details. Hopefully as other compilers reach compliance with Standard C++, this situation will change. In the example above, using export means returning to the original code which produced the linker errors, and making a change: declare the template in xyz.h with the export keyword: ``` // xyz.h export // ... ORIGINAL contents of xyz.h ... ``` The ctor and dtor in xyz.cpp will be exported simply by virtue of #includeing xyz.h, which it already does. So, in this case you don't need xyztir.cpp, nor the instantiation request at the end of xyz.cpp, and you don't need the ctor or dtor manually brought into xyz.h. With the command line shown earlier, it's possible that the compiler will do it all for you automatically.
See [this](https://isocpp.org/wiki/faq/templates#separate-template-fn-defn-from-decl-export-keyword) explanation for its use Quite a few compilers don't support it either because it's too new or in the case of gcc - because they disaprove. This post describes standard support for many compilers. [Visual Studio support for new C / C++ standards?](https://stackoverflow.com/questions/146381/visual-studio-support-for-new-c-c-standards)
What is the best explanation for the export keyword in the C++0x standard?
[ "", "c++", "" ]
I am trying to find out how much memory my application is consuming from within the program itself. The memory usage I am looking for is the number reported in the "Mem Usage" column on the Processes tab of Windows Task Manager.
A good starting point would be [GetProcessMemoryInfo](http://msdn.microsoft.com/en-us/library/ms683219.aspx), which reports various memory info about the specified process. You can pass `GetCurrentProcess()` as the process handle in order to get information about the calling process. Probably the `WorkingSetSize` member of `PROCESS_MEMORY_COUNTERS` is the closest match to the Mem Usage coulmn in task manager, but it's not going to be exactly the same. I would experiment with the different values to find the one that's closest to your needs.
I think this is what you were looking for: ``` #include<windows.h> #include<stdio.h> #include<tchar.h> // Use to convert bytes to MB #define DIV 1048576 // Use to convert bytes to MB //#define DIV 1024 // Specify the width of the field in which to print the numbers. // The asterisk in the format specifier "%*I64d" takes an integer // argument and uses it to pad and right justify the number. #define WIDTH 7 void _tmain() { MEMORYSTATUSEX statex; statex.dwLength = sizeof (statex); GlobalMemoryStatusEx (&statex); _tprintf (TEXT("There is %*ld percent of memory in use.\n"),WIDTH, statex.dwMemoryLoad); _tprintf (TEXT("There are %*I64d total Mbytes of physical memory.\n"),WIDTH,statex.ullTotalPhys/DIV); _tprintf (TEXT("There are %*I64d free Mbytes of physical memory.\n"),WIDTH, statex.ullAvailPhys/DIV); _tprintf (TEXT("There are %*I64d total Mbytes of paging file.\n"),WIDTH, statex.ullTotalPageFile/DIV); _tprintf (TEXT("There are %*I64d free Mbytes of paging file.\n"),WIDTH, statex.ullAvailPageFile/DIV); _tprintf (TEXT("There are %*I64d total Mbytes of virtual memory.\n"),WIDTH, statex.ullTotalVirtual/DIV); _tprintf (TEXT("There are %*I64d free Mbytes of virtual memory.\n"),WIDTH, statex.ullAvailVirtual/DIV); _tprintf (TEXT("There are %*I64d free Mbytes of extended memory.\n"),WIDTH, statex.ullAvailExtendedVirtual/DIV); } ```
How to get memory usage under Windows in C++
[ "", "c++", "windows", "memory-management", "" ]
What is the best way to pass data between a C server to a Java applet? Currently it's done by using a buffer and copying bytes to it using memcpy, but if the object ever changes I have to hunt down every instance of where it's being sent to the applet and have it changed. Is there a better way to pass object to java? How would you do it? Edit for clarification: It is going from the C server to the Java applet only, there is no java servlet. The only thing the Applet passes to the C server is a hex number signaling an action to be taken
You might want to take a look at [Protocol Buffers](http://code.google.com/p/protobuf/) They let you define structured data, then generate the code to read and write messages in any of the supported languages. The only catch is I think they only support C++ for now, though I know there was interest in straight C implementation.
I would have opened a socket connection between the two applications. You could serialize the object to an array of bytes and have the Java servlet deserialize it into a Java object with the same value. This way if the class definition changes, you only have to change the code in two places.
Passing data from C to Java
[ "", "java", "c", "serialization", "" ]
I've tried reading a JPG file using the `StreamReader` class' `ReadToEnd()` method which returns a string. For some reason though, when I write this string out to a file, it doesn't open. Is something lost when reading data into a string?
Strings are for *text* data. They're not for binary data - if you use them this way you *will* lose data (there are encodings you can use which won't lose data if you're lucky, but there are subtle issues which still make it a really bad idea.) If you're actually dealing with a file, the easiest way of reading the whole thing is to call [File.ReadAllBytes](http://msdn.microsoft.com/en-us/library/system.io.file.readallbytes.aspx). If you have to deal with an arbitrary stream, have a look at ["Creating a byte array from a stream"](https://stackoverflow.com/questions/221925/creating-a-byte-array-from-a-stream).
String is designed for holding unicode characters; not binary. For binary, use a `byte[]` or `Stream`. Or an `Image` etc for more specialized image handling. Despite the name, `StreamReader` is actually a specialized `TextReader` - i.e. it is a `TextReader` that reads from a `Stream`. Images are not text, so this isn't the right option.
c# - Is data "lost" when using binary data in a string?
[ "", "c#", "string", "" ]
I have a long URL with tons of parameters that I want to open in the default browser from Java on a Windows system using ``` Runtime.getRuntime().exec("rundll32 url.dll,FileProtocolHandler "+url) ``` For short URLs like "<http://www.google.com>" this works fine. But for long URLs (say, 2000 characters), this simply does absolutely nothing at all: no exception or anything of the sort, it is simply ignored. Is there a character limit a) for a Runtime.exec command or b) for the rundll32 url.dll command? If so, what is the limit?
You will be running up against [this (archived)](https://web.archive.org/web/20190902193246/https://boutell.com/newfaq/misc/urllength.html) operating system/browser specific maximum URL length problem: For "rundll32 url.dll" (i.e. Microsoft IE) you will be limited to 2,083 characters (including http://). From where I sit you have two alternatives: 1. Build (or use) a TinyURL-style service that turns your long-urls into short, redirected ones. However even here you are going to run into the same URL length issue, just within the browser itself rather than your Runtime() statement. e.g. The browser window would open, go to the short-URL which would perform the redirect to the long-URL and fail. 2. Use a POST request and bury some or all of your URL parameters within it. Rather than using a GET call you can supply very long parameters within the body of an HTTP POST request. This would not be as simple as your example code. In fact this maybe quite tricky (or impossible) with the rundll32 url.dll combination (I am not familiar with it)...
As an aside, I would suggest using the cross platform `Desktop.open()` or `Desktop.browse()` instead of Windows only `rundll32`. This will give you an IOException if it can't open the write application.
Limit for URL length for "rundll32 url.dll,FileProtocolHandler"?
[ "", "java", "windows", "url", "" ]
I have a dictionary where keys are strings, and values are integers. ``` stats = {'a': 1, 'b': 3000, 'c': 0} ``` How do I get the key with the maximum value? In this case, it is `'b'`. --- Is there a nicer approach than using an intermediate list with reversed key-value tuples? ``` inverse = [(value, key) for key, value in stats.items()] print(max(inverse)[1]) ```
You can use `operator.itemgetter` for that: ``` import operator stats = {'a': 1000, 'b': 3000, 'c': 100} max(stats.iteritems(), key=operator.itemgetter(1))[0] ``` And instead of building a new list in memory use `stats.iteritems()`. The `key` parameter to the `max()` function is a function that computes a key that is used to determine how to rank items. Please note that if you were to have another key-value pair 'd': 3000 that this method will only return **one** of the **two** even though they both have the maximum value. ``` >>> import operator >>> stats = {'a': 1000, 'b': 3000, 'c': 100, 'd': 3000} >>> max(stats.iteritems(), key=operator.itemgetter(1))[0] 'b' ``` If using Python3: ``` >>> max(stats.items(), key=operator.itemgetter(1))[0] 'b' ```
``` max(stats, key=stats.get) ```
Getting key with maximum value in dictionary?
[ "", "python", "dictionary", "max", "" ]
When I see Lua, the only thing I ever read is "great for embedding", "fast", "lightweight" and more often than anything else: "World of Warcraft" or in short "WoW". Why is it limited to embedding the whole thing into another application? Why not write general-purpose scripts like you do with Python or Perl? Lua seems to be doing great in aspects like speed and memory-usage (The fastest scripting language afaik) so why is it that I never see Lua being used as a "Desktop scripting-language" to automate tasks? For example: * Renaming a bunch of files * Download some files from the web * Webscraping Is it the lack of the standard library?
Just because it is "marketed" (in some general sense) as a special-purpose language for embedded script engines, does not mean that it is limited to that. In fact, WoW could probably just as well have chosen Python as their embedded scripting language.
Lua is a cool language, light-weight and extremely fast! But the point is: **Is performance so important for those tasks you mentioned?** * Renaming a bunch of files * Download some files from the web * Webscraping You write those programs once, and run them once, too maybe. Why do you care about performance so much for a run-once program? For example: 1. Cost 3 hours to write a C/C++ program, to handle data once, the program will take 1 hour to run. 2. Cost 30 Minute to write a Python program to handle data once, the program will take 10 hours to run. If you choose the first, you save the time to run the program, but you cost your time to develop the program. On the other hand, if you choose the second, you waste time to run the program, but you can do other things when the program is running. **How about play World of Warcraft, kill monsters with your warlock? Eat my D.O.T**! :P That's it! Although Lua is not so difficult to write, everything about Lua is designed to be efficient.And what's more, there are little modules for Lua, but there are so many modules for Python. You don't want to port a C library for Lua just for a run-once program, do you? Instead, choose Python and use those module to achieve your task easily might be a better idea. FYI: Actually, I have tried to use Lua to do webscraping, but finally, I realized I do not have to care so much about language performance. **The bottleneck of webscraping is not on the performance of the language**. The bottleneck is on network I/O, HTML parsing and multitasking. All I have to do is make sure the program works and find the bottleneck. Finally, I chose Python rather than Lua. There is so many excellent Python modules; I have no reason to build my own. According to my experience about webscraping, I chose Twisted for network I/O and lxml for html parsing as the backend of my webscraping program. I have wrote an article for an introduction to this technology. [The best choice to grab data from websites: Python + Twisted + lxml](http://blog.ez2learn.com/2009/09/26/the-best-choice-to-grab-data-from-websites-python-twisted-lxml/) Hope this is helpful.
Lua as a general-purpose scripting language?
[ "", "python", "scripting", "lua", "" ]
I have a [`draggable`](https://jqueryui.com/draggable/) with a custom [`helper`](http://api.jqueryui.com/draggable/#option-helper). Sometimes the helper is a clone and sometimes it is the original element. The problem is that when the helper is the original element and is **not** dropped on a valid droppable it gets removed. My solution looks like this so far: in my `on_dropped` callback I set `ui.helper.dropped_on_droppable` to `true`; In the `stop` callback of the draggable, I check for that variable and then ... what do I do? ``` $('.my_draggable').draggable({ stop : function(e, ui) { if (!ui.helper.dropped_on_droppable) { /* what do I do here? */ } }, ``` Is this even the right approach?
Ok, I found a solution! It's ugly and it breaks the 'rules of encapsulation,' but at least it does the job. Remember **this is just for special cases**! jQuery can handle its own helper removal just fine. In my case I had a helper that was sometimes the original element and sometimes a clone, so it wasn't always appropriate to delete the helper after reverting. ``` element.draggable({ stop : function(e, ui) { /* "dropped_on_droppable" is custom and set in my custom drop method ".moved_draggable" is custom and set in my custom drag method, to differentiate between the two types of draggables */ if (!ui.helper.dropped_on_droppable & ui.helper.hasClass('moved_draggable')) { /* this is the big hack that breaks encapsulation */ $.ui.ddmanager.current.cancelHelperRemoval = true; } }, ``` ## Warning: this breaks encapsulation and may not be forwards compatible
I might be missing something here, but is it not simply a case of adding ``` revert: "invalid" ``` to the options of the draggable if the draggable is of an original element, not a clone?
jQuery: How to stop a helper from being removed if it wasn't successfully dropped
[ "", "javascript", "jquery", "jquery-ui", "drag-and-drop", "jquery-ui-draggable", "" ]
Hi guys I wrote this code and i have two errors. 1. Invalid rank specifier: expected ',' or ']' 2. Cannot apply indexing with [] to an expression of type 'int' Can you help please? ``` static void Main(string[] args) { ArrayList numbers = new ArrayList(); foreach (int number in new int[12] {10,9,8,7,6,5,4,3,2,1}) //error No.1 { numbers.Add(number); } numbers.Insert(numbers.Count - 1, 75); numbers.Remove(7); numbers.RemoveAt(6); for(int i=0; i<numbers.Count; i++) { int number = (int) number[i]; // error No.2 Console.WriteLine(number); } } ```
``` using System; using System.Collections; namespace ConsoleApplication3 { class Program { static void Main(string[] args) { ArrayList numbers = new ArrayList(); foreach (int number in new int[] { 10, 9, 8, 7, 6, 5, 4, 3, 2, 1 }) { numbers.Add(number); } numbers.Insert(numbers.Count - 1, 75); numbers.Remove(7); numbers.RemoveAt(6); for (int i = 0; i < numbers.Count; i++) { int number = (int)numbers[i]; Console.WriteLine(number); } } } } ```
1 - You don't have to specify the length of the array just say new int[] 2 - number is just an integer, I think you're trying to access numbers[i]
Why this code is not working?
[ "", "c#", ".net", "arrays", "arraylist", "" ]
More specifically, if I have: ``` public class TempClass : TempInterface { int TempInterface.TempProperty { get; set; } int TempInterface.TempProperty2 { get; set; } public int TempProperty { get; set; } } public interface TempInterface { int TempProperty { get; set; } int TempProperty2 { get; set; } } ``` How do I use reflection to get all the propertyInfos for properties explicitly implementing TempInterface? Thanks.
I had to modify Jacob Carpenter's answer but it works nicely. nobugz's also works but Jacobs is more compact. ``` var explicitProperties = from method in typeof(TempClass).GetMethods(BindingFlags.NonPublic | BindingFlags.Instance) where method.IsFinal && method.IsPrivate select method; ```
I think the class you are looking for is System.Reflection.InterfaceMapping. ``` Type ifaceType = typeof(TempInterface); Type tempType = typeof(TempClass); InterfaceMapping map = tempType.GetInterfaceMap(ifaceType); for (int i = 0; i < map.InterfaceMethods.Length; i++) { MethodInfo ifaceMethod = map.InterfaceMethods[i]; MethodInfo targetMethod = map.TargetMethods[i]; Debug.WriteLine(String.Format("{0} maps to {1}", ifaceMethod, targetMethod)); } ```
How do I use reflection to get properties explicitly implementing an interface?
[ "", "c#", "reflection", "explicit-interface", "" ]
I'd like to format a duration in seconds using a pattern like H:MM:SS. The current utilities in java are designed to format a time but not a duration.
If you're using a version of Java prior to 8... you can use [Joda Time](http://joda-time.sourceforge.net/) and [`PeriodFormatter`](http://joda-time.sourceforge.net/api-release/org/joda/time/format/PeriodFormatter.html). If you've really got a duration (i.e. an elapsed amount of time, with no reference to a calendar system) then you should probably be using `Duration` for the most part - you can then call `toPeriod` (specifying whatever `PeriodType` you want to reflect whether 25 hours becomes 1 day and 1 hour or not, etc) to get a `Period` which you can format. If you're using Java 8 or later: I'd normally suggest using `java.time.Duration` to represent the duration. You can then call `getSeconds()` or the like to obtain an integer for standard string formatting as per bobince's answer if you need to - although you should be careful of the situation where the duration is negative, as you probably want a *single* negative sign in the output string. So something like: ``` public static String formatDuration(Duration duration) { long seconds = duration.getSeconds(); long absSeconds = Math.abs(seconds); String positive = String.format( "%d:%02d:%02d", absSeconds / 3600, (absSeconds % 3600) / 60, absSeconds % 60); return seconds < 0 ? "-" + positive : positive; } ``` Formatting this way is *reasonably* simple, if annoyingly manual. For *parsing* it becomes a harder matter in general... You could still use Joda Time even with Java 8 if you want to, of course.
If you don't want to drag in libraries, it's simple enough to do yourself using a Formatter, or related shortcut eg. given integer number of seconds s: ``` String.format("%d:%02d:%02d", s / 3600, (s % 3600) / 60, (s % 60)); ```
How to format a duration in java? (e.g format H:MM:SS)
[ "", "java", "date-formatting", "duration", "" ]
If I’m writing an applet that shows a video sequence (eg. streaming from a camera, or the applet itself is running the on the camera), do my clients need to download the Java Media Framework libraries inorder to see the sequence?
Did you consider to use [Java FX](http://javafx.com/)? This technology is dealing with this problem of downloading media libraries and so no. Of course. It is still in development. If to be first-adopter is option, it will be worth of considering this.
If the applet makes use of the JMF libraries they need to be downloaded to the client machine (where the applet executes). However, JMF gets very little development from Sun (read none) and is pretty much legacy now (*subjective*). Depending on how modern the camera is and what codecs it can output it may also be worth considering the video support in either [javafx](http://www.sun.com/software/javafx/) of flash.
Java Media Framework on client side?
[ "", "java", "applet", "jmf", "" ]
So - I have a checkbox ``` <asp:CheckBox ID="chkOrder" runat="server" Visible='<%#IsCheckBoxVisible() %>' Checked="false" OnCheckedChanged="chkOrder_CheckedChanged" AutoPostBack="true" EnableViewState="false"></asp:CheckBox> ``` the one above. Now, the checkbox is in a gridview and on databound - for all the rows in the gridview the checkbox is set to false. The problem is that the first checkbox is still true checked. In IE the problem doesn't exist, same for Chrome. I'm running out of options. Also if i use ``` $("checkboxName").attr("checked"); // verified on jquery ready function. ``` In FF it is true; IE false; Chrome false. Any tips? **EDIT** Now get ready for this : in the generated html - there is NO checked attribute. The diff between FF and IE is **exactly the same**. Another thing - the grid that contains the checkboxes has an ajax panel on it and when I page the grid, try to go to page 2 - the checkedChanged in codebehind is triggered.
In some php coding I did recently, I noticed that FF3 was remembering what I checked, even after a F5 page refresh. Looking at the source showed the correct HTML that I wanted generated. To work around this was to go up to the Address Bar and force the request for the page again. Why this work around was necessary I'm not sure, but from a normal usability perspective I appreciated it, just not during development.
Firefox remembers the state of form fields by default. `Ctrl+F5` will force Firefox to clear this cache. You can disable this for individual form and input elements: ``` <form autocomplete="off"> <input ... autocomplete="off" /> ```
Why does a checkbox remain checked in FF3 but not in IE, Chrome or
[ "", "javascript", "jquery", "asp.net", "checkbox", "" ]
I have seen the following code: ``` [DefaultValue(100)] [Description("Some descriptive field here")] public int MyProperty{...} ``` The functionality from the above snippit seems clear enough, I have no idea as to how I can use it to do useful things. Im not even sure as to what name to give it! Does anyone know where I can find more information/a tutorial on these property attributes? I would be also interested in any novel / useful tasks this feature can do.
People have already covered the UI aspect - attributes have other uses, though... for example, they are used extensively in most serialization frameworks. Some attributes are given special treatment by the compiler - for example, `[PrincipalPermission(...)]` adds declarative security to a method, allowing you to (automatically) check that the user has suitable access. To add your own special handling, you can use [PostSharp](http://www.postsharp.org/); there are many great examples of using PostSharp to do AOP things, like logging - or just code simplification, such as with [automatic `INotifyPropertyChanged` implementation](http://code.google.com/p/postsharp-user-samples/wiki/DataBindingSupport).
> The functionality from the above > snippit seems clear enough, Maybe not, as many people think that [DefaultValue()] *sets* the value of the property. Actually, all it does to tell some visual designer (e.g. Visual Studio), what the code is going to set the default value to. That way it knows to **bold** the value in the Property Window if it's set to something else.
C# property attributes
[ "", "c#", "properties", "attributes", "" ]
I've begun to the the built-in TraceSource and TraceListener classes and I would like to modify the output format of the events independently of the TraceSources and TraceListeners. It seems that the TraceListeners apply their own formatting. Is it possible to completely change the formatting without creating a new class for each and every TraceListener I use?
The Enterprise Library Logging Application Block (<http://msdn.microsoft.com/en-us/library/cc309506.aspx>) is built on the .Net TraceSource and TraceListener classes (so you can pretty much just drop it into your project and it'll work), and it supports a message formatter that you can configure in the web.config (or app.config).
This is way late, but for any latecomers who might be looking for a TraceSource/TraceListener solution that supports formatting similar to that available in log4net, NLog, and LAB, you might try [Ukadc.Diagnostics](http://ukadcdiagnostics.codeplex.com/). You can configure the Ukadc-provided TraceListeners with a formatting string, and it will be applied when traces are written to the listener. You can also write your own tokens and add them to the formatting statement. For example, I wrote one for fun that simply increments a counter each time its value is retrieved. The result is that in the log file, each line receives a sequentially increasing number. I wrote another one that allows information from Trace.CorrelationManager.LogicalOperationStack to be added to the output. I don't have easy access right now to my computer that has that work on it, or I would post these examples.
Does the .Net TraceSource/TraceListener framework have something similar to log4net's Formatters?
[ "", "c#", ".net", "trace", "" ]
I have let's say two pc's.PC-a and PC-b which both have the same application installed with java db support.I want from time to time to copy the data from the database on PC-a to database to PC-b and vice-versa so the two PC's to have the same data all the time. Is there an already implemented API in the database layer for this(i.e 1.export-backup database from PC-a 2.import-merge databases to PC-b) or i have to do this in the sql layer(manually)?
In short: You can't do this without some work on your side. SalesLogix fixed this problem by giving everything a site code, so here's how your table looked: ``` Customer: SiteCode varchar, CustomerID varchar, .... primary key(siteCode, CustomerID) ``` So now you would take your databases, and match up each record by primary key. Where there are conflicts you would have to provide a report to the end-user, on what data was different. Say machine1: ``` SiteCode|CustomerID|CustName |phone |email 1 XXX |0001 |Customer1 |555.555.1212 |darth@example.com ``` and on machine2: ``` SiteCode|CustomerID|CustName |phone |email 2 XXY |0001 |customer2 |555.555.1213 |darth@nowhere.com 3 XXX |0001 |customer1 |555.555.1212 |darth@nowhere.com ``` When performing a resolution: * Record 1 and 3 are in conflict, because the PK matches, but the data doesnt (email is different). * Record 2 is unique, and can freely exist in both databases. There is *NO* way to do this automatically without error or data corruption or referential integrity issues.
As you mention in the comments that you want to "merge" the databases, this sounds like you need to write custom code to do this, as presumably there could be conficts - the same key in both, but with different details against it, for example.
The best way to import(merge)-export java db database
[ "", "java", "database", "import", "export", "" ]
``` $images = array(); $images[0][0] = "boxes/blue.jpg"; $images[0][1] = "blah.html"; $images[1][0] = "boxes/green.jpg"; $images[1][1] = "blah.html"; $images[2][0] = "boxes/orange.jpg"; $images[2][1] = "blah.html"; $images[3][0] = "boxes/pink.jpg"; $images[3][1] = "blah.html"; $images[4][0] = "boxes/purple.jpg"; $images[4][1] = "blah.html"; $images[5][0] = "boxes/red.jpg"; $images[5][1] = "blah.html"; $images[6][0] = "boxes/yellow.jpg"; $images[6][1] = "blah.html"; $i = 0; *echo "<a href='" . $images[0][1] . "'><img src='" . $images[0][0] . "' /></a>"; $boxes = array(); while($i<5) { $rand = rand(0,(sizeof($images)-1)); //echo $rand; $slice = array_splice($images, $rand); $boxes[$i] = $slice; $i++; }* ``` I am trying to get a random image picker to choose from a list of images provided by the $images array. However, I am unable to fill the $boxes array with anything other than "Array". Can anyone tell me why? Any help is much appreciated UPDATE I am now using the code below and it breaks whenever it comes across an empty element. Unless i am very much mistaken, shouldn't splice patch up holes like that? ``` $rand = rand(0,(sizeof($images))); array_splice($images, $rand); $i = 0; while($i<5) { echo "<a href='" . $images[$i][1] . "'><img src='" . $images[$i][0] . "' /></a>"; $i++; } ```
Slightly off topic, but wouldn't it be easier in this case (picking 5 items from a list of 6) just to pick one element and discard it from the original array, and then use the original? This will also ensure you do not get duplicates in the resultant array. I realise that you may have more than 6 items in the original, and may want less than 5 from it, but I'm talking specifically about the example posted.
This might be a nicer way of doing it: ``` foreach (array_rand($images, 5) as $key) { $boxes[] = $images[$key]; } ```
Random image picker PHP
[ "", "php", "" ]
I've been a PHP developer for many years now, with many tools under my belt; tools that I've either developed myself, or free-to-use solutions that I have learned to trust. I looked into CodeIgniter recently, and discovered that they have many classes and helper routines to aid with development, yet saw nothing in the examples that I couldn't do just as easily with my own tools. Simple things like DB abstractions, Email helpers, etc. There was some interesting code relating to routes - mapping urls to the right controllers; but even that's not particularly difficult to code yourself if you've ever written an MVC style web app with pretty urls. Even after looking through some of the other popular frameworks, I still see nothing that would be **that** much of a time-saver. Even looking at the forums, I see people struggling to get the tools to work for them. I do understand how they would be more useful for junior developers, since full system design skills take a while to understand and appreciate fully. Yet, I'm often told that I should use an off-the-shelf framework to produce my solutions, but I still remain unconvinced. What's the real benefit to someone like myself? Am I just being elitist, or is this a common opinion? Edit: Looking at some of the answers here, should I perhaps consider packaging up my toolset as its very own framework, writing some documentation and posting tutorials? If I'm hesitant to take on other's frameworks, would opening it up and getting more eyes on it help to improve my own skills/tools?
Frameworks have several advantages: * You don't have to write everything. In your case, this is less of a help because you have your own framework which you have accumulated over the years. * Frameworks provide standardized and tested ways of doing things. The more users there are of a given framework, the more edge cases that have been encountered and coded for. Your own code may, or may not, be battle hardened in the same way. * Others can be recruited onto a project with a standard framework and have access to the documentation, examples and experience with that framework. Your own snippets may or may not be fully documented or have examples of use... but isn't much chance that others are comfortable with them initially. EDIT: With regards to your idea of packaging up your own framework, the benefit of cleaning it up for public consumption can be larger than the benefit of getting others to use it. The reason is simple: you will have to re-evaluate your assumptions about each component, how they fit together and how clear each piece is to understand. Once you publish your framework, your success will be strongly dependent on how easy it is to get up and running with. Big wins with little effort are essential for adoption (those wins will encourage people to delve further into the framework). Ruby on Rails in an example of a framework that gives such big wins with little effort, and then has hidden layers of features that would have overwhelmed someone just getting started. (The question of the quality of RoR apps is not the point, the point is about adoption speed). After people adopt a framework, it is about the ease of continued use. Little details like consistent parameter use patterns make all the difference here. If one class has many parameters on every method, while another has setters that are expected to be called before invoking methods, you will lose users because they can't get a "feel" for what is expected in a given case without resorting to the documents. If both ease-of-adoption and ease-of-living-with issues are addressed properly, you only have to get lucky for people to adopt your framework. If those issues are not addressed properly, even an initial interest in the framework will wane quickly. The reason is that there are *many* frameworks: you will need to stand out to gain the advantages of having others using your kit (as they rightfully are as wary of *your* framework as you are of others).
Here's another reason *not* to create your own framework. [Linus' Law](http://en.wikipedia.org/wiki/Linus%27s_Law) - "Given enough eyeballs, all bugs are shallow". In other words, the more people who use a given framework, the more solid and bug-free it is likely to be. Have you seen how many web frameworks there are for Java? Back in the day, it was fashionable for any half-decent developer/architect to write their own custom web framework. And at the end of the day, 95% of them looked like a custom implementation of Struts (the most popular Java web framework at the time). So they basically created a Struts clone that was: 1) proprietary; and 2) not as well documented and tested. Let's face it - writing our own customer framework is fun, but what happens next? It becomes a maintenance burden to keep up with the framework yourself (or the poor soul who replaces you). And maintaining software is much, much more costly, especially when it comes to custom frameworks. Is the company in business to solve domain problems or in the business of maintaining frameworks? I forget who said it, but I once heard a great quote - "The first rule to creating your own framework is: don't". Somebody else has probably gone through the effort of doing so and probably done the same work you would have done. Save yourself the time, effort, and testing.
Why do I need to use a popular framework?
[ "", "php", "frameworks", "" ]
``` today1 = new Date(); today2 = Date.parse("2008-28-10"); ``` To compare the time (millisecond) values of these I have to do the following, because today2 is just a number. ``` if (today1.getTime() == today2) ``` Why is this?
To answer the question in the title: Because they decided so when creating the JavaScript language. Probably because Java's `java.util.Date` parse function was doing the same thing, and they wanted to mimic its behavior to make the language feel more familiar. To answer the question in the text... Use this construct to get two date objects: ``` var today2 = new Date(Date.parse("2008-10-28")); ``` --- EDIT: A simple ``` var today2 = new Date("2008-10-28"); ``` also works. --- Note: Old Internet Explorer versions (anything before 9) does not understand dashes in the date string. It works with slashes, though: ``` var today2 = new Date("2008/10/28"); ``` Slashes seem to be universally understood by browsers both old and new.
If I remember correctly, Date gives you a value down to the millisecond you created the Date object. So unless this code runs exactly on 2008-28-10 at 00:00:00:000, they won't be the same. Just an addition: Date.parse() by definition returns a long value representing the millisecond value of the Date, and not the Date object itself. If you want to hold the Date object itself, just build it like so: ``` var newDate = new Date(); newDate.setFullYear(2008,9,28); ``` For more reference check out: [the Date class reference](http://www.w3schools.com/jsref/jsref_obj_date.asp)
Why does Date.parse not return a Date object?
[ "", "javascript", "" ]
I basically have a page which shows a "processing" screen which has been flushed to the browser. Later on I need to redirect this page, currently we use meta refresh and this normally works fine. With a new payment system, which includes 3D secure, we potentially end up within an iframe being directed back to our site from a third party. I need to be able to redirect from this page, either using javascript or meta-refresh, and bust out of the iframe if it exists. Cheers! (I have done busting out of iframes before but can't find my old code and a google search was useless, thought it was the perfect time to try Stackoverflow out!)
So I added the following to my redirected pages. Luckily they have nothing posted at them so can be simply redirected. Also the use of javascript is ok as it is required to get to that point in the site. ``` <script type="text/javascript" language="javascript"> if (top.frames.length>0) setTimeout("top.location = window.location;",100); </script> ```
I'm doing something similar to keep an old site inside it's frameset: ``` <SCRIPT TYPE="text/JavaScript"> if (window == top){top.location.replace("/foo.html");} </SCRIPT> ``` So to break out of the iframe, just change == to != I see that you're using setTimeout in your example. Is waiting to break out of the iframe a requirement, or would you rather it happen immediately?
Busting out of an iframe using meta-refresh or javascript?
[ "", "javascript", "html", "iframe", "redirect", "" ]
I have a class which has the following constructor ``` public DelayCompositeDesigner(DelayComposite CompositeObject) { InitializeComponent(); compositeObject = CompositeObject; } ``` along with a default constructor with no parameters. Next I'm trying to create an instance, but it only works without parameters: ``` var designer = Activator.CreateInstance(designerAttribute.Designer); ``` This works just fine, but if I want to pass parameters it does not: ``` var designer = Activator.CreateInstance(designerAttribute.Designer, new DelayComposite(4)); ``` This results in an `MissingMethodException`: > Constructor voor type > Vialis.LightLink.Controller.Scenarios.Composites.DelayCompositeDesigner > was not found Any ideas here? --- The problem is I really need to pass an object during construction. You see I have a designer which loads all the types that inherit from the `CompositeBase`. These are then added to a list from which the users can drag them to a designer. Upon doing so an instance of the dragged is added to the designer. Each of these classes have custom properties defined on them: ``` [CompositeMetaData("Delay","Sets the delay between commands",1)] [CompositeDesigner(typeof(DelayCompositeDesigner))] public class DelayComposite : CompositeBase { } ``` When the user selects an item in the designer, it looks at these attributes in order to load up a designer for that type. For example, in the case of the `DelayComposite` it would load up a user control which has a label and a slider which allow the user to set the "Delay" property of the `DelayComposite` instance. So far this works fine if I don't pass any parameters to the constructor. The designer creates an instance of the `DelayCompositeDesigner` and assigns it to the content property of a WPF `ContentPresenter`. But since that designer needs to modify the properties of the selected `DelayComposite` in the designer, I have to pass this instance to it. That is why the constructor looks lie this: ``` public DelayCompositeDesigner(DelayComposite CompositeObject) { InitializeComponent(); compositeObject = CompositeObject; } ``` Suggestions are welcome --- @VolkerK The result of your code is this: > <---- foo > Vialis.LightLink.Controller.Scenarios.Composites.DelayCompositeDesignerVoid > .ctor() > Vialis.LightLink.Controller.Scenarios.Composites.DelayCompositeDesignerVoid > .ctor(Vialis.LightLink.Controller.Scenarios.Composites.DelayComposite) > param:Vialis.LightLink.Controller.Scenarios.Composites.DelayComposite > foo ----> --- Leppie, you were correct, I had for some reason referenced the Composites assembly in my UI application... which is not something I should have done as I was loading it at runtime. The following code works: ``` object composite = Activator.CreateInstance(item.CompositType,(byte)205); var designer = Activator.CreateInstance(designerAttribute.Designer, composite); ``` As you can see the code does not have knowledge of the `DelayComposite` type. This solves the current problem, but introduces many new ones for what I want to achieve, either way thank you and thank you to everyone who has replied here. --- As for the following code, suggested by multiple people: ``` var designer = Activator.CreateInstance( designerAttribute.Designer, new object[] { new DelayComposite(4) } ); ``` The `Activator.CreateInstance` has a signature that looks like this: ``` Activator.CreateInstance(Type type, params object[] obj) ``` So it should accept my code, but I will try the suggested code **UPDATE:** I've tried this as suggested: ``` var designer = Activator.CreateInstance(designerAttribute.Designer, new object[] { new DelayComposite(4)}); ``` The result is the same.
I think you are dealing with a Type mismatch. Likely the assembly is referenced in different places, or they are compiled against different versions. I suggest you iterate through the ConstructorInfo's and do a `paramtype == typeof(DelayComposite)` on the appropriate parameter.
I would think that your call would need to be: ``` var designer = Activator.CreateInstance(designerAttribute.Designer, new object[] { new DelayComposite(4) }); ``` Unless, of course, it *is* that, in which case the answer is not immediately obvious.
Activator.CreateInstance can't find the constructor (MissingMethodException)
[ "", "c#", ".net", "activator", "missingmethodexception", "" ]
example: I want to see if `array[5]` holds a value or is empty.
Elements in primitive arrays can't be empty. They'll always get initialized to something (usually `0` for `int` arrays, but depends on how you declare the array). If you declare the array like so (for example): ``` int [] myArray ; myArray = new int[7] ; ``` then all of the elements will default to `0`. An alternative syntax for declaring arrays is ``` int[] myArray = { 12, 7, 32, 15, 113, 0, 7 }; ``` where the initial values for an array (of size seven in this case) are given in the curly braces `{}`.
There is no such thing as an "empty" element in a Java array. If the array's length is at least six, then element 5 exists and it has a value. If you have not assigned anything else to that location, then it will have the value zero, just like an object's uninitialized field would have. If it is an array of `Object` descendants, then you can check whether the element is equal to `null`.
How can I see if an element in an int array is empty?
[ "", "java", "arrays", "" ]
Can someone please let me know how to get the different segments of the three rows that are intersecting in different ways using SQL? The three rows in #t2 represent sets A,B, C - I am looking for A I B, A I C, B I C, A I B I C, A' , B', C' etc., (7 possible segments with 3 rows as in a Venn diagram) where I is the Intersection. I am looking for a generic solution which can handle n number of rows in #t2. ``` -- SQL Code Begin create table #t1 (key1 int, key2 int) -- for each Key1 there can be 1 or more Key2 go create table #t2 (row_id int identity(101, 1), key1 int) --row_id is the primary key go insert into #t1 select 1, 11 union select 1, 12 union select 1, 13 union select 1, 14 union select 2, 13 union select 2, 15 union select 2, 16 union select 2, 17 union select 3, 13 union select 3, 12 union select 3, 16 union select 3, 17 -- 1 --> 11, 12, 13, 14 -- 2 --> 13, 15, 16, 17 -- 3 --> 13, 12, 16, 17 insert into #t2 (key1) select 1 union select 2 union select 3 -- SQL Code End ``` The output I am looking for is, ``` 1001 11 (A') 1001 14 (A') 1002 12 (A I C - A I B I C) 1003 13 (A I B I C) 1004 15 (B') 1005 16 (B I C - A I B I C) 1005 17 (B I C - A I B I C) ``` The output has 5 segments, instead of the possible 7 as two of them are NULL.
If I have understood the problem correctly, I think you may have to resort to using a loop to cope with 'n' number of rows ``` DECLARE @Key2 INT DECLARE @Subset VARCHAR(1000) DECLARE @tblResults TABLE ( Key2 INT, Subset VARCHAR(1000) ) SET @Subset = '' SELECT @Key2 = MIN(Key2) FROM #t1 WHILE @Key2 IS NOT NULL BEGIN SELECT @Subset = @Subset + CAST(Key1 AS VARCHAR(10)) FROM #t1 WHERE Key2 = @Key2 INSERT INTO @tblResults (Key2, Subset) VALUES (@Key2, @Subset) SET @Subset = '' SELECT @Key2 = MIN(Key2) FROM #t1 WHERE Key2 > @Key2 END SELECT * FROM @tblResults ```
How about this? ``` SELECT key2, CASE WHEN InA = 1 and InB = 1 and InC = 1 THEN 'ABC' WHEN InA = 0 and InB = 1 and InC = 1 THEN 'BC' WHEN InA = 1 and InB = 0 and InC = 1 THEN 'AC' WHEN InA = 1 and InB = 1 and InC = 0 THEN 'AB' WHEN InA = 1 and InB = 0 and InC = 0 THEN 'A' WHEN InA = 0 and InB = 1 and InC = 0 THEN 'B' WHEN InA = 0 and InB = 0 and InC = 1 THEN 'C' ELSE 'I''m broke' END as [SubSet] FROM ( SELECT key2, MAX(CASE WHEN key1 = 1 THEN 1 ELSE 0 END) as InA, MAX(CASE WHEN key1 = 2 THEN 1 ELSE 0 END) as InB, MAX(CASE WHEN key1 = 3 THEN 1 ELSE 0 END) as InC FROM #t1 WHERE key1 in (1, 2, 3) GROUP BY key2 ) sub ORDER BY key2 ```
Splitting rows in SQL
[ "", "sql", "rows", "split", "" ]
I want to capture the HTTP request header fields, primarily the Referer and User-Agent, within my client-side JavaScript. How may I access them? --- Google Analytics manages to get the data via JavaScript that they have you embed in you pages, so it is definitely possible. > **Related:** > [Accessing the web page's HTTP Headers in JavaScript](https://stackoverflow.com/questions/220231/accessing-http-headers-in-javascript)
If you want to access referrer and user-agent, those are available to client-side Javascript, but not by accessing the headers directly. To retrieve the referrer, use [`document.referrer`](https://developer.mozilla.org/en-US/docs/DOM/document.referrer). To access the user-agent, use [`navigator.userAgent`](https://developer.mozilla.org/en-US/docs/DOM/window.navigator.userAgent). As others have indicated, the HTTP headers are not available, but you specifically asked about the referer and user-agent, which are available via Javascript.
Almost by definition, the client-side JavaScript is not at the receiving end of a http request, so it has no headers to read. Most commonly, your JavaScript is the result of an http response. If you are trying to get the values of the http request that generated your response, you'll have to write server side code to embed those values in the JavaScript you produce. It gets a little tricky to have server-side code generate client side code, so be sure that is what you need. For instance, if you want the User-agent information, you might find it sufficient to get the various values that JavaScript provides for browser detection. Start with navigator.appName and navigator.appVersion.
How do I access the HTTP request header fields via JavaScript?
[ "", "javascript", "http", "http-headers", "" ]
If you want to associate some constant value with a class, here are two ways to accomplish the same goal: ``` class Foo { public: static const size_t Life = 42; }; class Bar { public: enum {Life = 42}; }; ``` Syntactically and semantically they appear to be identical from the client's point of view: ``` size_t fooLife = Foo::Life; size_t barLife = Bar::Life; ``` Is there any reason other than just pure style concerns why one would be preferable to another?
The `enum` hack used to be necessary because many compilers didn't support in-place initialization of the value. Since this is no longer an issue, go for the other option. Modern compilers are also capable of optimizing this constant so that no storage space is required for it. The only reason for not using the `static const` variant is if you want to *forbid* taking the address of the value: you can't take an address of an `enum` value while you can take the address of a constant (and this would prompt the compiler to reserve space for the value after all, but only *if* its address is really taken). Additionally, the taking of the address will yield a link-time error unless the constant is explicitly *defined* as well. Notice that it can still be initialized at the site of declaration: ``` struct foo { static int const bar = 42; // Declaration, initialization. }; int const foo::bar; // Definition. ```
They're not identical: ``` size_t *pLife1 = &Foo::Life; size_t *pLife2 = &Bar::Life; ```
static const Member Value vs. Member enum : Which Method is Better & Why?
[ "", "c++", "class-design", "" ]
I am having trouble understanding how the System Registry can help me convert a DateTime object into the a corresponding TimeZone. I have an example that I've been trying to reverse engineer but I just can't follow the one critical step in which the UTCtime is offset depending on Daylight Savings Time. I am using .NET 3.5 (thank god) but It's still baffling me. Thanks EDIT: Additional Information: This question was for use in a WPF application environment. The code snippet I left below took the answer example a step further to get exactly what I was looking for.
Here is a code snippet in C# that I'm using in my WPF application. This will give you the current time (adjusted for Daylight Savings Time) for the time zone id you provide. ``` // _timeZoneId is the String value found in the System Registry. // You can look up the list of TimeZones on your system using this: // ReadOnlyCollection<TimeZoneInfo> current = TimeZoneInfo.GetSystemTimeZones(); // As long as your _timeZoneId string is in the registry // the _now DateTime object will contain // the current time (adjusted for Daylight Savings Time) for that Time Zone. string _timeZoneId = "Pacific Standard Time"; DateTime startTime = DateTime.UtcNow; TimeZoneInfo tst = TimeZoneInfo.FindSystemTimeZoneById(_timeZoneId); _now = TimeZoneInfo.ConvertTime(startTime, TimeZoneInfo.Utc, tst); ``` This is the code snippit I ended up with. Thanks for the help.
You can use DateTimeOffset to get the UTC offset so you shouldn't need to dig into the registry for that information. TimeZone.CurrentTimeZone returns additional time zone data, and TimeZoneInfo.Local has meta data about the time zone (such as whether it supports daylight savings, the names for its various states, etc). Update: I think this specifically answers your question: ``` var tzi = TimeZoneInfo.FindSystemTimeZoneById("Pacific Standard Time"); var dto = new DateTimeOffset(2008, 10, 22, 13, 6, 0, tzi.BaseUtcOffset); Console.WriteLine(dto); Console.ReadLine(); ``` That code creates a DateTime at -8 offset. The default installed time zones are [listed on MSDN](http://msdn.microsoft.com/en-us/library/bb384272.aspx).
Displaying Time Zones in WPF/C#. Discover Daylight Savings Time Offset
[ "", "c#", "wpf", "datetime", "timezone", "" ]
I'm working on a time sheet application, where I'd like the user to be able to enter times in TextBoxes, e.g.: 8 a or 8:00 a or the like, just like you can in Excel. Now if you enter a *date* in a TextBox and then use DateTime.TryParse, you can enter it in several formats (Jan 31, 2007; 1/31/2007; 31/1/2007; January 31, 2007; etc.) and .NET will figure it out and turn it into a DateTime. But when I use DateTime.TryParse on a string like "8 a" or "8:00 a", it doesn't understand it. I know I can use ParseExact, but I'm wondering if there's a more flexible solution. I want .NET to get 8:00a from "8 a" or "8:00 a", and to leave the date component at the default 1/1/0001.
Come to think of it, never mind. I just noticed that if I use "am" and "pm" instead of "a" and "p", it works fine. It assumes today's date, instead of the default 1/1/0001, but that's not a problem for my purposes. (Still, any reasonably easy solution to get the "a" and "p" to work is welcome.)
You can always cheat the system (quite easily): ``` DateTime blah = DateTime.Parse("1/1/0001 " + myTimeString); ``` I've done something similar myself.
Parsing time without date in a TextBox
[ "", "c#", "wpf", "vb.net", "datetime", ".net-3.5", "" ]
We want to throw an exception, if a user calls DataContext.SubmitChanges() and the DataContext is not tracking anything. That is... it is OK to call SubmitChanges if there are no inserts, updates or deletes. But we want to ensure that the developer didn't forget to attach the entity to the DataContext. Even better... is it possible to get a collection of all entities that the DataContext is tracking (including those that are not changed)? PS: The [last question I asked](https://stackoverflow.com/questions/259219/how-can-i-reject-all-changes-in-a-linq-to-sqls-datacontext) were answered with: "do it this way instead"... please don't :-)
I don't think there are any public/protected methods that would let you get at this directly. You'd probably have to use reflection, like I did about 3 messages down [here](http://groups.google.co.uk/group/microsoft.public.dotnet.languages.csharp/browse_thread/thread/1ad473b24976235e/345083e2f19884b1), looking at the `ChangeTracker` property of the `Services`. Very ugly, I'm afraid.
Look at the ObjectTracker or something that hangs off DataContext. It has the change list stored in there. Also, I believe SubmitChanges is virtual, so you can intercept the SubmitChanges call and do some checking there.
Can I check wheter Linq 2 SQL's DataContext is tracking entities?
[ "", "c#", "linq-to-sql", "" ]
I would like to remove two files from a folder at the conclusion of my script. Do I need to create a function responsible for removing these two specific files? I would like to know in some detail how to use os.remove (if that is what I should use) properly. These two files will always be discarded at the conclusion of my script (which packages a series of files together in a zip format). Thanks in advance.
Just call `os.remove("path/to/file")`. For example, to remove the file `.emacs`, call ``` os.remove(".emacs") ``` The path should be a `str` that's the pathname of the file. It may be relative or absolute.
It sounds like what you really want is a temp file: <http://docs.python.org/library/tempfile.html>
How do I remove a specific number of files using python (version 2.5)?
[ "", "python", "file", "" ]
I have an application that I'm trying to wrap into a jar for easier deployment. The application compiles and runs fine (in a Windows cmd window) when run as a set of classes reachable from the CLASSPATH. But when I jar up my classes and try to run it with java 1.6 in the same cmd window, I start getting exceptions: ``` C:\dev\myapp\src\common\datagen>C:/apps/jdk1.6.0_07/bin/java.exe -classpath C:\myapp\libs\commons -logging-1.1.jar -server -jar DataGen.jar Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/commons/logging/LogFactory at com.example.myapp.fomc.common.datagen.DataGenerationTest.<clinit>(Unknown Source) Caused by: java.lang.ClassNotFoundException: org.apache.commons.logging.LogFactory at java.net.URLClassLoader$1.run(URLClassLoader.java:200) at java.security.AccessController.doPrivileged(Native Method) at java.net.URLClassLoader.findClass(URLClassLoader.java:188) at java.lang.ClassLoader.loadClass(ClassLoader.java:306) at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:276) at java.lang.ClassLoader.loadClass(ClassLoader.java:251) at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:319) ... 1 more ``` The funny thing is, the offending LogFactory seems to be in commons-logging-1.1.jar, which is in the class path specified. The jar file (yep, it's really there): ``` C:\dev\myapp\src\common\datagen>dir C:\myapp\libs\commons-logging-1.1.jar Volume in drive C is Local Disk Volume Serial Number is ECCD-A6A7 Directory of C:\myapp\libs 12/11/2007 11:46 AM 52,915 commons-logging-1.1.jar 1 File(s) 52,915 bytes 0 Dir(s) 10,956,947,456 bytes free ``` The contents of the commons-logging-1.1.jar file: ``` C:\dev\myapp\src\common\datagen>jar -tf C:\myapp\libs\commons-logging-1.1.jar META-INF/ META-INF/MANIFEST.MF org/ org/apache/ org/apache/commons/ org/apache/commons/logging/ org/apache/commons/logging/impl/ META-INF/LICENSE.txt META-INF/NOTICE.txt org/apache/commons/logging/Log.class org/apache/commons/logging/LogConfigurationException.class org/apache/commons/logging/LogFactory$1.class org/apache/commons/logging/LogFactory$2.class org/apache/commons/logging/LogFactory$3.class org/apache/commons/logging/LogFactory$4.class org/apache/commons/logging/LogFactory$5.class org/apache/commons/logging/LogFactory.class ... (more classes in commons-logging-1.1 ...) ``` Yep, commons-logging has the LogFactory class. And finally, the contents of my jar's manifest: ``` Manifest-Version: 1.0 Ant-Version: Apache Ant 1.6.5 Created-By: 10.0-b23 (Sun Microsystems Inc.) Main-Class: com.example.myapp.fomc.common.datagen.DataGenerationTest Class-Path: commons-logging-1.1.jar commons-lang.jar antlr.jar toplink .jar GroboTestingJUnit-1.2.1-core.jar junit.jar ``` This has stumped me, and any coworkers I've bugged for more than a day now. Just to cull the answers, for now at least, third party solutions to this are probably out due to licensing restrictions and company policies (e.g.: tools for creating exe's or packaging up jars). The ultimate goal is to create a jar that can be copied from my development Windows box to a Linux server (with any dependent jars) and used to populate a database (so classpaths may wind up being different between development and deployment environments). Any clues to this mystery would be greatly appreciated!
The -jar option is mutually exclusive of -classpath. See an old description [here](http://download.java.net/jdk8u20/docs/technotes/tools/windows/java.html) > -jar > > Execute a program encapsulated in a JAR file. The first argument is the name of a JAR file instead of a startup class name. In order for this option to work, the manifest of the JAR file must contain a line of the form Main-Class: classname. Here, classname identifies the class having the public static void main(String[] args) method that serves as your application's starting point. > > See the Jar tool reference page and the Jar trail of the Java Tutorial for information about working with Jar files and Jar-file manifests. > > ***When you use this option, the JAR file is the source of all user classes, and other user class path settings are ignored.*** A quick and dirty hack is to append your classpath to the bootstrap classpath: > -Xbootclasspath/a:***path*** > > Specify a colon-separated path of directires, JAR archives, and ZIP archives to append to the default bootstrap class path. However, as [@Dan](https://stackoverflow.com/users/5171/dan-dyer) rightly says, the correct solution is to ensure your JARs Manifest contains the classpath for all JARs it will need.
You can omit the `-jar` option and start the jar file like this: `java -cp MyJar.jar;C:\externalJars\* mainpackage.MyMainClass`
NoClassDefFoundError while trying to run my jar with java.exe -jar...what's wrong?
[ "", "java", "jar", "classpath", "executable-jar", "" ]
Once I have all the files I require in a particular folder, I would like my python script to zip the folder contents. Is this possible? And how could I go about doing it?
Adapted version of [the script](http://mail.python.org/pipermail/python-list/2006-May/384142.html) is: ``` #!/usr/bin/env python from __future__ import with_statement from contextlib import closing from zipfile import ZipFile, ZIP_DEFLATED import os def zipdir(basedir, archivename): assert os.path.isdir(basedir) with closing(ZipFile(archivename, "w", ZIP_DEFLATED)) as z: for root, dirs, files in os.walk(basedir): #NOTE: ignore empty directories for fn in files: absfn = os.path.join(root, fn) zfn = absfn[len(basedir)+len(os.sep):] #XXX: relative path z.write(absfn, zfn) if __name__ == '__main__': import sys basedir = sys.argv[1] archivename = sys.argv[2] zipdir(basedir, archivename) ``` Example: ``` C:\zipdir> python -mzipdir c:\tmp\test test.zip ``` It creates `'C:\zipdir\test.zip'` archive with the contents of the `'c:\tmp\test'` directory.
On python 2.7 you might use: [shutil.make\_archive(base\_name, format[, root\_dir[, base\_dir[, verbose[, dry\_run[, owner[, group[, logger]]]]]]])](http://docs.python.org/library/shutil#shutil.make_archive). **base\_name** archive name minus extension **format** format of the archive **root\_dir** directory to compress. For example ``` shutil.make_archive(target_file, format="bztar", root_dir=compress_me) ```
How do I zip the contents of a folder using python (version 2.5)?
[ "", "python", "file", "zip", "python-2.5", "" ]