Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
Possible to get the current mouse coords with Javascript?
Source: <http://javascript.internet.com/page-details/mouse-coordinates.html> ``` <form name="Show"> X <input type="text" name="MouseX" value="0" size="4"> <br> Y <input type="text" name="MouseY" value="0" size="4"> <br> </form> <script language="JavaScript"> var IE = document.all ? true : false; if (!IE) { document.captureEvents(Event.MOUSEMOVE) } document.onmousemove = getMouseXY; var tempX = 0; var tempY = 0; function getMouseXY(e) { if (IE) {// grab the x-y pos.s if browser is IE tempX = e.clientX + document.body.scrollLeft; tempY = e.clientY + document.body.scrollTop; } else {// grab the x-y pos.s if browser is NS tempX = e.pageX; tempY = e.pageY; } if (tempX < 0) { tempX = 0; } if (tempY < 0) { tempY = 0; } document.Show.MouseX.value = tempX; document.Show.MouseY.value = tempY; return true; } </script> ```
[Here](http://www.webreference.com/programming/javascript/mk/column2/) is a compact function with a demonstration, it returns value with coordinates in .x and .y: ``` function mouseCoords(ev){ // from http://www.webreference.com/programming/javascript/mk/column2/ if(ev.pageX || ev.pageY){ return {x:ev.pageX, y:ev.pageY}; } return { x:ev.clientX + document.body.scrollLeft - document.body.clientLeft, y:ev.clientY + document.body.scrollTop - document.body.clientTop }; } ``` (I found quirksmode to be a good resource of JavaScript wisdom. [Here](http://www.quirksmode.org/js/events_properties.html#position) is the some background of the function in case you want to dig deeper.)
Possible to get the current mouse coords with Javascript?
[ "", "javascript", "" ]
The `__COUNTER__` symbol is provided by [VC++](http://msdn.microsoft.com/en-us/library/b0084kay(VS.80).aspx) and GCC, and gives an increasing non-negative integral value each time it is used. I'm interested to learn whether anyone's ever used it, and whether it's something that would be worth standardising?
It's used in the [xCover](http://www.sourceforge.net/projects/xcover) code coverage library, to mark the lines that execution passes through, to find ones that are not covered.
`__COUNTER__` is useful anywhere you need a unique name. I have used it extensively for RAII style locks and stacks. Consider: ``` struct TLock { void Lock(); void Unlock(); } g_Lock1, g_Lock2; struct TLockUse { TLockUse( TLock &lock ):m_Lock(lock){ m_Lock.Lock(); } ~TLockUse(){ m_Lock.Unlock(); } TLock &m_Lock; }; void DoSomething() { TLockUse lock_use1( g_Lock1 ); TLockUse lock_use2( g_Lock2 ); // ... } ``` It gets tedious to name the lock uses, and can even become a source of errors if they're not all declared at the top of a block. How do you know if you're on `lock_use4` or `lock_use11`? It's also needless pollution of the namespace - I never need to refer to the lock use objects by name. So I use `__COUNTER__`: ``` #define CONCAT_IMPL( x, y ) x##y #define MACRO_CONCAT( x, y ) CONCAT_IMPL( x, y ) #define USE_LOCK( lock ) TLockUse MACRO_CONCAT( LockUse, __COUNTER__ )( lock ) void DoSomething2() { USE_LOCK( g_Lock1 ); USE_LOCK( g_Lock2 ); // ... } ``` But don't get hung up on the fact I called the objects locks - any function(s) that need to get called in matching pairs fit this pattern. You might even have multiple uses on the same "lock" in a given block.
Has anyone ever had a use for the __COUNTER__ pre-processor macro?
[ "", "c++", "c", "" ]
Consider this: ``` var me = new { FirstName = "John", LastName = "Smith" }; ``` This is fine as we can then do this: ``` Console.WriteLine("{0} {1}", me.FirstName, me.LastName); ``` However we can't do this: ``` public T GetMe() { return new { FirstName = "John", LastName = "Smith" }; } ``` because we don't know the type of T. We could do this: ``` public object GetMe() { return new { FirstName = "John", LastName = "Smith" }; } ``` but then we'd have to inspect the properties of the object using reflection in order to access them: ``` var p = new Prog(); object o = p.GetMe(); Type t = o.GetType(); foreach (var prop in t.GetProperties()) { Console.WriteLine(prop.Name + ": " + prop.GetValue(o, null)); } ``` However what about if we could name an anonymous type as we define it? Of course it would no longer be anonymous, however it would be more succinct and maintainable than a normal class definition. Consider this: ``` public Person GetMe() { return new public class Person { FirstName = "John", LastName = "Smith" }; } ``` The benefit being it would then be possible to return the result of a complicated Linq query from a method without having to define the class explicitly. Consider this relatively complex Linq query: ``` List<int> list = new List<int>(); var query = from number in list select new { Number = number, Square = number*number, Absolute = Math.Abs(number), Range = Enumerable.Range(0, number) }; ``` Instead of defining a class like so: ``` public class MyNumbers { public int Number { get; set; } public int Square { get; set; } public int Absolute { get; set; } public IEnumerable<int> Range { get; set; } } ``` in order to return the query variable from a method we could instead just do this: ``` List<int> list = new List<int>(); return from number in list select new public class MyNumbers { Number = number, Square = number*number, Absolute = Math.Abs(number), Range = Enumerable.Range(0, number) }; ```
Actually, there's a "hack" that you can do to get an anonymous type back from a method. Consider this: ``` public object MyMethod() { var myNewObject = new { stringProperty = "Hello, World!", intProperty = 1337, boolProperty = false }; return myNewObject; } public T Cast<T>(object obj, T type) { return (T)obj; } ``` You can now do this: ``` var obj = MyMethod(); var myNewObj = Cast(obj, new { stringProperty = "", intProperty = 0, boolProperty = false }); ``` The myNewObj will now be an object of the same Type as the anonymous type.
The language feature you need is: ``` public var GetMe() { return new { FirstName = "John", LastName = "Smith" }; } ``` That is, `var` would be valid as a method return type, and the compiler would infer the actual type from whatever is returned. You would then have to do this at the call site: ``` var me = GetMe(); ``` Any two anonymous types with members of the same type would be the same type, so if you wrote other functions returning the same pattern, they would have the same type. For any types A and B where B has a subset of the members of A, then A is assignment-compatible with B (B is like a base class of A). If you wrote: ``` public var GetMeFrom(var names) { return new { FirstName = names["First"], LastName = names["Last"] }; } ``` The compiler would effectively define this as a generic method with two type parameters, `T1` being the type of names and `T2` being the type returned by the indexer on `T1` that accepts a string. `T1` would be constrained so that it must have an indexer that accepts a string. And at the call site you would just pass anything that had an indexer that accepted a string and returned *any type you like*, and that would determine the type of `FirstName` and `LastName` in the type returned by `GetMeFrom`. So type inference would figure all this out for you, automatically capturing whatever type constraints are discoverable from the code.
Would .NET benefit from "named anonymous" types?
[ "", "c#", ".net", "linq", "c#-4.0", "anonymous-types", "" ]
In my controller, I have the following: ``` ViewData["myList"] = new SelectList(itemRepository.GetAll(), "Id", "Name", currentItem.Id); ``` And in the view I have: ``` <%= Html.DropDownList("myItem", (SelectList)ViewData["myList"])%> ``` The rendered drop down list *should* have the item with the Id of currentItem.Id pre-selected but it doesn't. Nothing is selected so it defaults to the first one. This worked before I updated to the RC/RC(refresh). Any ideas?
If you match the name of the key in ViewData to the name of the form field on the view, the HtmlHelpers are designed to implicitly pull from the ViewData based on that key. I would suggest changing your view code to: ``` <%= Html.DropDownList("myList") %> ``` The HtmlHelpers seem to work best when using them in this fashion (though that is not always possible). **Update:** To expand upon the reason why this seems to work while the other methods don't, I dove into the code for SelectExtensions.cs... However you call DropDownList, the private method SelectInternal is what eventually renders the actual HTML. The signature for SelectInternal looks like: ``` SelectInternal( string optionLabel, string name, IEnumerable<SelectListItem> selectList, bool usedViewData, bool allowMultiple, IDictionary<string,object> htmlAttributes ) ``` Here is the path the two usages of DropDownList take: **DropDownList("myList")** ``` DropDownList( string name ) -> SelectInternal( null, name, htmlHelper.GetSelectData(name), true, false, null ) ``` **DropDownList("myItem",(SelectList)ViewData["myList"])** DropDown ``` List( string name, IEnumerable<SelectListItem> selectList ) -> DropDownList( name, selectList, null /* object, htmlAttributes */ ) -> DropDownList( name, selectList, new RouteValueDictionary(htmlAttributes) ) -> SelectInternal( null, name, selectList, false, false, htmlAttributes ) ``` So at the end of the day, the difference between the two paths is that the way that works passes *true* into SelectInternal's **usedViewData** parameter, while the way that doesn't work passes *false*. It seems likely to me that there is a bug somewhere inside SelectInternal when **usedViewData** is *false*.
**The following works for me (using MVC RC Refresh)** In the view: ``` <%= Html.DropDownList("NAME_OF_ITEM_ID_PROPERTY", (SelectList)ViewData["myList"]) %> ``` So for your example that would probably be: ``` <%= Html.DropDownList("Id", (SelectList)ViewData["myList"]) %> ```
Html.DropDownList in ASP.NET MVC RC (refresh) not pre-selecting item
[ "", "c#", ".net", "asp.net-mvc", "" ]
I have a simple struct that has limited use. The struct is created in a method that calls the data from the database. If there is no data returned from the database I want to be able to return a null, but Visual Studio complains, Cannot convert null to PackageName.StructName because it is a non-nullable value type. How can I make it nullable?
You want to look into the [`Nullable<T>`](http://blogs.msdn.com/ericgu/archive/2004/05/27/143221.aspx) value type.
``` public struct Something { //... } public static Something GetSomethingSomehow() { Something? data = MaybeGetSomethingFrom(theDatabase); bool questionMarkMeansNullable = (data == null); return data ?? Something.DefaultValue; } ```
Making a Non-nullable value type nullable
[ "", "c#", ".net-3.5", "non-nullable", "" ]
Java's [PriorityQueue](http://java.sun.com/j2se/1.5.0/docs/api/java/util/PriorityQueue.html) places the least element at the head of the list, however I need it to place the greatest element at the head. What what's the neatest way to get a priority queue that behaves like that. Since I wrote the class stored in this queue I could simply reverse the results of `compareTo`, its not used outside this queue. However I like to make the code an accurate representation of what I'm modeling, what I'm trying to do is get the greatest first so the code should say that rather than least first with an unusual definition of least. [edit]just a quick thank you everyone, Comparator sounds like what I need just as soon as I teach myself how to write one.
Pass a [Comparator](http://java.sun.com/javase/6/docs/api/java/util/Comparator.html "Comparator JavaDoc") that inverts the natural order when you instantiate the [PriorityQueue](http://java.sun.com/javase/6/docs/api/java/util/PriorityQueue.html "Priority Queue JavaDoc"). It would look something like this: ``` public class ReverseYourObjComparator implements Comparator<YourObj> { public int compare(final YourObj arg0, final YourObj arg1) { return 0 - arg0.compareTo(arg1); } } ```
You basically have the solution right in your question: You can pass a [Comparator](http://java.sun.com/j2se/1.5.0/docs/api/java/util/Comparator.html) to the constructor of a [PriorityQueue](http://java.sun.com/j2se/1.5.0/docs/api/java/util/PriorityQueue.html). The Comparator will influence the way the items will be ordered.
In Java what should I use for a PriorityQueue that returns the greatest element first?
[ "", "java", "compare", "compareto", "" ]
``` __int64 i64FreeBytes unsigned __int64 lpFreeBytesAvailableToCaller, lpTotalNumberOfBytes, lpTotalNumberOfFreeBytes; // variables used to obtain // the free space on the drive GetDiskFreeSpaceEx (Manager.capDir, (PULARGE_INTEGER)&lpFreeBytesAvailableToCaller, (PULARGE_INTEGER)&lpTotalNumberOfBytes, (PULARGE_INTEGER)&lpTotalNumberOfFreeBytes); i64FreeBytes = lpTotalNumberOfFreeBytes; _tprintf(_T ("Number of bytes free on the drive:%I64u \n"), lpTotalNumberOfFreeBytes); ``` I am working on a data management routine which is a Windows CE command line application. The above code shows how I get the number of free bytes on a particular drive which contains the folder Manager.capdir (it is the variable containing the full path name of the directory). My question is, the number of free bytes reported by the above code (the \_tprintf statement) doesn't match with the number of free bytes of the drive (which i check by doing a right click on the drive). I wish to know if the reason for this difference?
I have a single-user machine with no disk quota in operation. I posted your code into a dialog based MFC application and ran it, with the single proviso that I used "C:\" as the lpDirectoryName parameter so I could compare against the drive free space as reported by the system. That seemed logical as free space is only meaningful for a drive, not a folder. At first I thought that I was seeing a similar problem, but then I re-ran the check (I tied it to a button), and got the same result as the properties dialog **at that moment**. It seems the free space on a drive is a fairly dynamic quantity - this is not terribly suprising if it is the system drive - and even absent the criteria that other posters have quite correctly reported, you may not see precisely the same number as the properties dialog reports at the moment it was run.
Quoting (with editing) the documentation for [GetDiskFreeSpaceEx](http://msdn.microsoft.com/en-us/library/aa364937(VS.85).aspx), emphasis mine: > lpFreeBytesAvailable [out, optional]- > > A pointer to a variable that receives > the total number of free bytes on a > disk that are **available to the user > who is associated with the calling > thread.** > > This parameter can be NULL. > > **If per-user quotas are being used, > this value may be less than the total > number of free bytes on a disk.** > > lpTotalNumberOfBytes [out, optional]- > > A pointer to a variable that receives > the total number of bytes on a disk > that are **available to the user who is > associated with the calling thread.** > > This parameter can be NULL. > > **If per-user quotas are being used, > this value may be less than the total > number of bytes on a disk.** > > To determine the total number of bytes > on a disk or volume, use > IOCTL\_DISK\_GET\_LENGTH\_INFO. In other words, this number depends on the user, and if you want to match the value returned by Explorer, use `lpFreeBytesAvailable`.
GetDiskFreeSpaceEx reports wrong number of free bytes
[ "", "c++", "winapi", "types", "windows-ce", "" ]
On our Linux system we use named pipes for interprocess communication (a producer and a consumer). In order to test the consumer (Java) code, I would like to implement (in Java) a dummy producer which writes to a named pipe which is connected to the consumer. Now the test should also work in the Windows development environment. Thus I would like to know how to create a named pipe in Windows from Java. In Linux I can use mkfifo (called using `Runtime.exec()` ), but how should I do this on Windows?
[Use Named Pipes to Communicate Between Java and .Net Processes](http://v01ver-howto.blogspot.com/2010/04/howto-use-named-pipes-to-communicate.html) Relevant part in the link ``` try { // Connect to the pipe RandomAccessFile pipe = new RandomAccessFile("\\\\.\\pipe\\testpipe", "rw"); String echoText = "Hello word\n"; // write to pipe pipe.write ( echoText.getBytes() ); // read response String echoResponse = pipe.readLine(); System.out.println("Response: " + echoResponse ); pipe.close(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } ```
In windows, [named pipes exist](http://msdn.microsoft.com/de-de/library/aa365780(en-us).aspx) but they [cannot be created as files in a writeable filesystem](http://en.wikipedia.org/wiki/Named_pipe#Named_pipes_in_Windows) and there is no command line tool. They live in a special filesystem and can be created only by using the Win32 API. Looks like you'll have to resort to native code, or switch from pipes to sockets for IPC - probably the best longterm solution, since it's much more portable.
How to open a Windows named pipe from Java?
[ "", "java", "windows", "named-pipes", "" ]
I have a table like this: ``` rowInt Value 2 23 3 45 17 10 9 0 .... ``` The column rowInt values are integer but not in a sequence with same increament. I can use the following sql to list values by rowInt: ``` SELECT * FROM myTable ORDER BY rowInt; ``` This will list values by rowInt. How can get get the difference of Value between two rows with the result like this: ``` rowInt Value Diff 2 23 22 --45-23 3 45 -35 --10-45 9 0 -45 --0-45 17 10 10 -- 10-0 .... ``` The table is in SQL 2005 (Miscrosoft)
``` SELECT [current].rowInt, [current].Value, ISNULL([next].Value, 0) - [current].Value FROM sourceTable AS [current] LEFT JOIN sourceTable AS [next] ON [next].rowInt = (SELECT MIN(rowInt) FROM sourceTable WHERE rowInt > [current].rowInt) ``` ***EDIT:*** Thinking about it, using a subquery in the select (ala Quassnoi's answer) may be more efficient. I would trial different versions, and look at the execution plans to see which would perform best on the size of data set that you have... ***EDIT2:*** I still see this garnering votes, though it's unlikely many people still use SQL Server 2005. If you have access to Windowed Functions such as `LEAD()`, then use that instead... ``` SELECT RowInt, Value, LEAD(Value, 1, 0) OVER (ORDER BY RowInt) - Value FROM sourceTable ```
``` SELECT rowInt, Value, COALESCE( ( SELECT TOP 1 Value FROM myTable mi WHERE mi.rowInt > m.rowInt ORDER BY rowInt ), 0) - Value AS diff FROM myTable m ORDER BY rowInt ```
How to get difference between two rows for a column field?
[ "", "sql", "sql-server", "t-sql", "sql-server-2005", "" ]
In order to track the overall user clickstream, I'd like to fire a JavaScript event, if the user right-clicks, and select "Open in new Tab" (or middle-clicks in most browsers) on a link. Most of these links are linking outside of my site, and I'd like to interfere with overall browser experience (such as: status bar, etc) as little as possible. What options are there to solve this?
If you're looking at ways to see outbound link hits, you could try the following: * Use a script, example link.php?src=<http://www.example.com> that increments a counter per IP & User Agent combo when clicked. This however doesn't look very good in the status bar. It could also be saved by web crawlers. * Use unobtrusive JavaScript to attach event handlers on links that are external. You could determine if they are external if the hostname is present and doesn't match the one you are on. You could then use this event handler to save the href, prevent default of click event, to increment a number much like the first script and then send the window.location to the actual href. This of course fails without JavaScript enabled/supported.
There are many ways that a user can create a new tab in a browser: * Middle click * Context menu * Mouse gesture * "New tab" button on the toolbar * "File" > "New tab" Unfortunately there is no way to handle all these and potentially more user actions that could create a new tab.
Capture link clickthrough events from JavaScript
[ "", "javascript", "dom-events", "" ]
I am writing a library that I would like to be portable. Thus, it should not depend on glibc or Microsoft extensions or anything else that is not in the standard. I have a nice hierarchy of classes derived from std::exception that I use to handle errors in logic and input. Knowing that a particular type of exception was thrown at a particular file and line number is useful, but knowing how the execution got there would be potentially much more valuable, so I have been looking at ways of acquiring the stack trace. I am aware that this data is available when building against glibc using the functions in execinfo.h (see [question 76822](https://stackoverflow.com/questions/76822/how-to-generate-a-stacktrace-when-my-c-app-crashes-using-gcc-compiler)) and through the StackWalk interface in Microsoft's C++ implementation (see [question 126450](https://stackoverflow.com/questions/126450/call-stack-at-runtime)), but I would very much like to avoid anything that is not portable. I was thinking of implementing this functionality myself in this form: ``` class myException : public std::exception { public: ... void AddCall( std::string s ) { m_vCallStack.push_back( s ); } std::string ToStr() const { std::string l_sRet = ""; ... l_sRet += "Call stack:\n"; for( int i = 0; i < m_vCallStack.size(); i++ ) l_sRet += " " + m_vCallStack[i] + "\n"; ... return l_sRet; } private: ... std::vector< std::string > m_vCallStack; }; ret_type some_function( param_1, param_2, param_3 ) { try { ... } catch( myException e ) { e.AddCall( "some_function( " + param_1 + ", " + param_2 + ", " + param_3 + " )" ); throw e; } } int main( int argc, char * argv[] ) { try { ... } catch ( myException e ) { std::cerr << "Caught exception: \n" << e.ToStr(); return 1; } return 0; } ``` Is this a terrible idea? It would mean a lot of work adding try/catch blocks to every function, but I can live with that. It would not work when the cause of the exception is memory corruption or lack of memory, but at that point you are pretty much screwed anyway. It may provide misleading information if some functions in the stack do not catch exceptions, add themselves to the list, and rethrow, but I can at least provide a guarantee that all of my library functions do so. Unlike a "real" stack trace I will not get the line number in calling functions, but at least I would have something. My primary concern is the possibility that this will cause a slowdown even when no exceptions are actually thrown. Do all of these try/catch blocks require an additional set-up and tear-down on each function invocation, or is somehow handled at compile-time? Or are there other issues I have not considered?
I think this is a really bad idea. Portability is a very worthy goal, but not when it results in a solution that is intrusive, performance-sapping, and an inferior implementation. Every platform (Windows/Linux/PS2/iPhone/etc) I've worked on has offered a way to walk the stack when an exception occurs and match addresses to function names. Yes, none of these are portable but the reporting framework can be and it usually takes less than a day or two to write a platform-specific version of stack walking code. Not only is this less time than it'd take creating/maintaining a cross-platform solution, but the results are far better; * No need to modify functions * Traps crashes in standard or third party libraries * No need for a try/catch in every function (slow and memory intensive)
Look up `Nested Diagnostic Context` once. Here is a little hint: ``` class NDC { public: static NDC* getContextForCurrentThread(); int addEntry(char const* file, unsigned lineNo); void removeEntry(int key); void dump(std::ostream& os); void clear(); }; class Scope { public: Scope(char const *file, unsigned lineNo) { NDC *ctx = NDC::getContextForCurrentThread(); myKey = ctx->addEntry(file,lineNo); } ~Scope() { if (!std::uncaught_exception()) { NDC *ctx = NDC::getContextForCurrentThread(); ctx->removeEntry(myKey); } } private: int myKey; }; #define DECLARE_NDC() Scope s__(__FILE__,__LINE__) void f() { DECLARE_NDC(); // always declare the scope // only use try/catch when you want to handle an exception // and dump the stack try { // do stuff in here } catch (...) { NDC* ctx = NDC::getContextForCurrentThread(); ctx->dump(std::cerr); ctx->clear(); } } ``` The overhead is in the implementation of the NDC. I was playing with a lazily evaluated version as well as one that only kept a fixed number of entries as well. The key point is that if you use constructors and destructors to handle the stack so that you don't need all of those nasty `try`/`catch` blocks and explicit manipulation everywhere. The only platform specific headache is the `getContextForCurrentThread()` method. You can use a platform specific implementation using thread local storage to handle the job in most if not all cases. If you are more performance oriented and live in the world of log files, then change the scope to hold a pointer to the file name and line number and omit the NDC thing altogether: ``` class Scope { public: Scope(char const* f, unsigned l): fileName(f), lineNo(l) {} ~Scope() { if (std::uncaught_exception()) { log_error("%s(%u): stack unwind due to exception\n", fileName, lineNo); } } private: char const* fileName; unsigned lineNo; }; ``` This will give you a nice stack trace in your log file when an exception is thrown. No need for any real stack walking, just a little log message when an exception is being thrown ;)
Portable C++ Stack Trace on Exception
[ "", "c++", "portability", "stack-trace", "" ]
Right now my loop is ``` for (TreeNode n = e.Node.FirstNode; n != null; n = n.NextNode) ``` and my data is something like ``` a a1 a2 b b1 ``` I want to enum breadth only (a, b etc, not a1, a2 etc). How do i do this?
Breadth first enumeration is typically done by using a queue of some sort as an ancillary data structure. First push the root onto the queue. Then, while there is something in the queue: * Pop the first item from the front of the queue. * Push its children onto the end of the queue. * Process the item you popped.
Try ``` foreach (TreeNode n in e.Node.Parent.Nodes) ``` you might have to check for a null parent and use ``` TreeNodeCollection nodes; if(e.Node.Parent != null) { nodes = e.Node.Parent.Nodes; } else { nodes = e.Node.TreeView.Nodes; } ``` This should cover the breadth first algorithm (sorry I haven't tested it) ``` Queue<TreeNode> currentLevel = new Queue<TreeNode>( nodes ); Queue<TreeNode> nextLevel = new Queue<TreeNode>(); while( currentLevel.Count > 0 ) { while( currentLevel.Count > 0 ) { TreeNode n = currentLevel.Dequeue(); // Add child items to next level foreach( TreeNode child in n.Nodes ) { nextLevel.Enqueue( child ); } } // Switch to next level currentLevel = nextLevel; nextLevel = new Queue<TreeNode>(); } ```
TreeNode Breadth first enum?
[ "", "c#", "breadth-first-search", "" ]
Is there any way to take an xml string in .net and make it easyer to read? what i mean is can i convert this: ``` <element1><element2>some data</element2></element1> ``` to this: ``` <element1> <element2> some data </element2> </element1> ``` is there any built in class for this? as sql server 2005 seems to remove all formatting on xml to save space or some thing...
If you're using .NET 3.5, you can load it as an `XDocument` and then just call ToString() which will indent it appropriately. For example: ``` using System; using System.Xml.Linq; public class Test { static void Main() { string xml = "<element1><element2>some data</element2></element1>"; XDocument doc = XDocument.Parse(xml); xml = doc.ToString(); Console.WriteLine(xml); } } ``` Result: ``` <element1> <element2>some data</element2> </element1> ``` If you're writing it to a file or other stream, then `XDocument.Save` will (by default) indent it too. (I believe `XElement` has all the same features, if you don't really need an `XDocument`.)
How do you save / write the XML back to a file ? You can create an XmlWriter and pass it an XmlWriterSettings instance, where you set the Indent property to true: ``` XmlWriterSettings settings = new XmlWriterSettings(); settings.Indent = true; XmlWriter writer = XmlWriter.Create (outputStream, settings); ```
Make xml more readable
[ "", "c#", ".net", "xml", "vb.net", "text-formatting", "" ]
I am looking for a reference card for JavaScript - for example a summary of syntax and methods parameters. Google gives me lots of choices. What is a good one?
Actually, the one I use is the first hit on a Google search - [Added Bytes Cheat Sheet](http://www.addedbytes.com/cheat-sheets/javascript-cheat-sheet/) .
Danny Goodman's [JavaScript and Browser Objects Quick Reference](http://www.dannyg.com/dl/JSB6RefBooklet.pdf) is quite useful.
JavaScript Cheat Sheet
[ "", "javascript", "" ]
I am starting Boost.Asio and trying to make examples given on official website work. here`s client code: ``` using boost::asio::ip::tcp; int _tmain(int argc, _TCHAR* argv[]) { try { boost::asio::io_service io_service; tcp::resolver resolver(io_service); tcp::resolver::query query(argv[1], "daytime"); tcp::resolver::iterator endpoint_iterator = resolver.resolve(query); tcp::resolver::iterator end; tcp::socket socket(io_service); boost::system::error_code error = boost::asio::error::host_not_found; while(error && endpoint_iterator != end) { socket.close(); socket.connect(*endpoint_iterator++, error); } if (error) throw boost::system::system_error(error); for(;;) { boost::array buf; boost::system::error_code error; std::size_t len = socket.read_some(boost::asio::buffer(buf), error); if (error == boost::asio::error::eof) break; //connection closed cleanly by peer else if (error) throw boost::system::system_error(error); std::cout.write(buf.data(), len); } } catch(std::exception& e) { //... } return 0; } ``` The question is - I can not find out what the parameters would be to run program from command prompt?
You would run the program with the IP or Hostname of the server you want to connect to. tcp::resolver::query takes the host to resolve or the IP as the first parameter and the name of the service (as defined e.g. in /etc/services on Unix hosts) - you can also use a numeric service identifier (aka port number). It returns a list of possible endpoints, as there might be several entries for a single host.
read old manual! ``` ip::tcp::resolver resolver(my_io_service); ip::tcp::resolver::query query("www.boost.org", "http"); ip::tcp::resolver::iterator iter = resolver.resolve(query); ip::tcp::resolver::iterator end; // End marker. while (iter != end) { ip::tcp::endpoint endpoint = *iter++; std::cout << endpoint << std::endl; } ``` <http://www.boost.org/doc/libs/1_38_0/doc/html/boost_asio/overview/networking/protocols.html>
Can`t really understand what the parameters for constructing tcp::resolver::query
[ "", "c++", "boost", "boost-asio", "" ]
Is it possible tell the JVM to hint the OS that a certain object should preferably not get pushed out to swap space?
The short answer is no. Java doesn't allow you any control over what is swapped in and what is 'pinned' into RAM. Worrying about this sort of thing is usually a sign that there is something else wrong in your project. The OS will on the whole do a much better job of working out what should be swapped and what shouldn't. Your job is to write your software such that it doesn't try to second guess what underlying VM/OS is going to do, just concentrate on delivering your features and a good design.
This problem has also been very noticeable in Eclipse and the KeepResident dirty hack plugin (<http://suif.stanford.edu/pub/keepresident/>) avoids it. It might be a good place to start? I have not seen it in widespread use so perhaps this has been integrated in the standard Eclipse distribution?
Tell Java not to push an object into swap space
[ "", "java", "memory-management", "virtual-memory", "" ]
My Java application require a huge memory heap. I need to launch my application using java -Xms32m -Xmx128m xyz.jar Hence, I would like to create native launcher for my Java application, where I can pass the JVM heap size parameters in. I plan to use JSmooth <http://jsmooth.sourceforge.net/> for Windows platform. However, I would also like to create native launcher for Linux and Mac. May I know which open source/ free software can help me to do so? LaunchAnywhere <http://www.zerog.com/iamanual/usermanual_ia55/WebHelp/launchanywhere/abo12e.htm> seem good. But it is a commercial software. Thanks.
This may not be the answer you want, but I would use an [application bundle on MacOS](http://developer.apple.com/documentation/Java/Conceptual/Java14Development/00-Intro/JavaDevelopment.html) and a simple shell script on linux/unix. Only reason really is that the end user experience of using web start and or shell scripts on OSX just isn't that great, Mac users expect everything to work like a Mac app bundle.
Hm, you might consider using [Java Webstart](http://en.wikipedia.org/wiki/Java_Webstart). It's a bit more than just a launcher, but it can do the things you want. It eases deployment, and you can also install applications manually and use them offline, and it's cross-platform. Or you can just write a simple launcher shell script. Many apps do that, and it works fine.
Free Native Launcher For Java At Linux and Mac
[ "", "java", "" ]
I am planning to write an simple 3d(isometric view) game in Java using jMonkeyEngine - nothing to fancy, I just want to learn something about OpenGL and writing efficient algorithms (random map generating ones). When I was planning what to do, I started wondering about switching to Python. I know that Python didn't come into existence to be a tool to write 3d games, but is it possible to write good looking games with this language? I have in mind 3d graphics, nice effects and free CPU time to power to rest of game engine? I had seen good looking java games - and too be honest, I was rather shocked when I saw level of detail achieved in Runescape HD. On the other hand, pygame.org has only 2d games, with some starting 3d projects. Are there any efficient 3d game engines for python? Is pyopengl the only alternative? Good looking games in python aren't popular or possible to achieve? I would be grateful for any information / feedback.
If you are worried about 3D performance: Most of the performance-critical parts will be handled by OpenGL (in a C library or even in hardware), so the language you use to drive it should not matter too much. To really find out if performance is a problem, you'd have to try it. But there is no reason why it cannot work in principle. At any rate, you could still optimize the critical parts, either in Python or by dropping to C. You still gain Python's benefit for most of the game engine which is less performance-critical.
Yes. Eve Online does it. <http://support.eve-online.com/Pages/KB/Article.aspx?id=128>
Can 3D OpenGL game written in Python look good and run fast?
[ "", "python", "opengl", "" ]
I was experiencing a hard time creating FK relationships in my relational SQL database and after a brief discussion at work, we realized that we have nullable columns which were most likely contributing to the problem. I have always viewed NULL as meaning unassigned, not specified, blank, etc. and have really never seen a problem with that. The other developers I was speaking with felt that the only way to handle a situation where if a relationship did exist between 2 entities, then you would have to create a table that joins the data from both entities... It seems intuitive to me at least to say that for a column that contains an ID from another table, if that column is not null, then it must have an ID from the other table, but if it is NULL then that is OK and move on. It seems like this in itself is contradictory to what some say and suggest. What is the best practice or correct way to handle situations where there could be a relationship between two tables and if a value is specified then it must be in the other table...
It's perfectly acceptable, and it means that, if that column has any value, its value must exist in another table. (I see other answers asserting otherwise, but I beg to differ.) Think a table of Vehicles and Engines, and the Engines aren't installed in a Vehicle yet (so VehicleID is null). Or an Employee table with a Supervisor column and the CEO of the company. Update: Per Solberg's request, here is an example of two tables that have a foreign key relationship showing that the foreign key field value *can* be null. ``` CREATE TABLE [dbo].[EngineTable]( [EngineID] [int] IDENTITY(1,1) NOT NULL, [EngineCylinders] smallint NOT NULL, CONSTRAINT [EngineTbl_PK] PRIMARY KEY NONCLUSTERED ( [EngineID] ASC )WITH (IGNORE_DUP_KEY = OFF) ON [PRIMARY] ) ON [PRIMARY] CREATE TABLE [dbo].[CarTable]( [CarID] [int] IDENTITY(1,1) NOT NULL, [Model] [varchar](32) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL, [EngineID] [int] NULL CONSTRAINT [PK_UnitList] PRIMARY KEY CLUSTERED ( [CarID] ASC )WITH (IGNORE_DUP_KEY = OFF) ON [PRIMARY] ) ON [PRIMARY] ALTER TABLE [dbo].[CarTable] WITH CHECK ADD CONSTRAINT [FK_Engine_Car] FOREIGN KEY([EngineID]) REFERENCES [dbo].[EngineTable] ([EngineID]) Insert Into EngineTable (EngineCylinders) Values (4); Insert Into EngineTable (EngineCylinders) Values (6); Insert Into EngineTable (EngineCylinders) Values (6); Insert Into EngineTable (EngineCylinders) Values (8); ``` -- Now some tests: ``` Insert Into CarTable (Model, EngineID) Values ('G35x', 3); -- References the third engine Insert Into CarTable (Model, EngineID) Values ('Sienna', 13); -- Invalid FK reference - throws an error Insert Into CarTable (Model) Values ('M'); -- Leaves null in the engine id field & does NOT throw an error ```
I think this debate is another byproduct of the [object-relational impedence mismatch](http://en.wikipedia.org/wiki/Object-Relational_impedance_mismatch). Some DBA-types will pedantically say never allow null in a FK based on some deeper understanding of relational algebra semantics, but application developers will argue that it makes their domain layer more elegant. The use cases for a "not yet established" relationship are valid, but with null FKs some find that it adds complexity to their queries by introducing more sophisticated features of SQL, specifically LEFT JOINs. One common alternative solution I've seen is to introduce a "null row" or "sentinel row" into each table with pk=0 or pk=1 (based on what's supported by your RDBMS). This allows you to design a domain layer with "not yet established" relationships, but also avoid introducing LEFT JOINs as you're guaranteeing there will always be something to join against. Of course, this approach requires diligence too because you're basically trading off LEFT JOINs for having to check the presence of your sentinel row in queries so you don't update/delete it, etc. Whether or not the trade offs are justified is another thing. I tend to agree that reinventing null just to avoid a fancier join seems a bit silly, but I also worked in an environment where application developers don't win debates against DBAs. **Edits** I removed some of the "matter of fact" wording and tried to clarify what I meant by "failing" joins. @wcoenen's example is the reason that I've personally heard most often for avoiding null FKs. It's not that they fail as in "broken", but rather fail--some would argue--to adhere to the principle of least surprise. Also, I turned this response into a wiki since I've essentially butchered it from its original state and borrowed from other posts.
What does/should NULL mean along with FK relationships - Database
[ "", "sql", "database-design", "null", "" ]
I'm trying to retrieve all rows inserted during a specific month. ``` SELECT dbo.Post.UserId, dbo.Post.Tags, dbo.Post.CommentCount, dbo.Post.Status, dbo.Post.PostDate, dbo.Post.[Content], dbo.Post.Title, dbo.Post.PostId, dbo.[User].DisplayName FROM dbo.Post INNER JOIN dbo.[User] ON dbo.Post.UserId = dbo.[User].UserId Where PostDate >= DATEADD(mm, 0, DATEDIFF(mm, 0, '01/28/2009')) AND PostDate <= DATEADD(mm, 0, DATEDIFF(mm, 0, '01/28/2009')) ``` Any idea's?
``` WHERE PostDate >= DATEADD(mm, DATEDIFF(mm, 0, '01/28/2009'), 0) AND PostDate < DATEADD(mm, 1 + DATEDIFF(mm, 0, '01/28/2009'), 0) ```
You mention for a "given month", I'm assuming a month number from 1 to 12. If you start with a date and just want everything that falls within that month: ``` @month = datepart(mm, 'given date'); @year = datepart(yy, 'given date'); Then use: Where datepart(mm, Post.Postdate) = @month and datepart(yy, Post.PostDate) = @year ``` like that. (I added the year in case you care about that. :-))
How to retrieve all inserted rows during a given month using T-Sql
[ "", "sql", "t-sql", "date-range", "" ]
I'm currently running several copies of PHP/FastCGI, with APC enabled (under Apache+mod\_fastcgi, if that matters). Can I share cache between the processes? How can I check if it's shared already? (I think the `apc.mmap_file_mask` ini setting might be involved, but I don't know how to use it.) (One of the reasons I think its *not* shared at the moment is that the `apc.mmap_file_mask`, as reported by the apc.php web interface flips between about 3 different values as I reload.)
APC does **not** currently share its cache between multiple php-cgi workers running under fastcgi or fcgid. See [this feature request](http://pecl.php.net/bugs/bug.php?id=11988) for details: "this behaviour is the intended one as of now". One workaround is to allow PHP to manage its own workers. You can do this using the PHP\_FCGI\_CHILDREN environment variable in your wrapper script (plenty of examples all over the web for that). You should also stop fastcgi/fcgid from spawning more than one PHP process if you want to use this method. The disadvantage with PHP\_FCGI\_CHILDREN is that its management of the workers is not as good as that provided by fcgid/fastcgi. So, there we are. APC in a fcgid/fastcgi environment means giving each PHP worker their own cache, or disabling fcgid/fastcgi's process spawning in favor of PHP's built-in management. Let's hope this changes in the future.
While it's not perfect the method Domster suggested is the best. I've been doing this for a short time on some low volume sites without errors. I wrote up a detailed explanation on [how to set up mod\_fastcgi with a shared opcode cache](http://www.brandonturner.net/blog/2009/07/fastcgi_with_php_opcode_cache/) last night. I found it very important to use mod\_fastcgi rather than the newer mod\_fcgid because mod\_fcgid will only send one request at a time to the PHP process regardless of how many children PHP has spawned via PHP\_FCGI\_CHILDREN.
How to share APC cache between several PHP processes when running under FastCGI?
[ "", "php", "fastcgi", "apc", "mmap", "" ]
I have a GridView on my aspx page which displays a collection of objects defined by the following class ``` public class Item { public string ItemName{get; set;} public object ItemValue{get; set;} } ``` Then in my aspx markup I have something like this ``` <asp:GridView ID="MyTable" runat="server"> <Columns> <asp:BoundField DataField="ItemName" /> <asp:BoundField DataField="ItemValue" /> </Columns> </asp:GridView> ``` What I want to know is: *Is there a way to use conditional formatting on the ItemValue field, so that if the object is holding a string it will return the string unchanged, or if it holds a DateTime it will displays as DateTime.ToShortDateString().*
Not sure if you can use a BoundField, but if you change it to a TemplateField you could use a formatting function like in [this link](http://www.vbforums.com/showthread.php?t=545143). ie something like ``` <%# FormatDataValue(DataBinder.Eval(Container.DataItem,"ItemValue")) %> ``` Then in your codebehind, you can add a Protected Function ``` Protected Function FormatDataValue(val as object) As String 'custom enter code hereformatting goes here End Function ``` Or you could do something in the OnRowCreated event of the gridview, like in [this link](http://www.netomatix.com/development/gridviewformatcolumn.aspx) ``` <asp:GridView ID="ctlGridView" runat="server" OnRowCreated="OnRowCreated" /> ``` this function is conditional formatting based on whether or not the datavalue is null/is a double ``` protected void OnRowCreated(object sender, GridViewRowEventArgs e) { if (e.Row.RowType == DataControlRowType.DataRow) { DataRowView drv = e.Row.DataItem as DataRowView; Object ob = drv["ItemValue"]; if (!Convert.IsDBNull(ob) ) { double dVal = 0f; if (Double.TryParse(ob.ToString(), out dVal)) { if (dVal > 3f) { TableCell cell = e.Row.Cells[1]; cell.CssClass = "heavyrow"; cell.BackColor = System.Drawing.Color.Orange; } } } } } ```
With BoundField you should modify your Item class. If you don't want to modify your CodeBehind ther is a sort of trick you can do using a TemplateField: ``` <asp:GridView ID="MyTable" runat="server" AutoGenerateColumns="False"> <Columns> <asp:BoundField DataField="ItemName" HeaderText="Name" /> <asp:TemplateField HeaderText="Value"> <ItemTemplate> <asp:Label ID="Label1" runat="server" Text='<%# ((Eval("ItemValue") is DateTime) ? ((DateTime)Eval("ItemValue")).ToShortDateString() : Eval("ItemValue")) %>'></asp:Label> </ItemTemplate> </asp:TemplateField> </Columns> </asp:GridView> ``` obviously you can do it for any type of object but maybe your "Text" field would become.. complicated.. by the way.. my CodeBehind for this example was just you class Item and this Page\_Load(): ``` protected void Page_Load(object sender, EventArgs e) { Item i1 = new Item(); i1.ItemName = "name1"; i1.ItemValue = "foo"; Item i2 = new Item(); i2.ItemName = "name2"; i2.ItemValue = DateTime.Now; List<Item> list1 = new List<Item>(); list1.Add(i1); list1.Add(i2); MyTable.DataSource = list1; MyTable.DataBind(); } ``` and the result was correct ;)
How to implement conditional formatting in a GridView
[ "", "c#", ".net", "gridview", "asp.net-2.0", "" ]
Here I am dealing with a database containing tens of millions of records. I have an application which connects to the database, gets all the data from a single column in a table and does some operation on it and updates it (for SQL Server - using cursors). For millions of records it is taking very very ... long time to update. So I want to make it faster by 1. using multiple threads with an independent connection for each thread. or 2. by using a single connection throughout all the threads to fire the update queries. Which one is faster, or if you have any other ideas plz explain. I need a solution which is independent of database type , or even if you know specific solutions for each type of db, please reply.
The speedup you're trying to achieve won't work. To the contrary, it will slow down the overall processing as the database now has also to keep multiple connections/sessions/transactions in sync. Keep with as few connections/transactions as possible for repetitive and comparable operations. If it takes too long for your taste, maybe try to analyze if the queries can be optimized somehow. Also have a look at database-specific extensions (ie bulk operations) suitable for your problem.
All depends on the database, and the hardware it is running on. If the database can make use of concurrent processing, and avoids contention on shared resources (e.g. page base locks would span multiple records, record based would not). Shared resources in this case include hardware, a single core box will not be able to execute multiple CPU intensive activities (e.g. parsing SQL) truely in parallel. Network latency is something you might help alleviate with concurrent inserts even if the database is itself not able to exploit concurrency. As with any question of performance there is substitute for testing in your specific scenario.
Will multiple connections to a database from mulitple threads of an application increase insert queries performance?
[ "", "c#", "multithreading", "database-connection", "" ]
I'm looking for a iPhone-like "picker" control that I'm able to use on the web. Accessibility is not a concern. JavaScript will be available on all clients and the web app will be run on an environment provided to the user. If the solution could gracefully degrade to a select box though, that would be great. Flash & Silverlight are not ideal (for reasons I don't care to jump into) but similar solutions in Flash & Silverlight may be appreciated by others. Here's an example of the control on an iPhone: ![Screenshot](https://farm4.static.flickr.com/3647/3360349695_c9d123e6fd.jpg)
I know this question is somewhat old, but since I have an answer I could just as well give it. Other people can still be looking for it (just like I did). I created this control to use it as a plugin with jQuery. See my blog: <http://marinovdh.wordpress.com/2011/09/14/use-the-iphone-uipickerview-control-as-a-selectbox-on-your-website-with-jquery/>
It sounds like you're looking for something already built, which I haven't seen, but it looks like you could build one by using [YUI's](http://developer.yahoo.com/yui/) Carousel Control plus Animations, [as this section on the carousel control page explains](http://developer.yahoo.com/yui/carousel/#animation). Good luck!!
iPhone-like (slot machine) 'picker' select box for the web?
[ "", "javascript", "user-interface", "picker", "" ]
I have a TrackBar control on a TabPage inside a TabControl. The background of the TrackBar is being drawn in grey while the TabPage is being drawn as white. There is no way to set the BackColor property of the TrackBar to transparent, and I can't override the drawing because there is no DrawMode property for the TrackBar. What options do I have to make the TrackBar fit in? Why doesn't it support visual styles?
You might want to look at the [TransparentTrackBar](http://www.codeplex.com/TransparentTrackBar) project on CodePlex.
Simple ``` class MyTransparentTrackBar : TrackBar { protected override void OnCreateControl() { SetStyle(ControlStyles.SupportsTransparentBackColor, true); if (Parent != null) BackColor = Parent.BackColor; base.OnCreateControl(); } } ``` I also faced this (needed a transparent-background trackbar on a tab-control, that will work with both visualstyles enabled and disabled). And this worked for me.
Trackbar Background in a TabControl
[ "", "c#", "winforms", "trackbar", "" ]
I use expiring urls to hide the urls of images I use on my sites, so that they can only be hotlinked for the duration of the life of the hash (1 hour). I check the hash sent with the file url, against a hash on the server, if they match, the script calls the following code: ``` if (isset($_GET["hash"])) { $this_min = date('Y-m-d-g',time()) . "salt" . $vid_id; $current_hash = substr(md5($this_min),0,12); $submitted_hash = mysql_real_escape_string($_GET["hash"]); if ("$current_hash" == "$submitted_hash") { $file_url2 = "directory/" . $vid_file; header('Content-Type: application/octet-stream'); header("Content-Transfer-Encoding: Binary"); header("Content-disposition: inline; filename=\"".md5($vid_file)."\""); readfile($file_url2); exit; } else { $_SESSION["message"] = "Download link expired, refresh the page and try again"; $_SESSION["message_type"] = 0; header("Location:" . $_SERVER['HTTP_REFERER']); exit; } } ``` I use this in an tag (for example, `<img src="index.php?id=123&hash=ew6rg5reg4">`and it works perfectly. If the image is hotlinked, it will stop working when the hash changes, every hour (or minute if necessary). Unfortunately, this same method doesn't work when I use it to load .flv files into a flash player, such as the JW player . No .flv file is loaded. Any way I can fix this or achieve the same thing with an alternate method?
You can't really hide a downloading URL very effectively. Safari, for example, exposes all resources downloaded via the Activity window. Just look for the item that is MB in size and that's your FLV file. The only way to keep people from ripping your FLVs is to use RTMP streaming, where they never get access to the full file.
you can stop referrers other than your domain with htaccess fils (apache server only) ``` RewriteEngine On Options +FollowSymLinks <ifmodule mod_rewrite.c> RewriteCond %{HTTP_REFERER} !^$ RewriteCond %{HTTP_REFERER} !^http://(www\.)?yourdomain.com/.*$ [NC] RewriteRule \.(gif|jpg|png|mp3|mpg|avi|mov|flv)$ - [F] </ifmodule> ```
How do you hide the url of the .flv file in a flash player?
[ "", "php", "flash", "" ]
Is it possible to have objects stored in a data structure for the duration of an App Server's uptime? Basically I want an EJB that interfaces with this Data Structure, but does not require a full fledged database solution. As an example I made this dummy animal object: ``` package com.test.entities; public class Animal implements java.io.Serializable { private static final long serialVersionUID = 3621626745694501710L; private Integer id; private String animalName; public Integer getId() { // TODO Auto-generated method stub return id; } public void setId(Integer id){ this.id=id; } public String getAnimalName(){ return animalName; } public void setAnimalName(String animalName){ this.animalName=animalName; } } ``` So here is the **EJB Remote** Interface: ``` package com.test.beans; import java.util.Map; import javax.ejb.Remote; import com.test.entities.Animal; @Remote public interface MapBeanRemote { public void addAnimal(Animal a); public void removaAnimal(Integer id); public Animal getAnimalById(Integer id); Map<Integer, Animal> getAllAnimals(); } ``` Here is the Session Bean: ``` package com.test.beans; import java.util.ConcurrentHashMap; import java.util.Map; import javax.annotation.PostConstruct; import javax.ejb.Stateless; import com.test.entities.Animal; @Stateless(mappedName="ejb/MapBean") public class MapBean implements MapBeanRemote{ Map<Integer, Animal> animalStore; @PostConstruct public void initialize(){ animalStore = new ConcurrentHashMap<Integer,Animal>(); } @Override public void addAnimal(Animal a) { if(a.getId()!=null){ animalStore.put(a.getId(), a); } } @Override public Animal getAnimalById(Integer id) { return animalStore.get(id); } @Override public void removaAnimal(Integer id) { animalStore.remove(id); } @Override public Map<Integer, Animal> getAllAnimals() { return animalStore; } } ``` So basically I want any client who wants to manipulate the Animal Map to go through this EJB and have each client accessing the same exact Map of objects. This example does not work good enough. After a while all of the animals are erased (I'm assuming when the EJB gets replaced from the bean pool) Could this somehow be injected as a resource?
This can be accomplished by putting the Map in a Singleton and accessing this singleton from the beans. That way there is a single instance for all the EJB instances (since they share the same classloader). Different Session beans in different EAR's would not work though as they would each have their own classloader, but that doesn't appear to be your scenario. Your existing usage of ConcurrentHashMap will sufficiently handle most of your cases but you still need synchronization around the addAnimal method since you need the map to be consistent between the two method calls.
New EJB 3.1 spec provides new type of beans - Singleton beans - that are exactly what you need. The only implementation with partial support of EJB 3.1 I know of is Apache OpenEJB 3.1. It includes Singleton beans but I haven't used them yet.
EJBs and Storing Objects in a Data Structure (Map, List, etc)
[ "", "java", "jboss", "jakarta-ee", "ejb-3.0", "ejb", "" ]
I have a C# Queue<TimeSpan> containing 500 elements. I need to reduce those into 50 elements by taking groups of 10 TimeSpans and selecting their average. Is there a clean way to do this? I'm thinking LINQ will help, but I can't figure out a clean way. Any ideas?
I would use the Chunk function and a loop. ``` foreach(var set in source.ToList().Chunk(10)){ target.Enqueue(TimeSpan.FromMilliseconds( set.Average(t => t.TotalMilliseconds))); } ``` Chunk is part of my standard helper library. <http://clrextensions.codeplex.com/> [Source for Chunk](http://clrextensions.codeplex.com/SourceControl/changeset/view/25483#274852)
Take a look at the [.Skip() and .Take()](http://msdn.microsoft.com/en-us/library/bb386988.aspx) extension methods to partition your queue into sets. You can then use .Average(t => t.Ticks) to get the new TimeSpan that represents the average. Just jam each of those 50 averages into a new Queue and you are good to go. ``` Queue<TimeSpan> allTimeSpans = GetQueueOfTimeSpans(); Queue<TimeSpan> averages = New Queue<TimeSpan>(50); int partitionSize = 10; for (int i = 0; i <50; i++) { var avg = allTimeSpans.Skip(i * partitionSize).Take(partitionSize).Average(t => t.Ticks) averages.Enqueue(new TimeSpan(avg)); } ``` I'm a VB.NET guy, so there may be some syntax that isn't 100% write in that example. Let me know and I'll fix it!
Clean way to reduce many TimeSpans into fewer, average TimeSpans?
[ "", "c#", "linq", "timespan", "average", "" ]
I have some elements in a ComboBox (WinForms with C#). I want their content to be static so that a user cannot change the values inside when the application is ran. I also do not want the user adding new values to the ComboBox
Use the ComboStyle property: ``` comboBox.DropDownStyle = ComboBoxStyle.DropDownList; ```
This is another method I use because changing `DropDownSyle` to `DropDownList` makes it look 3D and sometimes its just plain ugly. You can prevent user input by handling the `KeyPress` event of the ComboBox like this. ``` private void ComboBox1_KeyPress(object sender, KeyPressEventArgs e) { e.Handled = true; } ```
How to disable editing of elements in combobox for c#?
[ "", "c#", "winforms", "combobox", "" ]
I'm learning C++ and I made a new program. I deleted some of my code and now my console window is not hidden. Is there a way to make it hide on startup without them seeing it?
If you're writing a console program and you want to disconnect your program from the console it started with, then call [`FreeConsole`](http://msdn.microsoft.com/en-us/library/ms683150.aspx). Ultimately, you probably won't be satisfied with what that function really does, but that's the literal answer to the question you asked. If you're writing a program that you never want to have a console in the first place, then configure your project so that it is not a console program. "Consoleness" is a property of the EXE file. The OS reads that setting and decides whether to allocate a console for your program *before any of your code ever runs*, so you can't control it within the program. Sometimes a non-console program is called a "GUI program," so you might look for a choice between "console" and "GUI" in the configuration options of your development environment. Setting it to GUI doesn't *require* that you have any user interface at all, though. The setting merely controls whether your program starts with a console. If you're trying to write a program that can sometimes have a console and sometimes not, then please see an earlier question, [Can one executable be both a console and GUI app?](https://stackoverflow.com/questions/493536/can-one-executable-be-both-a-console-and-gui-app)
Assuming you're on windows, configure your linker to make a gui-program, not a console program. * VS: Look in Linker ptions on project properties * LINK: add /SUBSYSTEM:WINDOWS * MinGW: -mwindows
Win32 programming hiding console window
[ "", "c++", "c", "windows", "winapi", "console", "" ]
I'm having a problem sending java.util.Date objects over RMI, to and from machines in different timezones. For example, a client in Germany will send a date object to a server in the UK. 1. User enters a date string e.g. 20090220. 2. Client app in Germany converts it to date using SimpleDateFormat("yyyyMMdd") to give: Fri Feb 20 00:00:00 CET 2009 3. Server in UK receives Date over RMI as: Thu Feb 19 23:00:00 GMT 2009 4. Server stores Date into a UK Oracle Database DATE column What is the best way to get around this issue of incorrect dates? I could send the date string across and have the Server convert it to a Date, but I want to reduce the amount of work that the Server has to do. Here is a stand-alone test program showing date serialisation: ``` import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Locale; public class SerializationTest { public static void main(String[] args) throws Exception { final String yyyyMMdd = "20090220"; final Date date = new SimpleDateFormat("yyyyMMdd").parse(yyyyMMdd); if (args.length != 1) { System.out.println("Usage SerializationTest S|D"); } boolean serialise = false; if (args[0].equals("S")) { serialise = true; } else if (args[0].equals("D")) { serialise = false; } String filename = "date.ser"; if (serialise) { // write the object to file FileOutputStream fos = new FileOutputStream(filename); BufferedOutputStream bos = new BufferedOutputStream(fos); ObjectOutputStream outputStream = new ObjectOutputStream(bos); outputStream.writeObject(date); outputStream.flush(); outputStream.close(); System.out.println("Serialised: " + date); } else { FileInputStream fis = new FileInputStream(filename); BufferedInputStream bis = new BufferedInputStream(fis); ObjectInputStream inputStream = new ObjectInputStream(bis); Date outDate = (Date) inputStream.readObject(); inputStream.close(); // print the object System.out.println(outDate); } } } ```
I fail to see what your problem is here, those dates look correct to me- they're just being formatted to the locale in use. If you want the date entered by the user to be in GMT, specify the locale on the SimpleDateFormat constructor
Look at getTime() and setTime(). They should do what you're looking for. Instead of sending it over the wire as a location-specific string, send it as the number of milliseconds since epoch using getTime() on the client, then build a new Date on the client and use setTime() with the long value on the server.
Sending Dates over RMI between machines in different regions
[ "", "java", "rmi", "" ]
Is there a way to get the current cpu load under Java without using the JNI?
Use the [`ManagementFactory`](http://java.sun.com/javase/6/docs/api/java/lang/management/ManagementFactory.html) to get an [`OperatingSystemMXBean`](http://java.sun.com/javase/6/docs/api/java/lang/management/OperatingSystemMXBean.html) and call [`getSystemLoadAverage()`](http://java.sun.com/javase/6/docs/api/java/lang/management/OperatingSystemMXBean.html#getSystemLoadAverage()) on it.
**getSystemLoadAverage()** gives you value over 1 minute of time (refreshes every second) and gives this value for overall operating system. More realtime overview should be done by monitoring each thread separately. Important is also notice the monitoring refresh interval - more often you check the value, more precice it is in given moment and if you do it every millisecond, it is typically 0 or 100 (or more depending how many CPU's is there). But if we allow timeframe (for example 1 second), we get avarage over this period of time and we get more informative result. Also, it is important to notice, that it is highly unlikely, that only one thread occupies more than one CPU (core). Following implementation allows to use 3 methods: * **getTotalUsage()** - Total load by all the threads in JVM * **getAvarageUsagePerCPU()** - Avarage load per CPU (core) * **getUsageByThread(Thread t)** - Total load by specified thread ``` import java.lang.management.ManagementFactory; import java.lang.management.OperatingSystemMXBean; import java.lang.management.ThreadMXBean; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; public class MonitoringThread extends Thread { private long refreshInterval; private boolean stopped; private Map<Long, ThreadTime> threadTimeMap = new HashMap<Long, ThreadTime>(); private ThreadMXBean threadBean = ManagementFactory.getThreadMXBean(); private OperatingSystemMXBean opBean = ManagementFactory.getOperatingSystemMXBean(); public MonitoringThread(long refreshInterval) { this.refreshInterval = refreshInterval; setName("MonitoringThread"); start(); } @Override public void run() { while(!stopped) { Set<Long> mappedIds; synchronized (threadTimeMap) { mappedIds = new HashSet<Long>(threadTimeMap.keySet()); } long[] allThreadIds = threadBean.getAllThreadIds(); removeDeadThreads(mappedIds, allThreadIds); mapNewThreads(allThreadIds); Collection<ThreadTime> values; synchronized (threadTimeMap) { values = new HashSet<ThreadTime>(threadTimeMap.values()); } for (ThreadTime threadTime : values) { synchronized (threadTime) { threadTime.setCurrent(threadBean.getThreadCpuTime(threadTime.getId())); } } try { Thread.sleep(refreshInterval); } catch (InterruptedException e) { throw new RuntimeException(e); } for (ThreadTime threadTime : values) { synchronized (threadTime) { threadTime.setLast(threadTime.getCurrent()); } } } } private void mapNewThreads(long[] allThreadIds) { for (long id : allThreadIds) { synchronized (threadTimeMap) { if(!threadTimeMap.containsKey(id)) threadTimeMap.put(id, new ThreadTime(id)); } } } private void removeDeadThreads(Set<Long> mappedIds, long[] allThreadIds) { outer: for (long id1 : mappedIds) { for (long id2 : allThreadIds) { if(id1 == id2) continue outer; } synchronized (threadTimeMap) { threadTimeMap.remove(id1); } } } public void stopMonitor() { this.stopped = true; } public double getTotalUsage() { Collection<ThreadTime> values; synchronized (threadTimeMap) { values = new HashSet<ThreadTime>(threadTimeMap.values()); } double usage = 0D; for (ThreadTime threadTime : values) { synchronized (threadTime) { usage += (threadTime.getCurrent() - threadTime.getLast()) / (refreshInterval * 10000); } } return usage; } public double getAvarageUsagePerCPU() { return getTotalUsage() / opBean.getAvailableProcessors(); } public double getUsageByThread(Thread t) { ThreadTime info; synchronized (threadTimeMap) { info = threadTimeMap.get(t.getId()); } double usage = 0D; if(info != null) { synchronized (info) { usage = (info.getCurrent() - info.getLast()) / (refreshInterval * 10000); } } return usage; } static class ThreadTime { private long id; private long last; private long current; public ThreadTime(long id) { this.id = id; } public long getId() { return id; } public long getLast() { return last; } public void setLast(long last) { this.last = last; } public long getCurrent() { return current; } public void setCurrent(long current) { this.current = current; } } } ```
CPU load from Java
[ "", "java", "profiling", "" ]
How do I get the percentage and filesize from this sort of string using regex in PHP? The thing is I get this string using the `print_r()` function like so: ``` while(!feof($handle)) { $progress = fread($handle, 8192); print_r($progress); } ``` The above outputs something like this: ``` [download] 28.8% of 1.51M at 171.30k/s ETA 00:06 ``` I'm sure I need to use something like `preg_match()` but not sure how to do it for an array plus how do I reference the string. The regex needs to be placed inside the loop.
Try this: ``` foreach ($progress as $str) { if (preg_match_all('/\[download] (\d+\.\d)% of (\d+\.\d+\w)/', $str, $matches)) { var_dump($matches); } } ```
``` $string = '[download] 28.8% of 1.51M at 171.30k/s ETA 00:06 [download] 41.8% of 1.51M at 178.19k/s ETA 00:05'; // $string = file_get_contents($file_path); $pattern = '/(?<percent>[0-9]{1,2}\.[0-9]{1,2})% of (?<filesize>.+) at/'; preg_match_all($pattern, $string, $matches); print_r($matches); ```
Parse formatted text and extract two values
[ "", "php", "arrays", "regex", "file", "text-extraction", "" ]
I want to let users iterate through my dictionary without modifying it. I considertwo solutions: 1.ReadOnlyDictionary -- is there an implementation of that available? 2.Copy the entire dictionary -- what is the most efficient way to copy it ? Thanks
The easiest way to do this would probably be to implement your own collection that is a wrapper around a Dictionary, something along the lines of: ``` public class ReadOnlyDictionary<T, U> { private IDictionary<T, U> BackingStore; public ReadOnlyDictionary<T, U>(IDictionary<T, U> baseDictionary) { this.BackingStore = baseDictionary; } public U this[T index] { get { return BackingStore[index]; } } // provide whatever other methods and/or interfaces you need } ```
Keep in mind that your values will not be read only with the solutions provided for wrapping a Dictionary with only a property getter; For example: ``` ReadOnlyDictionary<int, Employee> readOnlyDict = GetDictionaryHoweverYouLike(); ReadOnlyDictionary[5].EmployeeName = "Ooops" ``` To do that you will also need to wrap your values in a read only wrapper class.
How can return reference to Dictionary from a method as readonly?
[ "", "c#", "" ]
i've got a little problem with my water effect as you can see [here](http://img23.imageshack.us/img23/6127/psglitch.png), it doesn't show up the right way. another [screen](http://img142.imageshack.us/img142/1696/27198215.png) with a diffrent texture applied shows the error in the transform something more clearly my HLSL code: ``` V2P vs(float4 inPos : POSITION, float2 inTex: TEXCOORD) { V2P Output = (V2P)0; float4x4 viewproj = mul (matView, matProjection); float4x4 worldviewproj = mul (matWorld,viewproj); float4x4 reflviewproj = mul (matRLView, matProjection); float4x4 reflworldviewproj = mul (matWorld, reflviewproj); Output.Position = mul(inPos, worldviewproj); Output.RLMapTex = mul(inPos, reflworldviewproj); return Output; } P2F ps(V2P PSIn) { P2F Output = (P2F)0; float2 ProjectedTexCoords; ProjectedTexCoords.x = PSIn.RLMapTex.x / PSIn.RLMapTex.w /2.0f + 0.5f; ProjectedTexCoords.y = -PSIn.RLMapTex.y / PSIn.RLMapTex.w /2.0f + 0.5f; float2 ProjectedRefCoords; ProjectedRefCoords.x = ( PSIn.Position.x / PSIn.Position.w) /2.0f + 0.5f; ProjectedRefCoords.y = (-PSIn.Position.y / PSIn.Position.w) /2.0f + 0.5f; Output.Color = tex2D(samRLMap, ProjectedTexCoords); return Output; } ``` the reflection map is rendered on a render target while flipping the y value of the eye along the waterheight. (and with up vector 0,-1,0) so, my question: what could be the cuase of this?
I guess i found it, the matrix i used for the reflected view, is wrong. When i use the standard view, it works fine
I'm not clear on why you are changing x. Doesn't it stay the same as y is flipped? As in ``` float2 ProjectedTexCoords; ProjectedTexCoords.x = PSIn.RLMapTex.x / PSIn.RLMapTex.w; ProjectedTexCoords.y = -PSIn.RLMapTex.y / PSIn.RLMapTex.w /2.0f + 0.5f; ```
Weird vertexshader/pixelshader glitch
[ "", "c++", "directx", "" ]
I'm using MS SQL Server but welcome comparitive solutions from other databases. This is the basic form of my query. It returns the number of calls per day from the 'incidentsm1' table: ``` SELECT COUNT(*) AS "Calls", MAX(open_time), open_day FROM ( SELECT incident_id, opened_by, open_time - (9.0/24) AS open_time, DATEPART(dd, (open_time-(9.0/24))) AS open_day FROM incidentsm1 WHERE DATEDIFF(DAY, open_time-(9.0/24), GETDATE())< 7 ) inc1 GROUP BY open_day ``` This data is used to draw a bar graph, but if there were no calls on a given day of the week, there is no result row and thus no bar, and the user is like, "why does the graph only have six days and skip from Saturday to Monday?" Somehow I need to UNION ALL with a blank row from each day or something like that, but I can't figure it out. I am constrained to what I can do with one SQL statement and I have readonly access so I can't create a temporary table or anything.
How about something like this? ``` SELECT COUNT(incident_id) AS "Calls", MAX(open_time), days.open_day FROM ( select datepart(dd,dateadd(day,-6,getdate())) as open_day union select datepart(dd,dateadd(day,-5,getdate())) as open_day union select datepart(dd,dateadd(day,-4,getdate())) as open_day union select datepart(dd,dateadd(day,-3,getdate())) as open_day union select datepart(dd,dateadd(day,-2,getdate())) as open_day union select datepart(dd,dateadd(day,-1,getdate())) as open_day union select datepart(dd,dateadd(day, 0,getdate())) as open_day ) days left join ( SELECT incident_id, opened_by, open_time - (9.0/24) AS open_time, DATEPART(dd, (open_time-(9.0/24))) AS open_day FROM incidentsm1 WHERE DATEDIFF(DAY, open_time-(9.0/24), GETDATE()) < 7 ) inc1 ON days.open_day = incidents.open_day GROUP BY days.open_day ``` I've only tested it on a simplified table schema, but I think it should work. You might need to tinker with the dateadd stuff..
Can you create a table variable with the dates that you need and then `RIGHT JOIN` onto it? For example, ``` DECLARE @dateTable TABLE ([date] SMALLDATETIME) INSERT INTO @dateTable VALUES('26 FEB 2009') INSERT INTO @dateTable VALUES('27 FEB 2009') -- etc SELECT COUNT(*) AS "Calls", MAX(open_time), open_day FROM ( SELECT incident_id, opened_by, open_time - (9.0/24) AS open_time, DATEPART(dd, (open_time-(9.0/24))) AS open_day FROM incidentsm1 RIGHT JOIN @dateTable dates ON incidentsm1.open_day = dates.date WHERE DATEDIFF(DAY, open_time-(9.0/24), GETDATE())< 7 ) inc1 GROUP BY open_day ``` The more ideal situation however, would be to have a table object with the dates in
How do I include empty rows in a single GROUP BY DAY(date_field) SQL query?
[ "", "sql", "sql-server", "date", "group-by", "" ]
What is a good way of hashing a hierarchy (similar to a file structure) in python? I could convert the whole hierarchy into a dotted string and then hash that, but is there a better (or more efficient) way of doing this without going back and forth all the time? An example of a structure I might want to hash is: ``` a -> b1 -> c -> 1 -> d a -> b2 -> c -> 2 -> d a -> c -> 1 -> d ```
If you have access to your hierarchy components as a tuple, just hash it - tuples are hashable. You may not gain a lot over conversion to and from a delimited string, but it's a start. If this doesn't help, perhaps you could provide more information about how you store the hierarchy/path information.
How do you want to access your hierarchy? If you're always going to be checking for a full path, then as suggested, use a tuple: eg: ``` >>> d["a","b1","c",1,"d"] = value ``` However, if you're going to be doing things like "quickly find all the items below "a -> b1", it may make more sense to store it as a nested hashtable (otherwise you must iterate through all items to find those you're intereted in). For this, a defaultdict is probably the easiest way to store. For example: ``` from collections import defaultdict def new_dict(): return defaultdict(new_dict) d = defaultdict(new_dict) d["a"]["b1"]["c"][1]["d"] = "test" d["a"]["b2"]["c"][2]["d"] = "test2" d["a"]["c"][1]["d"] = "test3" print d["a"]["c"][1]["d"] # Prints test3 print d["a"].keys() # Prints ["c", "b1", "b2"] ```
Python Hash Functions
[ "", "python", "hash", "" ]
Lets say you have a class `SomeClass` which has its own implementation of `toString()`, and also has the ability to parse a new instance of itself by reading that same string. Which of these methods do you prefer, or find better to use? You can either define it as another constructor: ``` public SomeClass(String serializedString); ``` or you can define it as a static method, which in turn creates a new instance (by one of the other constructors, does some with it, and returns the new instance: ``` public static SomeClass toObject(String serializedString); ``` Does it even matter? (my hunch is there is no case this matters, but I am trying to make sure)
My own preference is to keep the parsing logic out of the constructor. That way it can call the appropriate constructors (possibly private) as necessary. It doesn't have to depend on default object construction and so on. So I would go with the toSomeClass() method. Also, it is not immediately clear that SomeClass(String) will parse an object based on the serialization string. There may be many other meanings to a constructor which takes a String. The toSomeClass() static method makes this clear.
I agree with Avi's recommendation. I'd like to add two more advantages: * A static factory method allows you to return null, which a constructor can't. * A static factory method allows you to return a subclass of its defined return type, which can help provide forward compatibility. One exception: if you're writing a simple value type and using the immutable pattern, I see no reason to use a static factory method.
Object construction from serialization - which is preferred?
[ "", "java", "parsing", "oop", "" ]
I have an ebook in word that I convert to PDF before distributing to my clients. I'd like to dynamically insert their email address into all links in the ebook to allow them access to the members-only content on my site, and I'd like to do this on the fly, as part of the book download process. I've briefly looked at <http://us.php.net/pdf> and FPDF, but I was wondering what specific technique I'd use to insert this data. I was thinking I'd insert an email token string where I want the email address to go, and then use some function to update those tokens in the PDF document. Can anyone point me in the right direction? I have php experience, but not with editing / generating pdf documents from php. EDIT: Yes, this commercial script <http://www.setasign.de/products/pdf-php-solutions/setapdf-linkreplacer/> does exactly what I needed.
So far it's looking like this is my best bet: <http://www.setasign.de/products/pdf-php-solutions/setapdf-linkreplacer/> Trying an eval copy of it, will update post with results.
you can do this with FPDI extension for FPDF <http://www.setasign.de/products/pdf-php-solutions/fpdi/> it enables fpdf to import existing pdf files, though I'm not sure how can one replace links. I'd say your best shot would be to generate the whole thing in php, or just save it in html, replace links in html, then convert html to pdf.
Dynamically insert content into pdf files with php
[ "", "php", "pdf", "" ]
I am trying to convert from a Java keystore file into a PEM file using `keytool` and `openssl` applications. However, I could not find an ideal way to do the conversion. Any thoughts? Instead of converting the keystore directly into `PEM`, I tried to create a `PKCS12` file first and then convert it into a relevant PEM file and Keystore. However, I could not establish a connection using them. (Note that I need a PEM file and a Keystore file to implement a secured connection. There is no restriction like "Start from a java keystore file". So starting from other formats is acceptable in my case) But a direct conversion method from `jks` to `pem` is preferable.
## It's pretty straightforward, using jdk6 at least... ``` bash$ keytool -keystore foo.jks -genkeypair -alias foo \ -dname 'CN=foo.example.com,L=Melbourne,ST=Victoria,C=AU' Enter keystore password: Re-enter new password: Enter key password for (RETURN if same as keystore password): bash$ keytool -keystore foo.jks -exportcert -alias foo | \ openssl x509 -inform der -text Enter keystore password: asdasd Certificate: Data: Version: 3 (0x2) Serial Number: 1237334757 (0x49c03ae5) Signature Algorithm: dsaWithSHA1 Issuer: C=AU, ST=Victoria, L=Melbourne, CN=foo.example.com Validity Not Before: Mar 18 00:05:57 2009 GMT Not After : Jun 16 00:05:57 2009 GMT Subject: C=AU, ST=Victoria, L=Melbourne, CN=foo.example.com Subject Public Key Info: Public Key Algorithm: dsaEncryption DSA Public Key: pub: 00:e2:66:5c:e0:2e:da:e0:6b:a6:aa:97:64:59:14: 7e:a6:2e:5a:45:f9:2f:b5:2d:f4:34:27:e6:53:c7: bash$ keytool -importkeystore -srckeystore foo.jks \ -destkeystore foo.p12 \ -srcstoretype jks \ -deststoretype pkcs12 Enter destination keystore password: Re-enter new password: Enter source keystore password: Entry for alias foo successfully imported. Import command completed: 1 entries successfully imported, 0 entries failed or cancelled bash$ openssl pkcs12 -in foo.p12 -out foo.pem Enter Import Password: MAC verified OK Enter PEM pass phrase: Verifying - Enter PEM pass phrase: bash$ openssl x509 -text -in foo.pem Certificate: Data: Version: 3 (0x2) Serial Number: 1237334757 (0x49c03ae5) Signature Algorithm: dsaWithSHA1 Issuer: C=AU, ST=Victoria, L=Melbourne, CN=foo.example.com Validity Not Before: Mar 18 00:05:57 2009 GMT Not After : Jun 16 00:05:57 2009 GMT Subject: C=AU, ST=Victoria, L=Melbourne, CN=foo.example.com Subject Public Key Info: Public Key Algorithm: dsaEncryption DSA Public Key: pub: 00:e2:66:5c:e0:2e:da:e0:6b:a6:aa:97:64:59:14: 7e:a6:2e:5a:45:f9:2f:b5:2d:f4:34:27:e6:53:c7: bash$ openssl dsa -text -in foo.pem read DSA key Enter PEM pass phrase: Private-Key: (1024 bit) priv: 00:8f:b1:af:55:63:92:7c:d2:0f:e6:f3:a2:f5:ff: 1a:7a:fe:8c:39:dd pub: 00:e2:66:5c:e0:2e:da:e0:6b:a6:aa:97:64:59:14: 7e:a6:2e:5a:45:f9:2f:b5:2d:f4:34:27:e6:53:c7: ``` You end up with: * foo.jks - keystore in java format. * foo.p12 - keystore in PKCS#12 format. * foo.pem - all keys and certs from keystore, in PEM format. (This last file can be split up into keys and certificates if you like.) --- ### Command summary - to create JKS keystore: ``` keytool -keystore foo.jks -genkeypair -alias foo \ -dname 'CN=foo.example.com,L=Melbourne,ST=Victoria,C=AU' ``` ### Command summary - to convert JKS keystore into PKCS#12 keystore, then into PEM file: ``` keytool -importkeystore -srckeystore foo.jks \ -destkeystore foo.p12 \ -srcstoretype jks \ -deststoretype pkcs12 openssl pkcs12 -in foo.p12 -out foo.pem ``` if you have more than one certificate in your JKS keystore, and you want to only export the certificate and key associated with one of the aliases, you can use the following variation: ``` keytool -importkeystore -srckeystore foo.jks \ -destkeystore foo.p12 \ -srcalias foo \ -srcstoretype jks \ -deststoretype pkcs12 openssl pkcs12 -in foo.p12 -out foo.pem ``` ### Command summary - to compare JKS keystore to PEM file: ``` keytool -keystore foo.jks -exportcert -alias foo | \ openssl x509 -inform der -text openssl x509 -text -in foo.pem openssl dsa -text -in foo.pem ```
I kept getting errors from `openssl` when using StoBor's command: ``` MAC verified OK Error outputting keys and certificates 139940235364168:error:06065064:digital envelope routines:EVP_DecryptFinal_ex:bad decrypt:evp_enc.c:535: 139940235364168:error:23077074:PKCS12 routines:PKCS12_pbe_crypt:pkcs12 cipherfinal error:p12_decr.c:97: 139940235364168:error:2306A075:PKCS12 routines:PKCS12_item_decrypt_d2i:pkcs12 pbe crypt error:p12_decr.c:123: ``` For some reason, only this style of command would work for my JKS file ``` keytool -importkeystore -srckeystore foo.jks \ -destkeystore foo.p12 \ -srcstoretype jks \ -srcalias mykey \ -deststoretype pkcs12 \ -destkeypass DUMMY123 ``` The key was setting `destkeypass`, the value of the argument did not matter.
Converting a Java Keystore into PEM Format
[ "", "java", "encryption", "https", "openssl", "ssl-certificate", "" ]
Lets say I have a table containing several hundred million rows that looks something like this: ``` memID | foo | bar | foobar 1 | blah | blah | blah 1 | blah | blah | blah 1 | blah | blah | blah 1 | blah | blah | blah 1 | blah | blah | blah 1 | blah | blah | blah 1 | blah | blah | blah 2 | blah | blah | blah 2 | blah | blah | blah 2 | blah | blah | blah 2 | blah | blah | blah 2 | blah | blah | blah . . . 10001 | blah | blah | blah 10001 | blah | blah | blah ``` I need a query that will return the top N rows for each memID in a range of member IDs. For example, if N = 3 and the range is 0-2 it should return ``` memID | foo | bar | foobar 1 | blah | blah | blah 1 | blah | blah | blah 1 | blah | blah | blah 2 | blah | blah | blah 2 | blah | blah | blah 2 | blah | blah | blah ``` I've considered a couple approaches, first creating a massive ``` SELECT TOP (3) * FROM table WHERE memID = 0 UNION ALL SELECT TOP (3) * FROM table WHERE memID = 1 . . . ``` query in code. This isn't really a realistic option for probably obvious reasons. The second approach is to create a temporary table and loop over the range of memIDs inserting the TOP 3 for each memID into that temporary table. ``` WHILE @MemID < 10000 AND @MemID > 0 BEGIN INSERT INTO tmp_Table SELECT TOP (3) * FROM table WHERE memID = @MemID SET @MemID = @MemID + 1 END ``` This works, but I'm wondering if there is a more elegant single query solution that I'm missing. Cadaeic gave me an answer that works without tinkering, but thank you to everyone that suggested analytics, it looks like I have some serious reading to do.
``` declare @startID int, @endID int, @rowsEach int select @startID = 0, @endID = 2, @rowsEach = 3 select * from ( select memID, foo, bar, foobar, row_number() over (partition by dense_rank order by dense_rank) [rank_row] from ( select memID, foo, bar, foobar, dense_rank() over (order by memID) [dense_rank] from #test where memID between @startID and @endID ) a ) b where rank_row <= @rowsEach ``` The result: ``` memID foo bar foobar rank_row ----------- ---- ---- ------ -------------------- 1 blah blah blah 1 1 blah blah blah 2 1 blah blah blah 3 2 blah blah blah 1 2 blah blah blah 2 2 blah blah blah 3 ``` And here's the set-up code if you'd like to test locally: ``` create table #test ( memID int not null , foo char(4) not null , bar char(4) not null , foobar char(4) not null ) insert into #test (memID, foo, bar, foobar) select 1, 'blah', 'blah', 'blah' union all select 1, 'blah', 'blah', 'blah' union all select 1, 'blah', 'blah', 'blah' union all select 1, 'blah', 'blah', 'blah' union all select 1, 'blah', 'blah', 'blah' union all select 1, 'blah', 'blah', 'blah' union all select 1, 'blah', 'blah', 'blah' union all select 2, 'blah', 'blah', 'blah' union all select 2, 'blah', 'blah', 'blah' union all select 2, 'blah', 'blah', 'blah' union all select 2, 'blah', 'blah', 'blah' union all select 10001, 'blah', 'blah', 'blah' union all select 10001, 'blah', 'blah', 'blah' union all select 10001, 'blah', 'blah', 'blah' ```
``` SQL> select ename,sal, 2 row_number() 3 over (order by sal desc)rn, 4 rank() 5 over (order by sal desc)rnk, 6 dense_rank() 7 over (order by sal desc)drnk 8 from emp 9 order by sal desc 10 / ENAME SAL RN RNK DRNK ----- ---- -- --- ---- KING 5000 1 1 1 FORD 3000 2 2 2 SCOTT 3000 3 2 2 JONES 2975 4 4 3 BLAKE 2850 5 5 4 CLARK 2450 6 6 5 ```
SQL query to return top N rows per ID across a range of IDs
[ "", "sql", "sql-server", "database", "optimization", "" ]
Sorry if this is a basic question, but how can I take an ItemTemplate that I have for a ListBox, and put it in the resources for the window so that more than one ListBox can use it. Here's some XAML: ``` <Window x:Class="Example"> <Window.Resources> <DataTemplate x:Key="dtExample"> <ListBox.ItemTemplate> // styles go here... </ListBox.ItemTemplate> </DataTemplate> </Window.Resources> <ListBox ItemTemplate="{StaticResource dtExample}"> // items go here... </ListBox> </Window> ``` This is throwing a "Attached property has no setter" design-time error. I've removed portions of code that I didn't think would matter, for sake of brevity. Thanks
just add your itemtemplate to your window's resource and add a key: ``` <Window.Resource> <DataTemplate x:Key="myTemplate"> .... </DataTemplate> </Window.Resources> ``` and then apply it with something like this: ``` <ListBox ItemTemplate="{StaticResource myTemplate}"> ... </ListBox> ```
you provided the following code: ``` <DataTemplate x:Key="dtExample"> <ListBox.ItemTemplate> // styles go here... </ListBox.ItemTemplate> </DataTemplate> ``` but this will not work. you **cannot** provide `<ListBox.ItemTemplate>` directly within your template. you don't need this here. just create a simple datatemplate and it should work.
How do I embed the ItemTemplate for a wpf ListBox into the Window's resources?
[ "", "c#", "wpf", "xaml", "itemtemplate", "" ]
I have this login page managed in php. It contains several checkboxes, radiobuttons and a dropdownlist. There's a lot of formchecking behind it and if something doesn't check out, the page reloads and all values are filled back into their place, except for passwords. This means the `<select>`, `<input type="radio"` and `<input type="checkbox"` elements that have been selected are re-selected. Yet when I look at the source code, the `checked="checked"` and `selected="selected"` pieces are missing. But seeing as how the reloaded page has them selected, they must have been implemented. Yet when I click my `<input type="reset"` button, nothing happens. The don't get de-selected. Fun thing is, when I select some other checkboxes, radiobuttons and change the select, the reset does work, but only on the newly clicked checkboxes and radiobuttons. Even more weird is the fact that when I click reset, the radiobuttons, checkboxes and selects don't clear themselves, they jump back to the one that was checked or selected when PHP forced the page to reload. What's going on here? Using Firefox and IE. Working with XHTML 1.1
If you're using "View Source" and the script is setting aggressive `no-cache` headers, it's possible that you're not seeing the source code of what's being displayed. Try it in something that shows the live DOM, like Firebug or the DOM Inspector.
If your code after the PHP reload is missing the checked="checked" and selected="selected" attributes, then really the only explanation for them appearing selected is that your browser remembered their values and restored them. That would probably also explain the rest of the behavior. I would suggest making sure the PHP code generates the checked/selected attributes correctly and the rest should take care of itself.
Why aren't checkboxes/radiobuttons and options resetable if they were set by PHP?
[ "", "php", "xhtml", "" ]
What are the good email address validation libraries for Java? Are there any alternatives to [commons validator](http://commons.apache.org/proper/commons-validator/apidocs/org/apache/commons/validator/routines/EmailValidator.html)?
Apache Commons is generally known as a solid project. Keep in mind, though, you'll still have to send a verification email to the address if you want to ensure it's a real email, and that the owner wants it used on your site. > **EDIT**: There was a [bug](https://issues.apache.org/jira/browse/VALIDATOR-324) where it was too restrictive on domain, causing it to not accept valid emails from new TLDs. > > This bug was resolved on 03/Jan/15 02:48 in **commons-validator** version 1.4.1
Using the [official java email package](https://java.net/projects/javamail) is the easiest: ``` public static boolean isValidEmailAddress(String email) { boolean result = true; try { InternetAddress emailAddr = new InternetAddress(email); emailAddr.validate(); } catch (AddressException ex) { result = false; } return result; } ```
What is the best Java email address validation method?
[ "", "validation", "email", "apache-commons", "java", "" ]
**Background** I have a container class which uses vector<std::string> internally. I have provided a method *AddChar(std::string)* to this wrapper class which does a *push\_back()* to the internal vector. In my code, I have to add multiple items to the container some time. For that I have to use ``` container.AddChar("First"); container.AddChar("Second"); ``` This makes the code larger. So to make it more easier, I plan to overload operator <<. So that I can write ``` container << "First" << "Second" ``` and two items will get added to underlying vector. Here is the code I used for that ``` class ExtendedVector { private: vector<string> container; public: friend ExtendedVector& operator<<(ExtendedVector& cont,const std::string str){ cont.AddChar(str); return cont; } void AddChar(const std::string str) { container.push_back(str); } string ToString() { string output; vector<string>::iterator it = container.begin(); while(it != container.end()) { output += *it; ++it; } return output; } }; ``` It is working as expected. **Questions** 1. Is operator overload written correctly? 2. Is it a good practice to overload operators in situations like this? 3. Will there be any performance issues or any other issues with this code? Any thoughts? **Edit** After hearing the excellent comments, I decided not to overload << as it doesn't make sense here. I removed the operator overload code and here is the final code. ``` class ExtendedVector { private: vector<string> container; public: ExtendedVector& AddChar(const std::string str) { container.push_back(str); return *this; } .. other methods } ``` This allows me to add ``` container.AddChar("First").AddChar("Second") ``` In C#, I can do this more easily by using the params keyword. Code will be like ``` void AddChar(params string[] str) { foreach(string s in str) // add to the underlying collection } ``` I know in C++, we can use *...* to specify variable langth of parameters. But AFAIK, it is not type safe. So is it a recommended practice to do so? So that I can write ``` container.AddChar("First","Second") ``` Thanks for the replies.
> Is operator overload written correctly? It is, but one can do better. Like someone else mentioned, your function can be defined entirely out of existing, public functions. Why not make it use only those? Right now, it is a friend, which means it belongs to the implementation details. The same is true if you put operator<< as a member into your class. However, make your operator<< a *non-member*, *non-friend* function. ``` class ExtendedVector { ... }; // note, now it is *entirely decoupled* from any private members! ExtendedVector& operator<<(ExtendedVector& cont, const std::string& str){ cont.AddChar(str); return cont; } ``` If you change your class, you will not be sure that that your operator<< will still work. But if your operator<< entirely depends only on public functions, then you can be sure that it will work after changes were made to implementation details of your class only. Yay! > Is it a good practice to overload operators in situations like this? As another guy said again, this is arguable. In many situations, operator overloading will look "neat" at first sight, but will look like hell next year, because you have no clue anymore what you had in mind when giving some symbols special love. In the case of operator<<, i think this is an OK use. Its use as an insertion operator for streams is well known. And i know of Qt and KDE applications that use it extensively in cases like ``` QStringList items; items << "item1" << "item2"; ``` A similar case is `boost.format` which also reuses `operator%` for passing arguments for placeholders in its string: ``` format("hello %1%, i'm %2% y'old") % "benny" % 21 ``` It's of course also arguable to use it there. But its use for printf format specifies are well known and so its use is OK there too, imho. But as always, style is also subjective so take it with a grain of salt :) > How can i accept variable length arguments in a typesafe way? Well, there is the way of accepting a vector if you are looking for homogeneous arguments: ``` void AddChars(std::vector<std::string> const& v) { std::vector<std::string>::const_iterator cit = v.begin(); for(;cit != v.begin(); ++cit) { AddChar(*cit); } } ``` It's not really confortable to pass it though. You have to construct your vector manually and then pass... I see you already have the right feeling about the vararg style functions. One should not use them for this kind of code and only when interfacing with C code or debugging functions if at all. Another way to handle this case is to apply preprocessor programming. This is an advanced topic and is quite hacky. The idea is to automatically generate overloads up to some upper limit roughly like this: ``` #define GEN_OVERLOAD(X) \ void AddChars(GEN_ARGS(X, std::string arg)) { \ /* now access arg0 ... arg(X-1) */ \ /* AddChar(arg0); ... AddChar(arg(N-1)); */ \ GEN_PRINT_ARG1(X, AddChar, arg) \ } /* call macro with 0, 1, ..., 9 as argument GEN_PRINT(10, GEN_OVERLOAD) ``` That is pseudo code. You can have a look at the boost preprocessor library [here](http://www.boost.org/doc/libs/1_38_0/libs/preprocessor/doc/index.html). Next C++ version will offer far better possibilities. Initializer lists can be used: ``` void AddChars(initializer_list<std::string> ilist) { // range based for loop for(std::string const& s : ilist) { AddChar(s); } } ... AddChars({"hello", "you", "this is fun"}); ``` It's also possible in next C++ to support arbitrary many (mixed-type) arguments using [variadic templates](http://www.osl.iu.edu/~dgregor/cpp/variadic-templates.html). GCC4.4 will have support for them. GCC 4.3 already partially supports them.
> Is it a good practice to overload > operators in situations like this? I don't think so. It's confusing as hell for someone who doesn't know that you've overloaded the operator. Just stick to descriptive method names and forget about the extra characters you're typing, its just not worth it. Your maintainer (or you yourself in 6 months) will thank you.
Overloading operator << - C++
[ "", "c++", "vector", "operator-overloading", "params-keyword", "" ]
We just spent 300 man-hours fixing a buggy application in the field. It all came down to calling Application.DoEvents (re-entrancy problem). This was not caught in design reviews, code reviews. The code was inserted two years ago with the first version; the application was always "flaky" but recent changes exposed the re-entrancy problems to a greater degree. This incident is the second time in our organization that Application.DoEvents caused failures and multi-man hours of debugging. It was discovered in this case by simply noticing the call, buried way down in a complex event handler for an asynchronous task. What do you suggest to prevent this issue from happening again: * Add checkin gates to source control? * Developer training? * Code Analysis rules (why is this not already a built-in rule?) How to I enforce a coding practice?
Every time the application is built centrally, run this on every assembly: ``` ildasm MyAssembly.exe /TEXT ``` Then search the output for: ``` System.Windows.Forms.Application::DoEvents ``` If it's found, mark the build as failed, as if it was a compile error.
Maintain a Development standards and add this to it.
What is the best way to stop developers from calling System.Windows.Forms.Application.DoEvents()?
[ "", "c#", ".net", "vb.net", "" ]
Technically, any odd number of backslashes, as described in [the documentation](http://docs.python.org/reference/lexical_analysis.html##string-and-bytes-literals). ``` >>> r'\' File "<stdin>", line 1 r'\' ^ SyntaxError: EOL while scanning string literal >>> r'\\' '\\\\' >>> r'\\\' File "<stdin>", line 1 r'\\\' ^ SyntaxError: EOL while scanning string literal ``` It seems like the parser could just treat backslashes in raw strings as regular characters (isn't that what raw strings are all about?), but I'm probably missing something obvious.
The reason is explained in the part of that section which I highlighted in bold: > **String quotes can be escaped with a > backslash,** but the backslash remains > in the string; for example, `r"\""` is a > valid string literal consisting of two > characters: a backslash and a double > quote; `r"\"` is not a valid string > literal (even a raw string cannot end > in an odd number of backslashes). > Specifically, a raw string cannot end > in a single backslash (since the > backslash would escape the following > quote character). Note also that a > single backslash followed by a newline > is interpreted as those two characters > as part of the string, not as a line > continuation. So raw strings are not 100% raw, there is still some rudimentary backslash-processing.
The whole misconception about python's raw strings is that most of people think that backslash (within a raw string) is just a regular character as all others. It is NOT. The key to understand is this python's tutorial sequence: > When an '**r**' or '**R**' prefix is present, a character following a > backslash is included in the string without change, and all > backslashes are left in the string So any character following a backslash **is** part of raw string. Once parser enters a raw string (non Unicode one) and encounters a backslash it knows there are 2 characters (a backslash and a char following it). This way: > **r'abc\d'** comprises **a, b, c, \, d** > > **r'abc\'d'** comprises **a, b, c, \, ', d** > > **r'abc\''** comprises **a, b, c, \, '** and: > **r'abc\'** comprises **a, b, c, \, '** but there is no terminating quote now. Last case shows that according to documentation now a parser cannot find closing quote as the last quote you see above is part of the string i.e. backslash cannot be last here as it will 'devour' string closing char.
Why can't Python's raw string literals end with a single backslash?
[ "", "python", "string", "literals", "rawstring", "" ]
For some caching I'm thinking of doing for an upcoming project, I've been thinking about Java serialization. Namely, should it be used? Now I've previously written custom serialization and deserialization (Externalizable) for various reasons in years past. These days interoperability has become even more of an issue and I can foresee a need to interact with .Net applications so I've thought of using a platform-independant solution. Has anyone had any experience with high-performance use of GPB? How does it compare in terms of speed and efficiency with Java's native serialization? Alternatively, are there any other schemes worth considering?
I haven't compared Protocol Buffers with Java's native serialization in terms of speed, but for interoperability Java's native serialization is a serious no-no. It's also not going to be as efficient in terms of space as Protocol Buffers in most cases. Of course, it's somewhat more flexible in terms of what it can store, and in terms of references etc. Protocol Buffers is very good at what it's intended for, and when it fits your need it's great - but there are obvious restrictions due to interoperability (and other things). I've recently posted a Protocol Buffers benchmarking framework in Java and .NET. The Java version is in the [main Google project](https://github.com/google/protobuf) (in the [benchmarks directory](https://github.com/google/protobuf/tree/master/benchmarks)), the .NET version is in [my C# port project](http://code.google.com/p/protobuf-csharp-port/). If you want to compare PB speed with Java serialization speed you could write similar classes and benchmark them. If you're interested in interop though, I really wouldn't give native Java serialization (or .NET native binary serialization) a second thought. There are other options for interoperable serialization besides Protocol Buffers though - [Thrift](http://developers.facebook.com/thrift/), [JSON](http://www.json.org/) and [YAML](http://www.yaml.org/) spring to mind, and there are doubtless others. EDIT: Okay, with interop not being so important, it's worth trying to list the different qualities you want out of a serialization framework. One thing you should think about is versioning - this is another thing that PB is designed to handle well, both backwards and forwards (so new software can read old data and vice versa) - when you stick to the suggested rules, of course :) Having tried to be cautious about the Java performance vs native serialization, I really wouldn't be surprised to find that PB was faster anyway. If you have the chance, use the server vm - my recent benchmarks showed the server VM to be *over twice as fast* at serializing and deserializing the sample data. I think the PB code suits the server VM's JIT very nicely :) Just as sample performance figures, serializing and deserializing two messages (one 228 bytes, one 84750 bytes) I got these results on my laptop using the server VM: ``` Benchmarking benchmarks.GoogleSize$SizeMessage1 with file google_message1.dat Serialize to byte string: 2581851 iterations in 30.16s; 18.613789MB/s Serialize to byte array: 2583547 iterations in 29.842s; 18.824497MB/s Serialize to memory stream: 2210320 iterations in 30.125s; 15.953759MB/s Deserialize from byte string: 3356517 iterations in 30.088s; 24.256632MB/s Deserialize from byte array: 3356517 iterations in 29.958s; 24.361889MB/s Deserialize from memory stream: 2618821 iterations in 29.821s; 19.094952MB/s Benchmarking benchmarks.GoogleSpeed$SpeedMessage1 with file google_message1.dat Serialize to byte string: 17068518 iterations in 29.978s; 123.802124MB/s Serialize to byte array: 17520066 iterations in 30.043s; 126.802376MB/s Serialize to memory stream: 7736665 iterations in 30.076s; 55.93307MB/s Deserialize from byte string: 16123669 iterations in 30.073s; 116.57947MB/s Deserialize from byte array: 16082453 iterations in 30.109s; 116.14243MB/s Deserialize from memory stream: 7496968 iterations in 30.03s; 54.283176MB/s Benchmarking benchmarks.GoogleSize$SizeMessage2 with file google_message2.dat Serialize to byte string: 6266 iterations in 30.034s; 16.826494MB/s Serialize to byte array: 6246 iterations in 30.027s; 16.776697MB/s Serialize to memory stream: 6042 iterations in 29.916s; 16.288969MB/s Deserialize from byte string: 4675 iterations in 29.819s; 12.644595MB/s Deserialize from byte array: 4694 iterations in 30.093s; 12.580387MB/s Deserialize from memory stream: 4544 iterations in 29.579s; 12.389998MB/s Benchmarking benchmarks.GoogleSpeed$SpeedMessage2 with file google_message2.dat Serialize to byte string: 39562 iterations in 30.055s; 106.16416MB/s Serialize to byte array: 39715 iterations in 30.178s; 106.14035MB/s Serialize to memory stream: 34161 iterations in 30.032s; 91.74085MB/s Deserialize from byte string: 36934 iterations in 29.794s; 99.98019MB/s Deserialize from byte array: 37191 iterations in 29.915s; 100.26867MB/s Deserialize from memory stream: 36237 iterations in 29.846s; 97.92251MB/s ``` The "speed" vs "size" is whether the generated code is optimised for speed or code size. (The serialized data is the same in both cases. The "size" version is provided for the case where you've got a lot of messages defined and don't want to take a lot of memory for the code.) As you can see, for the smaller message it can be *very* fast - over 500 small messages serialized or deserialized *per millisecond*. Even with the 87K message it's taking less than a millisecond per message.
One more data point: this project: <http://code.google.com/p/thrift-protobuf-compare/> gives some idea of expected performance for small objects, including Java serialization on PB. Results vary a lot depending on your platform, but there are some general trends.
High performance serialization: Java vs Google Protocol Buffers vs ...?
[ "", "java", "serialization", "caching", "protocol-buffers", "" ]
I've seen Restrictions.ilike('property', '%value%'), but would like to generate SQL like: lower(property) = 'value'. Any ideas? I used: ``` Restrictions.eq("email", email).ignoreCase() ``` since Expression is deprecated. The SimpleExpression will call toLowerCase() on the value, so it is not necessary to do it beforehand. See: [SimpleExpression source](http://viewvc.jboss.org/cgi-bin/viewvc.cgi/hibernate/core/trunk/core/src/main/java/org/hibernate/criterion/SimpleExpression.java?view=markup)
Be careful of using ilike because it would allow someone to enter things like "test%" and match. I use the following to do a case-insensitive equal in one app: ``` ... Criteria crit=session.createCriteria(Event.class); crit.add(Expression.eq("rsvpCode","test1").ignoreCase()); ... ```
Expression is now deprecated. Use Restrictions instead ... ``` crit(Restrictions.eq("firstName", firstName).ignoreCase()); ```
Case-insensitive equals using Hibernate Criteria
[ "", "java", "hibernate", "" ]
So, I've been working on some playing cards in Java. (Not for any practical purpose really, I just enjoy playing cards and they're good practice) Now, right now, I'm making some Card Structures, decks, hands, piles, etc. They're all essentially the same, so I figure that I'd like to use some inheritance. The problem that I've encountered is that the core of each structure is some type of collection, but they don't all use the same collection type. A deck uses a Stack, since a deck essentially functions as a stack most often. But, a hand uses an ArrayList (If there is something more efficient than an ArrayList to use, that would be good to know as well). So, when trying to write an abstract class, I'd like to avoid using abstract methods (as it defeats the original purpose of making an abstract class, to conserve code). But, all of these methods rely on the core collection, for obvious reasons, but I don't know what type the collection is. This is what I've tried so far: ``` public abstract class CardSet { protected AbstractCollection<Card> elCollection; public CardSet() { super(); } public CardSet(Card[] cards) { super(); for(Card c: cards) elCollection.add(c); } public void add(Card c) { elCollection.add(c); } } public class Pair extends CardSet //Pair is just a dummy class to get inheritance right { ArrayList<Card> elPair; public Pair() { elPair = new ArrayList<Card>(); //elPair is defined, because casting elCollection = elPair; // elCollection to arraylist would be a pain. } public Pair(Card[] cards) { this(); super(cards); } } ``` First off, forgive my variable names. I used to name everything "theVariable", but I decided that using "el" was more interesting. (You've got to amuse yourself somehow, right?) Also, using protected was just for the sake of simplicity. Now, the general idea seems to work, defining a variable in the abstract class, and then defining an alias of it in the child class, but I'm not so sure that it's a great practice. The real problem I'm having is with the constructor. The constructor in Pair that accepts an array of Cards doesn't work, because to add the cards, I would first need to create the collection (in this case, the ArrayList) before the parent constructor tries to add the cards. Is there any way to work around this? Is this even a viable way of handling inheritance?
Just have each implementation pass down the collection type in the constructor: ``` public abstract class CardSet<C extends Collection<Card>> { protected final C elCollection; public CardSet<Collection<Card>> cardSet() { return new CardSet<Collection<Card>>(new ArrayList<Card>()); } public CardSet(C col){ this.elCollection = col; } public CardSet(C col, Card[] cards) { this(col); for(Card c: cards) elCollection.add(c); } public void add(Card c) { elCollection.add(c); } } public class Pair extends CardSet<List<Card>> { public Pair() { super(new ArrayList<Card>()); } public Pair(Card[] cards) { super(new ArrayList<Card>(), cards); } } ``` You may have to play a little bit with the declarations, but that should see you right
I think your biggest problem is that your just creating these classes without any real requirements. Is inheritance really the right choice here? It feels like you're designing the classes to fit a pre-conceived implementation instead of the other way around. Define your interfaces for each class you need based on the real requirements, implement them, and then see if an abstract base class makes sense.
Abstract Inheritance and Generics (with playing cards)
[ "", "java", "generics", "inheritance", "abstract", "" ]
So I have a div whose content is generated at runtime it initially has no height associated with it. When it's generated according to firebug and from what I can alert with js the div still has a height of 0. However, looking at the read-only properties with firebug I can see that it has an offset height of 34. It's this value that I need. Hopefully it's obvious but in case it isn't, this number is variable, it's not always 38. So, I thought that I could just get that by doing this via jquery... ``` $("#parentDiv").attr('offsetHeight'); ``` or this with straight js... ``` document.getElementById("parentDiv").offsetHeight; ``` But all that is returned is 0. Does it have anything to do with the fact that offset height is a read-only property in this instance? How can I get this height? I mean firebug is figuring it out somehow so it seems like I should be able to. **Edit:** Here's a sample of what the div looks like right now... ``` <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML Strict//EN"><META http-equiv="Content-Type" content="text/html; charset=utf-8"> <HTML style="OVERFLOW: hidden; HEIGHT: 100%" xmlns="http://www.w3.org/1999/xhtml"><BODY><FORM id="aspnetForm" name="aspnetForm" action="blah.aspx" method="post"><DIV id="container"> <DIV id="ctl00_BodyContentPlaceHolder_Navigation" style="Z-INDEX: 1; LEFT: 1597px; POSITION: absolute; TOP: 67px"> <DIV class="TransparentBg" id="TransparentDiv" style="MARGIN-TOP: 10px; MARGIN-RIGHT: 10px; HEIGHT: 94px; TEXT-ALIGN: center"> </DIV> <DIV class="Foreground" id="ForegroundId" style="MARGIN-TOP: 10px; MARGIN-RIGHT: 10px; TEXT-ALIGN: center"> <DIV id="ctl00_BodyContentPlaceHolder_Navigation1" style="WIDTH: 52px; COLOR: black; HEIGHT: 52px; BACKGROUND-COLOR: transparent; -moz-user-focus: normal"> <IMG style="FILTER: progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod = scale src='../images/image.gif'); CURSOR: pointer" height="52" hspace="0" src="..." width="52" /> </DIV> <DIV id="ctl00_BodyContentPlaceHolder_UserControl" name="ctl00_BodyContentPlaceHolder_UserControl"> <IMG style="DISPLAY: block; VERTICAL-ALIGN: bottom; CURSOR: pointer" height="17" src="..." width="16" /> <IMG style="VERTICAL-ALIGN: top; CURSOR: pointer" height="17" src="..." width="16" /> </DIV> </DIV> </DIV> </DIV></FORM></BODY></HTML> ``` This code is being generated by a control in a separate library. So here's the actual code creating it in my .aspx page. ``` <blah:blahControl ID="control" runat="server" /> ``` Ok, it's edited slightly but thats a whole lot more HTML than I had before. The div I was referring to as "parentDiv" before is called "ctl00\_BodyContentPlaceHolder\_UserControl" up there. That code includes the div in question, it's sibling, parent, grandparent and children. It's almost a direct copy from firebug. **Update:** I should have mentioned this is being done in IE 7. It seemed to work fine one time in Firefox, but it's returning 0 now. Does this provide any new insights of possible work-arounds or anything? ... You all must think I'm nuts. **Update:** Some styling... ``` .TransparentBg { background-color: white; filter:alpha(opacity=50); -moz-opacity:0.5; -khtml-opacity: 0.5; opacity: 0.5; } .Foreground { position: absolute; top: 0px; } ```
Are you sure it's not a [Heisenbug](http://en.wikipedia.org/wiki/Unusual_software_bug#Heisenbug)? If you are setting the height somewhere programmatically and then trying to read it soon later, there is a chance DOM would not have updated.
Are you sure the element is included in the document tree, and rendered? (ie. not “display: none”, but “visibility: hidden” is OK.) An element that is not actually taking part in the document render process has no dimensions, and will give an offsetWidth/Height of 0. ETA after code sample added: with your exact code, I get offsetHeight on the div of ‘17’. The first image is sized correctly, the second has no size. This is correct as rendered(\*). Any images that fail to load are replaced by their alt text as an inline span. Your image has no alt text, so it is replaced by an empty string. Normally, as an inline element, this cannot be set to any particular size. The exception is the first image, because you've given it ‘display: block’, which makes it amenable to the explicit sizing provided by width/height. In Quirks Mode, you would have got little ‘broken image’ icons sized the same as the images were supposed to be. This does not happen in Standards Mode because it is assumed that you know how to use alt text properly if you're using standards. Either way, the dimensions measurement works fine for me if I replace the "..." URLs with real working addresses. (\*: although you can't actually see it because of the rather weird ‘overflow-hidden’ on html and ‘left: 1597px;’ combo. Well, unless you have a *really* wide monitor!)
Why would jquery return 0 for an offsetHeight when firebug says it's 34?
[ "", "javascript", "jquery", "dom", "" ]
Does anyone know if there's a working port of the Symbian OS C++ Descriptors functionality to other operating systems? I recall there being some code towards that [here](http://discussion.forum.nokia.com/forum/showpost.php?s=ad278476973d3bb6f589b7cb8a0c4026&p=210806&postcount=10), although last time I tested it, it did not compile with G++ due to some missing/undefined types. Thanks in advance, Tyson
There's nothing inherently platform-specific about descriptors and you could trivially port them (i.e. re-compile them) to another platform from the Symbian source once it's open sourced. However, since some of the descriptor functions 'leave' you'd have to pull in the Symbian cleanup stack functionality too. Since these are some of the worst (i.e. most non-standard and widely hated) bits of Symbian C++, I'm curious why you'd want to?
I haven't seen such ports, but you may want to wait for the upcoming Symbian Foundation platform release where most of the OS (including descriptors) is opened up under EPL license.
Symbian OS/C++ Descriptors Port?
[ "", "c++", "symbian", "" ]
I have a class that contains the following two properties: ``` public int Id { get; private set; } public T[] Values { get; private set; } ``` I have made it `IEquatable<T>` and overriden the `object.Equals` like this: ``` public override bool Equals(object obj) { return Equals(obj as SimpleTableRow<T>); } public bool Equals(SimpleTableRow<T> other) { // Check for null if(ReferenceEquals(other, null)) return false; // Check for same reference if(ReferenceEquals(this, other)) return true; // Check for same Id and same Values return Id == other.Id && Values.SequenceEqual(other.Values); } ``` When having override `object.Equals` I must also override `GetHashCode` of course. But what code should I implement? How do I create a hashcode out of a generic array? And how do I combine it with the `Id` integer? ``` public override int GetHashCode() { return // What? } ```
Because of the problems raised in this thread, I'm posting another reply showing what happens if you get it wrong... mainly, that you can't use the array's `GetHashCode()`; the correct behaviour is that no warnings are printed when you run it... switch the comments to fix it: ``` using System; using System.Collections.Generic; using System.Linq; static class Program { static void Main() { // first and second are logically equivalent SimpleTableRow<int> first = new SimpleTableRow<int>(1, 2, 3, 4, 5, 6), second = new SimpleTableRow<int>(1, 2, 3, 4, 5, 6); if (first.Equals(second) && first.GetHashCode() != second.GetHashCode()) { // proven Equals, but GetHashCode() disagrees Console.WriteLine("We have a problem"); } HashSet<SimpleTableRow<int>> set = new HashSet<SimpleTableRow<int>>(); set.Add(first); set.Add(second); // which confuses anything that uses hash algorithms if (set.Count != 1) Console.WriteLine("Yup, very bad indeed"); } } class SimpleTableRow<T> : IEquatable<SimpleTableRow<T>> { public SimpleTableRow(int id, params T[] values) { this.Id = id; this.Values = values; } public int Id { get; private set; } public T[] Values { get; private set; } public override int GetHashCode() // wrong { return Id.GetHashCode() ^ Values.GetHashCode(); } /* public override int GetHashCode() // right { int hash = Id; if (Values != null) { hash = (hash * 17) + Values.Length; foreach (T t in Values) { hash *= 17; if (t != null) hash = hash + t.GetHashCode(); } } return hash; } */ public override bool Equals(object obj) { return Equals(obj as SimpleTableRow<T>); } public bool Equals(SimpleTableRow<T> other) { // Check for null if (ReferenceEquals(other, null)) return false; // Check for same reference if (ReferenceEquals(this, other)) return true; // Check for same Id and same Values return Id == other.Id && Values.SequenceEqual(other.Values); } } ```
FWIW, it's very dangerous to use the contents of the Values in your hash code. You should only do this if you can guarantee that it will never change. However, since it is exposed, I don't think guaranteeing it is possible. The hashcode of an object should never change. Otherwise, it loses its value as a key in a Hashtable or Dictionary. Consider the hard-to-find bug of using an object as a key in a Hashtable, its hashcode changes because of an outside influence and you can no longer find it in the Hashtable!
GetHashCode override of object containing generic array
[ "", "c#", "arrays", "generics", "hashcode", "" ]
OK I have a table that has two columns, userID and courseID. It is used to assign training courses to a user. It looks like this: ``` userid courseid 0 1 0 3 0 6 1 1 1 4 1 5 ``` so user 0 is assigned to courses 1,3,6 and user 1 is assigned to 1, 4 5 anyways I need to take every user that is assigned to 6 and create a new row that has that userid and courseid 11, basically assigning every user who is currently assigned to 6 to also be assigned to 11 for some reason (I did not create this database) both rows are marked as primary keys, and some statements I have tried have thrown an error because of this, what the heck is the deal? oh maybe it is because there are a few users that are already assigned to 11 so it is choking on those maybe? please help
``` Insert Into TableName (userID, courseID) Select userID, 11 From TableName Where courseID=6; ``` Also, I'm a bit confused by your comment that both are primary keys. Both rows can be *part* of the primary key or both can be Unique keys but they cannot both be a primary key. As far as errors go, it is probably because the query tried to insert rows that were duplicates of already existing rows. To eliminate this possibility you could do this: ``` Insert Into TableName (userID, courseID) Select userID, 11 From TableName Where courseID=6 AND (userID not in (Select userID From TableName Where courseID=11)) ``` Depending on your database this could work too: ``` INSERT OR IGNORE INTO TableName (userID, courseID) SELECT userID, 11 FROM TableName WHERE courseID=6; ``` Anyway, there you go.
``` insert into TableName (userId, courseId) select userId, 11 from TableName where courseId = 6 and not exists ( select 1 from TableName nested where nested.userId = TableName.UserId and nested.courseId = 11 ) ``` Selects all users that are assigned to courseId 6 but are not yet assigned to courseId 11 and inserts a new record into the table for them for courseId 11.
Duplicate a row in SQL?
[ "", "sql", "" ]
I have a series of hex bytes. Theoretically, the last 20 bytes are the sha1 hash of the first part: ``` 3F F4 E5 25 98 20 52 70 01 63 00 68 00 75 00 79 00 69 00 00 00 74 28 96 10 09 9D C9 01 00 74 A0 D7 DB 0B 9D C9 01 4D 00 79 00 47 00 72 00 6F 00 75 00 70 00 00 00 2F 00 00 00 BD 0D EA 71 BE 0B 25 75 E7 5C 58 20 31 57 F3 9A EF 69 1B FD ``` If I apply sha1 to them in PHP like this: ``` echo sha1("3FF4E525982052700163006800750079006900000074289610099DC9010074A0D7DB0B9DC9014D007900470072006F007500700000002F000000"); ``` I get back: ``` d68ca0839df6e5ac7069cc548d82f249752f3acb ``` But I'm looking for this value: ``` bd0dea71be0b2575e75c58203157f39aef691bfd (BD 0D EA 71 BE 0B 25 75 E7 5C 58 20 31 57 F3 9A EF 69 1B FD) ``` Is it because I'm treating the hex values as a string? What do I need to do? Edit: Here's the original information I am working from: ``` ticketBytes {byte[0x0000003a]} [0x00000000]: 0x3f [0x00000001]: 0xf4 [0x00000002]: 0xe5 [0x00000003]: 0x25 [0x00000004]: 0x98 [0x00000005]: 0x20 [0x00000006]: 0x52 [0x00000007]: 0x70 [0x00000008]: 0x01 [0x00000009]: 0x63 [0x0000000a]: 0x00 [0x0000000b]: 0x68 [0x0000000c]: 0x00 [0x0000000d]: 0x75 [0x0000000e]: 0x00 [0x0000000f]: 0x79 [0x00000010]: 0x00 [0x00000011]: 0x69 [0x00000012]: 0x00 [0x00000013]: 0x00 [0x00000014]: 0x00 [0x00000015]: 0x74 [0x00000016]: 0x28 [0x00000017]: 0x96 [0x00000018]: 0x10 [0x00000019]: 0x09 [0x0000001a]: 0x9d [0x0000001b]: 0xc9 [0x0000001c]: 0x01 [0x0000001d]: 0x00 [0x0000001e]: 0x74 [0x0000001f]: 0xa0 [0x00000020]: 0xd7 [0x00000021]: 0xdb [0x00000022]: 0x0b [0x00000023]: 0x9d [0x00000024]: 0xc9 [0x00000025]: 0x01 [0x00000026]: 0x4d [0x00000027]: 0x00 [0x00000028]: 0x79 [0x00000029]: 0x00 [0x0000002a]: 0x47 [0x0000002b]: 0x00 [0x0000002c]: 0x72 [0x0000002d]: 0x00 [0x0000002e]: 0x6f [0x0000002f]: 0x00 [0x00000030]: 0x75 [0x00000031]: 0x00 [0x00000032]: 0x70 [0x00000033]: 0x00 [0x00000034]: 0x00 [0x00000035]: 0x00 [0x00000036]: 0x2f [0x00000037]: 0x00 [0x00000038]: 0x00 [0x00000039]: 0x00 hashed {byte[0x00000014]} [0x00000000]: 0xbd [0x00000001]: 0x0d [0x00000002]: 0xea [0x00000003]: 0x71 [0x00000004]: 0xbe [0x00000005]: 0x0b [0x00000006]: 0x25 [0x00000007]: 0x75 [0x00000008]: 0xe7 [0x00000009]: 0x5c [0x0000000a]: 0x58 [0x0000000b]: 0x20 [0x0000000c]: 0x31 [0x0000000d]: 0x57 [0x0000000e]: 0xf3 [0x0000000f]: 0x9a [0x00000010]: 0xef [0x00000011]: 0x69 [0x00000012]: 0x1b [0x00000013]: 0xfd ```
Something is very wrong here. [SHA1 digests are 160 bits](http://www.w3.org/PICS/DSig/SHA1_1_0.html), which is 20 hexadecimal numbers, which is represented by 40 characters. The value you're expecting is 32 characters, which means it's not a SHA1 digest - or something else is missing that I don't yet understand.
Unfortunately this doesn't give you the correct value either, but it might point you in the right direction. Either way it's a much better idea to actually convert the hex code to a binary string before hashing it. Like this: ``` $str = "3F F4 E5 25 98 20 52 70 01 63 00 68 00 75 00 79 00 69 00 00 00 74 28 96 10 09 9D C9 01 00 74 A0 D7 DB 0B 9D C9 01 4D 00 79 00 47 00 72 00 6F 00 75 00 70 00 00 00 2F 00 00 00"; // Create an array where each entry represents a single byte in hex $arr = explode(" ", $str); // Convert the hex to decimal $arr = array_map("hexdec", $arr); // Convert the decimal number into the corresponding ASCII character $arr = array_map("chr", $arr); // Implode the array into a string, and hash the result $result = sha1(implode($arr)); echo $result."\n"; ``` The result is fa3ebc158305d09443b4315d35c0eee5aa72daef, which is what vartecs code produces as well. I think there's some aspect of how the correct reference is calculated that we don't know, because the approach used here and by vartec is definitely the most logical way to do it based on the facts that we do know.
How do I sha1 hash hex values correctly in PHP?
[ "", "php", "hash", "hex", "" ]
I have to caculate the number of business days between a given time period which is simple enough, however taking into account public holidays adds in a dimension of complexity. My solution is not what I would call elegant nor efficient as it retrieves public holidays and puts them in a list, checks to see if a date in the list matches a date within the given time period to be checked by incrementing the date from the start date. ALthough this works fine I'd rather have a more efficient algorithm has anyone got any tips or recommend a different data strucuture to hold the public holidays?
If you've got the public holidays stored in order, in a list, you can just do a binary search to find where in the list the start of your time period falls, and another to find where in the list the end of the time period falls. Then you just need to take the "normal" difference (removing weekends) and subtract the count of items between the results of the binary searches. Be careful of time periods which start or end on a public holiday! ([`List<T>.BinarySearch`](http://msdn.microsoft.com/en-us/library/3f90y839.aspx) method should be fine for you assuming you're using DateTime or some other naturally comparable time structure. Note the return value is negative if the key you're searching for isn't actually in the list (which it won't be most of the time). See the remarks in the docs.)
If you calculate the number of business days between the two dates so ``` TimeSpan t1 = Date1 - Date2; int totalDays = t1.TotalDays; ``` Then using your two dates, count the number of public holidays in your list which fall between and subtract from the total days. I would think this would work, unless there are some public holidays in there which span multiple days and then you would have to adjust your selection logic. Can you paste what you have done so far to get a judge of where you are at and exactly what method you are using pls. :-) Thanks, Andrew
c# code efficency
[ "", "c#", "" ]
Hopefully the last question in choosing an implementation language for this web app, but before pitching to anyone, we would like to know what your experiences are with maintaining an application. We maintained (and since moved to a hosted solution) a web portal based on Perl. The problem was that we had cases where Perl was updated or a module was updated, and since the whole website was interconnected, it easily became a nightmare because one small change in the CPAN modules could cause the whole website to die (this was an open source portal, we didn't create it) because something in the portal was very specific about what version module it would accept. There were a couple times where an innocuous set of security updates could cause the website to come crashing apart for a noticeable period of time. So, in deciding to create a web app based on PHP, Django, or Ruby on Rails, can people share what maintenance on the website has entailed when upgrading all or parts of the framework or language? How "easy" it is to break or glitch the web application when just trying to install a security fix for a module/gem you didn't create? Or isn't it really an issue?
If I were deploying a python app these days, I would certainly check out [virtualenv](http://pypi.python.org/pypi/virtualenv). From their page: > virtualenv is a tool to create > isolated Python environments. > > The basic problem being addressed is > one of dependencies and versions, and > indirectly permissions. Imagine you > have an application that needs version > 1 of LibFoo, but another application > requires version 2. How can you use > both these applications? If you > install everything into > /usr/lib/python2.4/site-packages (or > whatever your platform's standard > location is), it's easy to end up in a > situation where you unintentionally > upgrade an application that shouldn't > be upgraded. > > Or more generally, what if you want to > install an application and leave it > be? If an application works, any > change in its libraries or the > versions of those libraries can break > the application.
With Django, I have never had any issues when upgrading between point revisions (some of my projects have been bitrotting since 0.96 or so, so they were more complex). As far as reusable apps goes, it really depends on the app. By and large, though, developers that are disciplined enough to release their apps (rather than assuming people will run the development version) tend to be good at ensuring migration between versions is painless.
Web framework maintainability
[ "", "php", "ruby-on-rails", "django", "" ]
I'm working with an existing SQL 2005 database that was not implemented with FK relationships between tables. I tried to add the relationships with a database diagram and my application immediately blew up trying to edit or insert any data that is tied to the new FK. ``` dbo.person [person_id | firstname | lastname | dateofbirth] dbo.campaign [campaign_id | campaign_description] dbo.disposition [disposition_id | disposition_description] dbo.person_campaigns [person_campaign_id | person_id | campaign_id | disposition_id] ``` The person\_campaigns table is where a person, campaign, and disposition are tied together. Can you please provide the appropriate SQL syntax for adding the proper FK relationships between these entities? **EDIT** ``` CREATE TABLE [dbo].[person_campaigns]( [person_campaigns_id] [int] IDENTITY(1,1) NOT NULL, [person_id] [int] NOT NULL, [d_campaign_id] [int] NOT NULL, [d_physician_disposition_id] [int] NULL, CONSTRAINT [PK_person_campaigns] PRIMARY KEY CLUSTERED ( [person_campaigns_id] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] ) ON [PRIMARY] GO CREATE TABLE [dbo].[d_campaign]( [d_campaign_id] [int] IDENTITY(1,1) NOT NULL, [name] [varchar](50) NULL, [year] [int] NULL, [isactive] [bit] NOT NULL, CONSTRAINT [PK_d_campaign] PRIMARY KEY CLUSTERED ( [d_campaign_id] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] ) ON [PRIMARY] GO SET ANSI_PADDING OFF GO ALTER TABLE [dbo].[d_campaign] ADD CONSTRAINT [DF_d_campaign_isactive] DEFAULT ((1)) FOR [isactive] GO CREATE TABLE [dbo].[d_disposition]( [d_disposition_id] [int] IDENTITY(1,1) NOT NULL, [name] [varchar](50) NULL, [isactive] [bit] NOT NULL, CONSTRAINT [PK_d_disposition] PRIMARY KEY CLUSTERED ( [d_disposition_id] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] ) ON [PRIMARY] GO SET ANSI_PADDING OFF GO ALTER TABLE [dbo].[d_disposition] ADD CONSTRAINT [DF_d_disposition_isactive] DEFAULT ((1)) FOR [isactive] GO CREATE TABLE [dbo].[person]( [person_id] [int] IDENTITY(1,1) NOT NULL, [firstname] [varchar](30) NULL, [lastname] [varchar](30) NULL, [dateofbirth] [datetime] NULL CONSTRAINT [PK__person__0BC6C43E] PRIMARY KEY CLUSTERED ( [person_id] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] ) ON [PRIMARY] GO ```
the easiest way to do it is through the database diagram editor; do them one at a time and save the diagram to affect the tables after each connection is made. If it "blows up" it is most likely because the tables contain foreign-key values that do not exist; you'll have to clean these up first.
If you have to add them after the table is created the syntax is ``` create table person (person_id int primary key ,firstname varchar(10) , lastname varchar(10) , dateofbirth varchar(10)) create table campaign (campaign_id int primary key , campaign_description varchar(10)) create table disposition (disposition_id int primary key ,disposition_description varchar(10)) create table person_campaigns(person_campaign_id int ,person_id int, campaign_id int ,disposition_id int) go alter table person_campaigns add Constraint fk_person_campaigns_person_id Foreign Key (person_id) References person(person_id) GO alter table person_campaigns add Constraint fk_person_campaigns_campaign_id Foreign Key (campaign_id) References campaign(campaign_id) GO alter table person_campaigns add Constraint fk_person_campaigns_disposition_id Foreign Key (disposition_id) References disposition(disposition_id) GO ```
How do you add Foreign Key Relationships?
[ "", "sql", "sql-server-2005", "foreign-keys", "data-integrity", "" ]
I'm just wondering if all of the following joins are logically equivalent, and if not, why not? ``` SELECT t1.x, t2.y from t1, t2 where t1.a=t2.a and t1.b=t2.b and t1.c = t2.c; SELECT t1.x, t2.y from t1 join t2 on t1.a=t2.a where t1.b=t2.b and t1.c = t2.c; SELECT t1.x, t2.y from t1 join t2 on t1.a=t2.a and t1.b=t2.b where t1.c = t2.c; SELECT t1.x, t2.y from t1 join t2 on t1.a=t2.a and t1.b=t2.b and t1.c = t2.c; ``` I guess my real question is: does combining "where" with "on" doing something different from just having multiple conditions ANDed together with "on"? I work with MySQL, in case that makes a difference.
They are logically equivalent and should produce the same result. However, the last one is to be preferred as it states more correctly the semantics of the query - i.e. "join tables t1 and t2". The WHERE clause should be used for "filtering" results of the join - e.g. ``` ... WHERE t2.some_col > 10 ``` Also, as Constantin has said in another answer, the 4 queries would be different if the join was an OUTER join.
For INNER JOIN it makes no logical difference and optimizer should produce same plans. But for OUTER joins it becomes important whether you put condition in WHERE or FROM ... JOIN clause. This is because FROM and ON clauses are processed before WHERE clause: [ANSI SQL logical query processing http://www.sqlmag.com/Files/09/94378/Figure\_01.jpg](http://www.sqlmag.com/Files/09/94378/Figure_01.jpg)
Are all these SQL joins logically equivalent?
[ "", "sql", "join", "" ]
If I have an `int` array structured like this: ``` private int[][] map = new int[400][400]; ``` And I try to retrieve ``` map[100][200] ``` And that element isn't initialized, will i get a compiler/runtime error or will it return null? And is there any function to check if a given element/index exists/has been set?
As your array declaration is of a primitive type you won't get any compiler or runtime errors - the default value of 0 will be returned. If your array had been an array of Objects, then the array would hold `null` for any element not specifically assigned.
I won't return `null` because `int` is a primitive type. It will return the default `int` value, which is `0`. There is no way of knowing if any element has been set, short of keeping a separate boolean array.
How to check if an element in array exists in Java
[ "", "java", "arrays", "initialization", "" ]
I have a BigDecimal calculation result which I need to round to the nearest specified interval (in this case it's the financial market tick size). e.g. Price [Tick Size] -> Rounded Price ``` 100.1 [0.25] -> 100 100.2 [0.25] -> 100.25 100.1 [0.125] -> 100.125 100.2 [0.125] -> 100.25 ``` Thanks. Update: schnaader's solution, translated into Java/BigDecimal terms: ``` price = price.divide(tick).setScale(0, RoundingMode.HALF_UP).multiply(tick) ```
You could normalize tick size and then use the usual rounding methods: ``` 100.1 [0.25] -> * (1/0.25) -> 400.4 [1] -> round -> 400 -> / (1/0.25) -> 100 100.2 [0.25] -> * (1/0.25) -> 400.8 [1] -> round -> 401 -> / (1/0.25) -> 100.25 ``` So it should be: ``` Price = Round(Price / Tick) * Tick; ``` Also note that you seem to have to set the correct rounding mode for BigDecimals. See [BigDecimal Docs](http://java.sun.com/j2se/1.5.0/docs/api/java/math/BigDecimal.html#ROUND_CEILING) for example. So you should be sure to set this correct and write some tests to check the correctness of your code.
This is more related to **"Rounding a stock price to it's nearest tick size"**. Answer provided by schnaader is correct, however there are a few things missing. * First, you must check whether stock price needs rounding. Unnecessary rounding messes up the fractional part. * Then you also need to handle `ArithmeticException` that might come during `BigDecimal` divide function Here's my solution. It would take a lot of time to explain it. I'd recommend to try it with some samples to get a feel. Look for the function **`roundTick()`**. ``` import static java.math.RoundingMode.HALF_UP; import java.math.BigDecimal; /** * Utility class for stock price related operations. */ public final class PriceFormatter { public static final float DELTA = 0.0001f; private PriceFormatter() { } /** * Rounds the price to the nearest tick size. * * @param price price * @param tickSize tick size * @return price rounded to the nearest tick size */ public static final float roundTick(final float price, final float tickSize) { if (tickSize < DELTA) { return price; } if (!isRoundingNeeded(price, tickSize)) { return price; } final BigDecimal p = new BigDecimal(price); final BigDecimal t = new BigDecimal(tickSize); final BigDecimal roundedPrice = p.divide(t, 0, HALF_UP).multiply(t); return roundedPrice.floatValue(); } /** * Checks whether price needs rounding to the nearest tick size. * * @param price price * @param tickSize tick size * @return true, if rounding is needed; false otherwise */ public static final boolean isRoundingNeeded(final float price, final float tickSize) { final int mult = calculateTickMultiplier(tickSize); final int mod = (int) (tickSize * mult); final float reminder = (((price * mult) % mult) % mod); final boolean needsRounding = reminder > DELTA; return needsRounding; } public static final int calculateTickMultiplier(final float tickSize) { int result = 1; while (((tickSize * result) < 1) || (((tickSize * result) - (int) (tickSize * result)) > DELTA)) { result *= 10; } return result; } } ```
Rounding a Java BigDecimal to the nearest interval
[ "", "java", "rounding", "bigdecimal", "intervals", "" ]
Is there any fast (and nice looking) way to remove an element from an array in Java?
You could use commons lang's ArrayUtils. ``` array = ArrayUtils.removeElement(array, element) ``` [commons.apache.org library:Javadocs](http://commons.apache.org/proper/commons-lang/javadocs/api-2.6/org/apache/commons/lang/ArrayUtils.html)
Your question isn't very clear. From your own answer, I can tell better what you are trying to do: ``` public static String[] removeElements(String[] input, String deleteMe) { List result = new LinkedList(); for(String item : input) if(!deleteMe.equals(item)) result.add(item); return result.toArray(input); } ``` NB: This is untested. Error checking is left as an exercise to the reader (I'd throw `IllegalArgumentException` if either `input` or `deleteMe` is null; an empty list on null list input doesn't make sense. Removing null Strings from the array might make sense, but I'll leave that as an exercise too; currently, it will throw an `NPE` when it tries to call equals on `deleteMe` if `deleteMe` is null.) Choices I made here: I used a `LinkedList`. Iteration should be just as fast, and you avoid any resizes, or allocating too big of a list if you end up deleting lots of elements. You could use an `ArrayList`, and set the initial size to the length of input. It likely wouldn't make much of a difference.
Removing an element from an Array (Java)
[ "", "java", "arrays", "element", "" ]
Consider: ``` // member data omitted for brevity // assume that "setAngle" needs to be implemented separately // in Label and Image, and that Button does need to inherit // Label, rather than, say, contain one (etc) struct Widget { Widget& move(Point newPos) { pos = newPos; return *this; } }; struct Label : Widget { Label& setText(string const& newText) { text = newText; return *this; } Label& setAngle(double newAngle) { angle = newAngle; return *this; } }; struct Button : Label { Button& setAngle(double newAngle) { backgroundImage.setAngle(newAngle); Label::setAngle(newAngle); return *this; } }; int main() { Button btn; // oops: Widget::setText doesn't exist btn.move(Point(0,0)).setText("Hey"); // oops: calling Label::setAngle rather than Button::setAngle btn.setText("Boo").setAngle(.5); } ``` Any techniques to get around these problems? Example: using template magic to make Button::move return Button& or something. **edit** It has become clear that the second problem is solved by making setAngle virtual. **But the first problem remains unsolved in a reasonable fashion!** **edit**: Well, I guess it's impossible to do properly in C++. Thanks for the efforts anyhow.
For the second problem, making setAngle virtual should do the trick. For the first one, there are no easy solutions. Widget::move returns a Widget, which doesn't have a setText method. You could make a pure virtual setText method, but that'd be a pretty ugly solution. You could overload move() on the button class, but that'd be a pain to maintain. Finally, you could probably do something with templates. Perhaps something like this: ``` // Define a move helper function template <typename T> T& move(T& obj, Point& p){ return obj.move(p); }; // And the problematic line in your code would then look like this: move(btn, Point(0,0)).setText("Hey"); ``` I'll let you decide which solution is cleanest. But is there any particular reason why you need to be able to chain these methods?
You can extend [CRTP](http://en.wikipedia.org/wiki/Curiously_Recurring_Template_Pattern) to handle this. monjardin's solution goes in the right direction. All you need now is a default `Label` implementation to use it as a leaf class. ``` #include <iostream> template <typename Q, typename T> struct Default { typedef Q type; }; template <typename T> struct Default<void, T> { typedef T type; }; template <typename T> void show(char const* action) { std::cout << typeid(T).name() << ": " << action << std::endl; } template <typename T> struct Widget { typedef typename Default<T, Widget<void> >::type type; type& move() { show<type>("move"); return static_cast<type&>(*this); } }; template <typename T = void> struct Label : Widget<Label<T> > { typedef typename Default<T, Widget<Label<T> > >::type type; type& set_text() { show<type>("set_text"); return static_cast<type&>(*this); } }; template <typename T = void> struct Button : Label<Button<T> > { typedef typename Default<T, Label<Button<T> > >::type type; type& push() { show<type>("push"); return static_cast<type&>(*this); } }; int main() { Label<> lbl; Button<> btt; lbl.move().set_text(); btt.move().set_text().push(); } ``` That said, consider whether such an effort is worth the small added syntax bonus. Consider alternative solutions.
Method chaining + inheritance don't play well together?
[ "", "c++", "inheritance", "method-chaining", "" ]
I have two fields that are of the same type in my property-grid. However, one is read-only, the other is editable. Both of these fields are of a custom type, and thus have a custom UITypeEditor, which puts the elipsis ([...]) button on the field. ``` [ CategoryAttribute("5 - Wind"), DisplayName("Factored Area"), Description("The factored area for the segment."), EditorAttribute(typeof(umConversionTypeEditor), typeof(UITypeEditor)), TypeConverter(typeof(umConversionTypeConverter)), ReadOnly(true) ] public FactoredAreaClass FactoredArea { ... } [ CategoryAttribute("5 - Wind"), DisplayName("Factored Area Modifier"), Description("The factored area modifier."), EditorAttribute(typeof(umConversionTypeEditor), typeof(UITypeEditor)), TypeConverter(typeof(umConversionTypeConverter)) ] public FactoredAreaClass FactoredAreaMod { ... } ``` In this example, FactoredAreaMod is available to be edited, but BOTH have the elipsis, which will cause great confusion with the users. Any way to turn that off??
Use the [ReadOnly](http://msdn.microsoft.com/en-us/library/system.componentmodel.readonlyattribute.aspx) attribute. This marks it as design-time read-only while keeping it read/write for runtime use. Also, you should either apply the [Editor](http://msdn.microsoft.com/en-us/library/system.componentmodel.editorattribute.aspx) attribute to the type rather than the properties. There's no gain in applying it to a property if you don't want that property to be editable.
Thanks to Jeff Yates, I came up with an alternate solution. Here's how I solved it... The biggest issue was that the EditorAttribute was actually assigned in the FactoredAreaClass. I put it in the raw example just to show that there was an editor attribute assigned. ``` [ CategoryAttribute("5 - Wind"), DisplayName("Factored Area"), Description("The factored area for the segment."), EditorAttribute(typeof(UITypeEditor), typeof(UITypeEditor)), // RESET THE UITYPEEDITOR to "nothing" ReadOnly(true) ] public FactoredAreaClass FactoredArea { ... } [ CategoryAttribute("5 - Wind"), DisplayName("Factored Area Modifier"), Description("The factored area modifier."), // the EditorAttribute and TypeConverter are part of FactoredAreaClass ] public FactoredAreaClass FactoredAreaMod { ... } ```
How do I remove the elipsis for a custom UITypeEditor that is read-only?
[ "", "c#", "winforms", "propertygrid", "" ]
I want to package my project in a single executable JAR for distribution. How can I make a Maven project package all dependency JARs into my output JAR?
``` <build> <plugins> <plugin> <artifactId>maven-assembly-plugin</artifactId> <configuration> <archive> <manifest> <mainClass>fully.qualified.MainClass</mainClass> </manifest> </archive> <descriptorRefs> <descriptorRef>jar-with-dependencies</descriptorRef> </descriptorRefs> </configuration> </plugin> </plugins> </build> ``` and you run it with ``` mvn clean compile assembly:single ``` *Compile goal should be added before assembly:single or otherwise the code on your own project is not included.* See more details in comments. --- Commonly this goal is tied to a build phase to execute automatically. This ensures the JAR is built when executing `mvn install` or performing a deployment/release. ``` <build> <plugins> <plugin> <artifactId>maven-assembly-plugin</artifactId> <configuration> <archive> <manifest> <mainClass>fully.qualified.MainClass</mainClass> </manifest> </archive> <descriptorRefs> <descriptorRef>jar-with-dependencies</descriptorRef> </descriptorRefs> </configuration> <executions> <execution> <id>make-assembly</id> <!-- this is used for inheritance merges --> <phase>package</phase> <!-- bind to the packaging phase --> <goals> <goal>single</goal> </goals> </execution> </executions> </plugin> </plugins> </build> ```
You can use the dependency-plugin to generate all dependencies in a separate directory before the package phase and then include that in the classpath of the manifest: ``` <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-dependency-plugin</artifactId> <executions> <execution> <id>copy-dependencies</id> <phase>prepare-package</phase> <goals> <goal>copy-dependencies</goal> </goals> <configuration> <outputDirectory>${project.build.directory}/lib</outputDirectory> <overWriteReleases>false</overWriteReleases> <overWriteSnapshots>false</overWriteSnapshots> <overWriteIfNewer>true</overWriteIfNewer> </configuration> </execution> </executions> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-jar-plugin</artifactId> <configuration> <archive> <manifest> <addClasspath>true</addClasspath> <classpathPrefix>lib/</classpathPrefix> <mainClass>theMainClass</mainClass> </manifest> </archive> </configuration> </plugin> ``` Alternatively, use `${project.build.directory}/classes/lib` as OutputDirectory to integrate all JAR files into the main JAR file, but then you will need to add custom classloading code to load the JAR files.
How can I create an executable/runnable JAR with dependencies using Maven?
[ "", "java", "build", "maven-2", "executable-jar", "build-automation", "" ]
Suppose you have a table widget class. Do you do `table.row(i).column(0).setText(students[i].surname())` or `table[0][i] = students[i].surname()` the latter makes way less sense but the simplicity is so luring ;) ditto for: `table.row(0).column(0).setBackground(red)` vs: `table[0][0].setBackground(red)` Note that `Table::row` returns a `Table::Row`, whose `column` function returns a Table::Cell, and Table::Cell provides either `setText` or `op=` (as well as setBackground). Same for `Table::op[]` and `Table::Row::op[]`. Your thoughts?
The solution with `Table::row()` and `Table::Row::column()` methods is a bit more readable (in general) and allows you to unambiguously create a `Table::column()` method, `Table::Column` (proxy) class, and `Table::Column::row()` method later on, if that is ever needed. This solution also makes it easy to find all places where rows/columns are accessed, which is much harder when you use operator overloading. As others pointed out however, the second solution is less typing and, in my opinion, not much worse in readability. (May even be more readable in certain situations.) It's up to you to decide though, I'm just giving some implications of both solutions :-)
As a less verbose alternative for many common cases, I would also provide something like this: ``` table.rowcol(i, j) = "blah"; // rowcol returns directly a cell table.colrow(k, t).SetBackground(black); ``` Basically the name of the method just serves as a reminder on the order of the parameters. Also, being a single method, you can perform better exception handling IMO.
Table api
[ "", "c++", "api", "" ]
I would like to catch and log MySQL warnings in Python. For example, MySQL issues a warning to standard error if you submit `'DROP DATABASE IF EXISTS database_of_armaments'` when no such database exists. I would like to catch this and log it, but even in the try/else syntax the warning message still appears. The try/except syntax does catch MySQL errors (eg, submission of a typo like `'DRP DATABASE database_of_armaments'`). I have experimented with `<<except.MySQLdb.Warning>>` -- no luck. I've looked at the warnings module, but don't understand how to incorporate it into the try/else syntax. To be concrete, how do I get the following (or something like it) to work. GIVEN: database 'database\_of\_armaments' does not exist. ``` try: cursor.execute('DROP DATABASE IF EXISTS database_of_armaments') except: <<WHAT DO I PUT HERE?>> print 'There was a MySQL warning.' <<AND what goes here if I want to get and manipulate information about the warning?>> ``` UPDATE: Thanks for the comments. I had tried these and they didn't work -- but I had been using a DatabaseConnection class that I wrote for a connection, and its runQuery() method to execute. When I created a connection and cursor outside the class, the try/except Exception caught the "Programming Error", and except MySQLdb.ProgrammingError worked as advertised. So now I have to figure out what is wrong with my class coding. Thank you for your help.
Follow these steps. 1. Run it with `except Exception, e: print repr(e)`. 2. See what exception you get. 3. Change the `Exception` to the exception you actually got. Also, remember that the exception, e, is an object. You can print `dir(e)`, `e.__class__.__name__`, etc.to see what attributes it has. Also, you can do this interactively at the `>>>` prompt in Python. You can then manipulate the object directly -- no guessing.
Have you tried something like this? ``` try: cursor.execute(some_statement) except MySQLdb.IntegrityError, e: # handle a specific error condition except MySQLdb.Error, e: # handle a generic error condition except MySQLdb.Warning, e: # handle warnings, if the cursor you're using raises them ```
Trapping MySQL Warnings In Python
[ "", "python", "mysql", "" ]
I have used C# expressions before based on lamdas, but I have no experience composing them by hand. Given an `Expression<Func<SomeType, bool>> originalPredicate`, I want to create an `Expression<Func<OtherType, bool>> translatedPredicate`. In this case SomeType and OtherType have the same fields, but they are not related (no inheritance and not based on a common interface). Background: I have a repository implementation based on LINQ to SQL. I project the LINQ to SQL entities to my Model entities, to keep my model in POCO. I want to pass expressions to the repository (as a form of specifications) but they should be based on the model entities. But I can't pass those expressions to the data context, since it expects expressions based on the LINQ to SQL entities.
With `Expression`, the simplest way is with a conversion **expression**: ``` class Foo { public int Value { get; set; } } class Bar { public int Value { get; set; } } static class Program { static void Main() { Expression<Func<Foo, bool>> predicate = x => x.Value % 2 == 0; Expression<Func<Bar, Foo>> convert = bar => new Foo { Value = bar.Value }; var param = Expression.Parameter(typeof(Bar), "bar"); var body = Expression.Invoke(predicate, Expression.Invoke(convert, param)); var lambda = Expression.Lambda<Func<Bar, bool>>(body, param); // test with LINQ-to-Objects for simplicity var func = lambda.Compile(); bool withOdd = func(new Bar { Value = 7 }), withEven = func(new Bar { Value = 12 }); } } ``` Note however that this will be supported differently by different providers. EF might not like it, for example, even if LINQ-to-SQL does. The other option is to rebuild the expression tree **completely**, using reflection to find the corresponding members. Much more complex.
There is one other way I have found, that also includes wrapping your original delegate. ``` Func<T, object> ExpressionConversion<U>(Expression<Func<T, U>> expression) { Expression<Func<T, object>> g = obj => expression.Compile().Invoke(obj); return g.Compile(); } ```
C# How to convert an Expression<Func<SomeType>> to an Expression<Func<OtherType>>
[ "", "c#", "linq-to-sql", "lambda", "repository-pattern", "expression-trees", "" ]
What would you suggest the best tool to profile C/C++ code and determine which parts are taking the most time. Currently, I'm just relying on logs but ofcourse the information is not accurate since unnecessary delays are introduced. Preferrably, the tool would also be able to detect/suggest areas which could be optimized, if such tool exist. Platform: Linux The application shall be used on an embedded environment so it should be lightweight and external (not a plugin on some IDE).
I can heartily recommend [`callgrind`](http://valgrind.org/info/tools.html#callgrind) in combination with [KCachegrind](http://kcachegrind.sourceforge.net/html/Home.html).
"gprof" on linux/freebsd is a quite simple and efficient tool to identify which routines are hogging the cPU at runtime. It gives both nested and flat profile of functions. It gives you the percentage of CPU time taken by each function executed during the runtime of the profiler, and also the percentage taken within the function itself, and the percentage taken by its child functions. That helps you easily segregate the offending functions.
Profiling programs written in C or C++
[ "", "c++", "c", "profile", "" ]
How can I hook into a browser window resize event? There's [a jQuery way of listening for resize events](https://stackoverflow.com/questions/599288/cross-browser-window-resize-event-javascript-jquery) but I would prefer not to bring it into my project for just this one requirement.
Best practice is to add to the resize event, rather than replace it: ``` window.addEventListener('resize', function(event) { ... }, true); ``` An alternative is to make a single handler for the DOM event (but can only have one), eg. ``` window.onresize = function(event) { ... }; ``` jQuery *may* do some work to ensure that the resize event gets fired consistently in all browsers, but I'm not sure if any of the browsers differ, but I'd encourage you to test in Firefox, Safari, and IE.
First off, I know the `addEventListener` method has been mentioned in the comments above, but I didn't see any code. Since it's the preferred approach, here it is: ``` window.addEventListener('resize', function(event){ // do stuff here }); ``` [Here's a working sample](http://codepen.io/jondlm/pen/doijJ).
JavaScript window resize event
[ "", "javascript", "window-resize", "" ]
I'm trying to POST data to an external url using HttpWebRequest, then i need to redirect the user to the external url where which i just POSTed my data, can this be achieved on the first place ?
Unless there is something that needs to be done on the server side you should probably do this from JS on the client side. Just submit a form programtically using JS that will take care of both the posting and the redirect.
Well, the redirect should be fairly standard - just a regular ASP.NET [redirect](http://msdn.microsoft.com/en-us/library/system.web.httpresponse.redirect.aspx). Re doing a POST; that is fine - but it would be even easier to just use `WebClient`: ``` using (WebClient client = new WebClient()) { client.UploadData(address, "POST", data); } ``` (other methods and overloads for different use-cases)
redirecting to POST HttpWebRequest
[ "", "c#", ".net", "asp.net", "httpwebrequest", "" ]
I have a server that's written in C, and I want to write a client in python. The python client will send a string "send some\_file" when it wants to send a file, followed by the file's contents, and the string "end some\_file". Here is my client code : ``` file = sys.argv[1] host = sys.argv[2] port = int(sys.argv[3]) sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM) sock.connect((host,port)) send_str = "send %s" % file end_str = "end %s" % file sock.send(send_str) sock.send("\n") sock.send(open(file).read()) sock.send("\n") sock.send(end_str) sock.send("\n") ``` The problem is this : * the server receives the "send some\_file" string from a recv * at the second recv, the file's content and the "end file" strings are sent together In the server code, the buffer's size is 4096. I first noticed this bug when trying to send a file that's less than 4096k. How can I make sure that the server receives the strings independently?
With socket programming, even if you do 2 independent sends, it doesn't mean that the other side will receive them as 2 independent recvs. One simple solution that works for both strings and binary data is to: First send the number of bytes in the message, then send the message. Here is what you should do for each message whether it is a file or a string: **Sender side:** * Send 4 bytes that holds the number of bytes in the following send * Send the actual data **Receiver side:** * From the receiver side do a loop that blocks on a read for 4 bytes * Then do a block on a read for the number of characters specified in the preceding 4 bytes to get the data. Along with the 4-byte length header I mentioned above, you could also add a constant size command type header (integer again) that describes what's in the following recv. You could also consider using a protocol like HTTP which already does a lot of the work for you and has nice wrapper libraries.
There are two much simpler ways I can think of in which you can solve this. Both involve some changes in the behaviors of both the client and the server. The first is to use padding. Let's say you're sending a file. What you would do is read the file, encode this into a simpler format like Base64, then send enough space characters to fill up the rest of the 4096-byte 'chunk'. What you would do is something like this: ``` from cStringIO import StringIO import base64 import socket import sys CHUNK_SIZE = 4096 # bytes # Extract the socket data from the file arguments filename = sys.argv[1] host = sys.argv[2] port = int(sys.argv[3]) # Make the socket sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM) sock.connect((host,port)) # Prepare the message to send send_str = "send %s" % (filename,) end_str = "end %s" % (filename,) data = open(filename).read() encoded_data = base64.b64encode(data) encoded_fp = StringIO(encoded_data) sock.send(send_str + '\n') chunk = encoded_fp.read(CHUNK_SIZE) while chunk: sock.send(chunk) if len(chunk) < CHUNK_SIZE: sock.send(' ' * (CHUNK_SIZE - len(chunk))) chunk = encoded_fp.read(CHUNK_SIZE) sock.send('\n' + end_str + '\n') ``` This example seems a little more involved, but it will ensure that the server can keep reading data in 4096-byte chunks, and all it has to do is Base64-decode the data on the other end (a C library for which is available [here](http://libb64.sourceforge.net/). The Base64 decoder ignores the extra spaces, and the format can handle both binary and text files (what would happen, for example, if a file contained the "end filename" line? It would confuse the server). The other approach is to prefix the sending of the file with the file's length. So for example, instead of sending `send filename` you might say `send 4192 filename` to specify that the length of the file is 4192 bytes. The client would have to build the `send_str` based on the length of the file (as read into the `data` variable in the code above), and would not need to use Base64 encoding as the server would not try to interpret any `end filename` syntax appearing in the body of the sent file. This is what happens in HTTP; the `Content-length` HTTP header is used to specify how long the sent data is. An example client might look like this: ``` import socket import sys # Extract the socket data from the file arguments filename = sys.argv[1] host = sys.argv[2] port = int(sys.argv[3]) # Make the socket sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM) sock.connect((host,port)) # Prepare the message to send data = open(filename).read() send_str = "send %d %s" % (len(data), filename) end_str = "end %s" % (filename,) sock.send(send_str + '\n') sock.send(data) sock.send('\n' + end_str + '\n') ``` Either way, you're going to have to make changes to both the server and the client. In the end it would probably be easier to implement a rudimentary HTTP server (or to get one which has already been implemented) in C, as it seems that's what you're doing here. The encoding/padding solution is quick but creates a lot of redundantly-sent data (as Base64 typically causes a 33% increase in the quantity of data sent), the length prefix solution is also easy from the client side but may be more difficult on the server.
socket trouble in python
[ "", "python", "sockets", "" ]
GUI development with Swing. I have a custom dialog for choosing a file to be opened in my application; its class extends `javax.swing.JDialog` and contains, among other components, a `JFileChooser`, which can be toggled to be shown or hidden. The `JFileChooser` component already handles the ESC key by itself: when the file chooser is shown (embedded in my dialog) and I press ESC, the file chooser hides itself. Now I would like my dialog to do the same: when I press ESC, I want the dialog to close. Mind you, when the embedded file chooser is shown, the ESC key should only hide it. Any ideas ?
Use `InputMap` and `ActionMap` for dealing with key actions in Swing. To close the dialog cleanly, send a window closing event to it. From my now defunct weblog: ``` private static final KeyStroke escapeStroke = KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0); public static final String dispatchWindowClosingActionMapKey = "com.spodding.tackline.dispatch:WINDOW_CLOSING"; public static void installEscapeCloseOperation(final JDialog dialog) { Action dispatchClosing = new AbstractAction() { public void actionPerformed(ActionEvent event) { dialog.dispatchEvent(new WindowEvent( dialog, WindowEvent.WINDOW_CLOSING )); } }; JRootPane root = dialog.getRootPane(); root.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put( escapeStroke, dispatchWindowClosingActionMapKey ); root.getActionMap().put( dispatchWindowClosingActionMapKey, dispatchClosing ); } ```
You can use the following snippet. This is better because the rootPane will get events from any component in the dialog. You can replace setVisible(false) with dispose() if you want. ``` public static void addEscapeListener(final JDialog dialog) { ActionListener escListener = new ActionListener() { @Override public void actionPerformed(ActionEvent e) { dialog.setVisible(false); } }; dialog.getRootPane().registerKeyboardAction(escListener, KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), JComponent.WHEN_IN_FOCUSED_WINDOW); } ```
Swing: how do I close a dialog when the ESC key is pressed?
[ "", "java", "user-interface", "swing", "" ]
I am reading files in various formats and languages and I am currently using a small encoding library to take attempt to detect the proper encoding (<http://www.codeproject.com/KB/recipes/DetectEncoding.aspx>). It's pretty good, but it still misses occasionally. (Multilingual files) Most of my potential users have very little understanding of encoding (the best I can hope for is "it has something to do with characters") and are very unlikely to be able to choose the right encoding in a list, so I would like to let them cycle through different encodings until the right one is found just by clicking on a button. Display problems? Click here to try a different encoding! (Well that's the concept anyway) What would be the best way to implement something like that? --- Edit: Looks like I didn't express myself clearly enough. By "cycling through the encoding", I don't mean "how to loop through encodings?" What I meant was "how to let the user try different encodings in sequence without reloading the file?" The idea is more like this: Let's say the file is loaded with the wrong encoding. Some strange characters are displayed. The user would click a button "Next encoding" or "previous encoding", and the string would be converted in a different encoding. The user just need to keep clicking until the right encoding is found. (whatever encoding looks good for the user will do fine). As long as the user can click "next", he has a reasonable chance of solving his problem. What I have found so far involves converting the string to bytes using the current encoding, then converting the bytes to the next encoding, converting those bytes into chars, then converting the char into a string... Doable, but I wonder if there isn't an easier way to do that. For instance, if there was a method that would read a string and return it using a different encoding, something like "render(string, encoding)". --- Thanks a lot for the answers!
Read the file as bytes and use then the Encoding.GetString Method. ``` byte[] data = System.IO.File.ReadAllBytes(path); Console.WriteLine(Encoding.UTF8.GetString(data)); Console.WriteLine(Encoding.UTF7.GetString(data)); Console.WriteLine(Encoding.ASCII.GetString(data)); ``` So you have to load the file only one time. You can use every encoding based on the original bytes of the file. The user can select the correct one und you can use the result of Encoding.GetEncoding(...).GetString(data) for further processing.
(removed original answer following question update) > For instance, if there was a method > that would read a string and return it > using a different encoding, something > like "render(string, encoding)". I don't think you can re-use the string data. The fact is: if the encoding was wrong, this string can be considered corrupt. It may very easily contain gibberish among the likely looking characters. In particular, many encodings may forgive the presence/absence of a BOM/preamble, but would you re-encode with it? without it? If you are happy to risk it (I wouldn't be), you could just re-encode your local string with the last encoding: ``` // I DON'T RECOMMEND THIS!!!! byte[] preamble = lastEncoding.GetPreamble(), content = lastEncoding.GetBytes(text); byte[] raw = new byte[preamble.Length + content.Length]; Buffer.BlockCopy(preamble, 0, raw, 0, preamble.Length); Buffer.BlockCopy(content, 0, raw, preamble.Length, content.Length); text = nextEncoding.GetString(raw); ``` In reality, I believe the best you can do is to keep the original `byte[]` - keep offering different renderings (via different encodings) until they like one. Something like: ``` using System; using System.IO; using System.Text; using System.Windows.Forms; class MyForm : Form { [STAThread] static void Main() { Application.EnableVisualStyles(); Application.Run(new MyForm()); } ComboBox encodings; TextBox view; Button load, next; byte[] data = null; void ShowData() { if (data != null && encodings.SelectedIndex >= 0) { try { Encoding enc = Encoding.GetEncoding( (string)encodings.SelectedValue); view.Text = enc.GetString(data); } catch (Exception ex) { view.Text = ex.ToString(); } } } public MyForm() { load = new Button(); load.Text = "Open..."; load.Dock = DockStyle.Bottom; Controls.Add(load); next = new Button(); next.Text = "Next..."; next.Dock = DockStyle.Bottom; Controls.Add(next); view = new TextBox(); view.ReadOnly = true; view.Dock = DockStyle.Fill; view.Multiline = true; Controls.Add(view); encodings = new ComboBox(); encodings.Dock = DockStyle.Bottom; encodings.DropDownStyle = ComboBoxStyle.DropDown; encodings.DataSource = Encoding.GetEncodings(); encodings.DisplayMember = "DisplayName"; encodings.ValueMember = "Name"; Controls.Add(encodings); next.Click += delegate { encodings.SelectedIndex++; }; encodings.SelectedValueChanged += delegate { ShowData(); }; load.Click += delegate { using (OpenFileDialog dlg = new OpenFileDialog()) { if (dlg.ShowDialog(this)==DialogResult.OK) { data = File.ReadAllBytes(dlg.FileName); Text = dlg.FileName; ShowData(); } } }; } } ```
C#: Cycle through encodings
[ "", "c#", "utf-8", "character-encoding", "" ]
I'm using TextWrangler to edit PHP code. I often run into the problem that the code just displays as a blank page in my development environment. Is there a good way to further target which place I should look in my code for the problem? Right now I'm just manually running through every line any time I run into this, but I'm guessing there is some sort of solution for this that I haven't been able to find the name for..
You should make sure your development php.ini file contains: ``` display_errors = On error_reporting = E_ALL ``` or ``` display_errors = On error_reporting = E_ALL | E_STRICT ``` Even with these on, sometimes an out-of-memory error can cause a blank page.
Set php.ini `error_reporting` to E\_ALL ``` display_error = On error_reporting = E_ALL ``` You can do this in your code also. ``` error_reporting(E_ALL); ``` or ``` ini_set('error_reporting', E_ALL); ``` You can read more about [error reporting here.](http://is.php.net/error_reporting)
PHP syntax checking?
[ "", "php", "syntax", "text-editor", "" ]
I have a vector of myObjects in global scope. I have a method which uses a `std::vector<myObject>::const_iterator` to traverse the vector, and doing some comparisons to find a specific element. Once I have found the required element, I want to be able to return a pointer to it (the vector exists in global scope). If I return `&iterator`, am I returning the address of the iterator or the address of what the iterator is pointing to? Do I need to cast the `const_iterator` back to a myObject, then return the address of that?
Return the address of the thing pointed to by the iterator: ``` &(*iterator) ``` **Edit:** To clear up some confusion: ``` vector <int> vec; // a global vector of ints void f() { vec.push_back( 1 ); // add to the global vector vector <int>::iterator it = vec.begin(); * it = 2; // change what was 1 to 2 int * p = &(*it); // get pointer to first element * p = 3; // change what was 2 to 3 } ``` No need for vectors of pointers or dynamic allocation.
Returning &iterator will return the address of the iterator. If you want to return a way of referring to the element return the iterator itself. Beware that you do not need the vector to be a global in order to return the iterator/pointer, but that operations in the vector can invalidate the iterator. Adding elements to the vector, for example, can move the vector elements to a different position if the new size() is greater than the reserved memory. Deletion of an element before the given item from the vector will make the iterator refer to a different element. In both cases, depending on the STL implementation it can be hard to debug with just random errors happening each so often. EDIT after comment: 'yes, I didn't want to return the iterator a) because its const, and b) surely it is only a local, temporary iterator? – Krakkos' Iterators are not more or less local or temporary than any other variable and they are copyable. You can return it and the compiler will make the copy for you as it will with the pointer. Now with the const-ness. If the caller wants to perform modifications through the returned element (whether pointer or iterator) then you should use a non-const iterator. (Just remove the 'const\_' from the definition of the iterator).
Returning a pointer to a vector element in c++
[ "", "c++", "pointers", "containers", "iterator", "" ]
Again me with vectors. I hope I'm not too annoying. I have a struct like this : ``` struct monster { DWORD id; int x; int y; int distance; int HP; }; ``` So I created a vector : ``` std::vector<monster> monsters; ``` But now I don't know how to search through the vector. I want to find an ID of the monster inside the vector. ``` DWORD monster = 0xFFFAAA; it = std::find(bot.monsters.begin(), bot.monsters.end(), currentMonster); ``` But obviously it doesn't work. I want to iterate only through the .id element of the struct, and I don't know how to do that. Help is greatly appreciated. Thanks !
[`std::find_if`](http://en.cppreference.com/w/cpp/algorithm/find): ``` it = std::find_if(bot.monsters.begin(), bot.monsters.end(), boost::bind(&monster::id, _1) == currentMonster); ``` Or write your own function object if you don't have boost. Would look like this ``` struct find_id : std::unary_function<monster, bool> { DWORD id; find_id(DWORD id):id(id) { } bool operator()(monster const& m) const { return m.id == id; } }; it = std::find_if(bot.monsters.begin(), bot.monsters.end(), find_id(currentMonster)); ```
how about: ``` std::find_if(monsters.begin(), monsters.end(), [&cm = currentMonster] (const monster& m) -> bool { return cm == m; }); ```
Vectors, structs and std::find
[ "", "c++", "data-structures", "find", "vector", "" ]
Can someone explain this behavior in Generics? I have a generic function in C# ``` protected virtual void LoadFieldDataEditor <T> (ref T control, string strFieldName) where T : Control { //T can be different types of controls inheriting from System.Web.UI.Control if (control is TextBox) { //This line gives an error //((TextBox)control).Text = "test"; //This line works! (control as TextBox).Text = "Test"; } } ``` On a side note, can I use switch case when I am doing a "Control is TextBox" type of checking? EDIT: Forgot to add the error message Sorry! Here you go: ``` Error 3 Cannot convert type 'T' to 'TextBox' ``` EDIT: While we are talking about generics, I have another question. (Wasn't sure If I had to start a new post) The method has been expanded to include another generic type ``` protected virtual void LoadFieldDataEditor <T1, T2> (T1 control, T2 objData, string strFieldName) where T1 : Control where T2 : BaseDataType { //I will need to access field1. //I don't know at compile time if this would be SomeType1 or //SomeType2 but all of them inherit from BaseDataType. //Is this possible using generics? } public abstract class BaseDataType {} public class SomeType1 : BaseDataType { string field1; string field2; } ```
The rules for what a generic type can be converted to are quite tricky, and occasionally counterintuitive, as in this case. See section 6.2.6 of the C# spec for details. There are places where they could be laxer, and I think this is one of them. You *can* cast up to `object` and then down again, but that's ugly. In this case the better solution would be: ``` protected virtual void LoadFieldDataEditor <T> (ref T control, string strFieldName) where T : Control { TextBox textBox = control as TextBox; if (textBox != null) { textBox.Text = "test"; } } ``` Aside from anything else, this only requires a single execution time check instead of two. For the side note: no, you can't use switch/case on types. (You could get the type name and switch on that, but it would be horrible.)
I'd highly recommend refactoring this to be: ``` protected virtual void LoadFieldDataEditor(Control control, string strFieldName) ``` As mentioned in a few comments, this method does not need generics at all. Since you're constraining to a Control, you know the base class, and it's a reference type (Control), so you can avoid the generics and the ref parameter declaration. Since Control is a reference type, you are free to change it's properties in the method, and this will work correctly. Setting .Text, etc, will do exactly what you are trying to do, but be much simpler. There is a small chance that you could need it to be: ``` protected virtual void LoadFieldDataEditor(ref Control control, string strFieldName) ``` but this would only be required if you were going to reassign control inside your method (ie: `control = new TextBox();`). I would strongly recommend against doing that, as it can cause some very unexpected behavior and would not be obvious. If you are trying to create a new control, using an out parameter, or just returning the new control would make everything much more clear. Also, in general, it's a good idea to avoid generic methods unless there is a good reason to include them. The FxCop team has added (and later removed) some rules trying to discourage their use because they tend to make code less understandable in the long run. There are many good reasons for using generic methods, but this doesn't require their use, so I would recommend avoiding them.
C# Generics function
[ "", "c#", "generics", "" ]
I have to implement an RMI server which will be a front end for two other RMI services. So I decided a logical thing to do would be to have the interface for this implement the interfaces for the other two services. ``` public interface FrontEndServer extends Remote, BookServer, StudentServer { // Block empty so far } ``` However there is a method on the StudentServer ``` /** * Allows a student to borrow a book * * @param studentID of the student who wishes to borrow a book * @param bookID of the book the student wishes to borrow * @throws RemoteException * @throws StudentNotFoundException when a student is not found in the system */ void addBookToStudent(int studentID, int bookID) throws RemoteException, StudentNotFoundException; ``` I would like the `FrontEndServer` to also throw a `BookNotFoundException` as this service will also validate if the book actually exists before attempting to add the details in. Is this possible or is my design idea completely off and this is actually a bad design idea as if the other interfaces change and all? And will I be better of writing the method signatures for all the methods inside the `FrontEndServer`?
If you extend an interface (the same applies if you implement an interface), you can't override a method and have it throw **more** checked exceptions than the original. You can it throw the same or less but not more. Think about it: ``` interface A { void foo(); } interface B extends A { void foo() throws IOException; } A a = new B() { ... } a.foo(); ``` would potentially throw an IOException but you'd have no way of knowing. That's why you can't do it. This of course is perfectly acceptable: ``` interface A { void foo() throws IOException; } interface B extends A { void foo(); } A a = new B() { ... } try { a.foo(); } catch (IOException e) { // must catch even though B.foo() won't throw one } ``` Your `BookNotFoundException` could however extend `RuntimeException` or `RemoteException`. Not sure that's a good approach however.
What good does a single type that extends both of these interfaces? Do you lose anything when a client depends on two distinct objects? Overuse of inheritance is a common beginner mistake, because "inheritance" is one of the notable traits of object-oriented programming. However, in most cases, composition is a better choice. In this case, why not have two separate services? Then, adding `CafeteriaService` and `DormitoryService` later doesn't impact any existing interfaces. With regard to the design, the `addBookToStudent` method would benefit from being able to throw `BookNotFoundException`. Interfaces are brittle, in the sense that changing them in any way breaks a lot of code. You have to be very careful in their initial design. For example, `BookNotFoundException` is probably to specific; couldn't there exist a variety of exceptions that would prevent "adding" a book to a student? (I'm guessing that students are checking books out of a lending library.) For example: `CheckOutLimitExceededException`, `UnpaidFinePendingException`, `AdultLiteraturePermissionException`, etc. Think carefully about the types of checked-exceptions that might be appropriate for the level of abstraction when designing interfaces, because they are hard to change later.
Java interface extends questions
[ "", "java", "interface", "" ]
We had some problems this morning and need to rollback our database for about one hour. Is this possible and how is it done? It is a Microsoft SQL 2005 database.
1. Find the previous full backup of your database (BF1). 2. Take a backup of the log file (BL1). 3. Take a full backup of the database (BF2). Good to have, in case the following steps go wrong. 4. Restore the previous full backup (BF1), with NORECOVERY 5. Restore the log file backup (BL1) with RECOVERY, and specifying the point in time you want to recover.
1. Select Your database. 2. Then select Tasks/Restore/Database. 3. On the restore database dialog select the Timeline option 4. Enter the time from when you want to revert your database. 5. Click ok 6. Ok Again. 7. Your database updated successfully.
Rollback complete database one hour
[ "", "sql", "sql-server", "sql-server-2005", "" ]
Can you give me an almost overly simplistic understanding of abstract class vs inheritance use and help me so I can truly understand the concept and how to implement? I have a project I'm trying to complete, and am lost on how to implement. I've been chatting with my professor and been told off pretty much, saying that if I can't figure it out, I'm probably not ready for the course. I have OVERCOVERED the prerequestite courses, and still have trouble understanding these concepts. To clarify, the project as I've done so far is below. I don't have the dog/cat classes etc filled out yet. Can you give me a pointer. I'm not asking for anyone to give me the "answers." I just am lost on where to go with this. I take online courses and his communication efforts with me have been troubling. I just finished with 4.0 with all my other courses, so I'm willing to put the effort in, but I'm lost in the comprehension of these concepts and how to PRACTICALLY apply them. Any comments or help that will let me progress further in this project? The description of what I'm to implement is as follows: > Overview: > > The purpose of this exercise is to > demonstrate the use of Interfaces, > Inheritance, Abstract classes, and > Polymorphism. Your task is to take > the supplied program shell and ADD the > appropriate classes and corresponding > class members/methods to get this > program to function correctly. You may > not make changes to any of the code > supplied, you may only add the classes > you write. Although there are > numerous ways to get the program > working, you must use techniques that > demonstrate the use of Interfaces, > Inheritance, Abstract classes, and > Polymorphism. Again, to make clear, > you can add to the supplied code but > you cannot change or delete any of > it. The code that is supplied will > work with very little additional code > and will satisfy the requirements of > the exercise. > > If you successfully complete the > assignment, your program should output > the following statements when run: > > My name is Spot, I am a Dog > > My name is Felix, I am a Cat > > Requirements: > > 1) You must have an abstract base > class called 'Animal' from which the > Dog and Cat classes derive. > > 2) The Animal base class must derive > from the Interface 'IAnimal', it is > the only class that should derive from > IAnimal. > > 3) Since all animals have a name and a > name is not an attribute that is > specific to a dog or a cat, the Animal > > base class should be where the name > is stored and where the WhatIsMyName > get-property is implemented. > > 4) You will need to create a Dog and a > Cat class that will derive only from > the Animal base class. > > 5) The Dog and Cat classes should > implement the WhatAmI get-property and > return the appropriate string value. Code you can't change: ``` using System; namespace IT274_U2 { public interface IAnimal { string WhatAmI { get; } string WhatIsMyName { get; } } public class TesterClass { public static void DescribeAnimal(IAnimal animal) { Console.WriteLine("My name is {0}, I am a {1}", animal.WhatIsMyName, animal.WhatAmI); } static void Main(string[] args) { Dog mydog = new Dog("Spot"); Cat mycat = new Cat("Felix"); DescribeAnimal(mydog); DescribeAnimal(mycat); } } } ``` /////////////////////// Code I've written so far: ``` using System; namespace IT274_U2 { public interface IAnimal { string WhatAmI { get; } string WhatIsMyName { get; } } public class Dog { public abstract string WhatAmI { get; set; } }//end public class Dog public class Cat { public abstract string WhatIsMyName { get; set; } }//end public class Cat public abstract class Animal : IAnimal { // fields protected string Dog; protected string Cat; // implement WhatIsMyName //properties public abstract String Dog { get; set; } public abstract String Cat { get; set; } public abstract string WhatIsMyName(); } //end public abstract class Animal public class TesterClass { public static void DescribeAnimal(IAnimal animal) { Console.WriteLine("My name is {0}, I am a {1}", animal.WhatIsMyName, animal.WhatAmI); } static void Main(string[] args) { Dog mydog = new Dog("Spot"); Cat mycat = new Cat("Felix"); DescribeAnimal(mydog); DescribeAnimal(mycat); } } } ```
**EDIT:** I have taken the body of code for each class out - If you want to see my answer, have a look at the edit revisions :) First off we define the [interface](http://msdn.microsoft.com/en-us/library/ms173156.aspx) ``` public interface IAnimal { string WhatAmI { get; } string WhatIsMyName { get; } } ``` Any class that implements this interface must implement these properties. An interface is like a contract; a class implementing an interface agrees to provide an implementation of the interface's methods, properties events or indexers. Next, we need to define your abstract Animal class ``` public abstract class Animal : IAnimal { //Removed for Training, See Edit for the code } ``` The fact that the class is [abstract](http://msdn.microsoft.com/en-us/library/sf985hc5(VS.71).aspx) indicates that the class is intended only to be a base class for other classes. We have implemented both properties of the interface and also have a private field to store the animal name. In addition, we have made the `WhatAmI` property accessor abstract so that we can implement our own specific property accessor logic in each derived class and have also defined a constructor that accepts a string argument and assigns the value to the `_name` private field. Now, let's define our `Cat` and `Dog` classes ``` public class Dog : Animal { //Removed for Training, See Edit for the code } public class Cat : Animal { //Removed for Training, See Edit for the code } ``` Both classes inherit from `Animal` and each has a constructor that defines a string argument and passes that argument as a parameter to the base constructor. In addition, each class implements it's own property accessor for `WhatAmI`, returning a string of their type, respectively. For the rest of the code ``` public class Program { public static void DescribeAnimal(IAnimal animal) { Console.WriteLine("My name is {0}, I am a {1}", animal.WhatIsMyName, animal.WhatAmI); } static void Main(string[] args) { Dog mydog = new Dog("Spot"); Cat mycat = new Cat("Felix"); DescribeAnimal(mydog); DescribeAnimal(mycat); Console.ReadKey(); } } ``` the static method `DescribeAnimal` accepts an `IAnimal` as an argument and writes out the values returned by the `WhatIsMyName` and `WhatAmI` property accessors for the passed in `IAnimal`. Since `Animal` implements `IAnimal` and both `Dog` and `Cat` inherit from `Animal`, any `Cat` or `Dog` object can be passed as a parameter to the `DescribeAnimal` method. I hope that I have explained this clearly, If anyone feels my choice of words needs tightening up, please comment and I will be happy to edit my answer.
The main difference between an interface and an abstract class is that in the interface you only define what should be the public methods and properties of the object that implements this interface. An abstract class provides some base implementation, but has some "gaps" - abstract methods that the inheritor needs to implement. I am not going to do your homework for you, but a hint: the Animal class should NOT contain anything specific for dogs and cats.
Can you help me understand in a practical example the usage abstract classes vs interfaces?
[ "", "c#", "interface", "abstract-class", "" ]
This algorithm does a great job of traversing the nodes in a graph. ``` Dictionary<Node, bool> visited = new Dictionary<Node, bool>(); Queue<Node> worklist = new Queue<Node>(); visited.Add(this, false); worklist.Enqueue(this); while (worklist.Count != 0) { Node node = worklist.Dequeue(); foreach (Node neighbor in node.Neighbors) { if (!visited.ContainsKey(neighbor)) { visited.Add(neighbor, false); worklist.Enqueue(neighbor); } } } ``` I can use this to find a target node in the graph. The worklist dequeues (or pops) the items as the worklist is processed. Once I find the target how can I return the full path to the node? **Update** I am trying to figure out how to reverse the path to the root. The method is called on the root node, after that, children may have two parents, so it isn't as simple as calling the parent property on each node and traversing back up. The goal of the method is to find the path, not to iterate all nodes, or to check if a node does exist.
Keep track of the predecessor nodes. In the easiest implementation, this is a dictionary, and usually denoted as π in pseudo-codes: ``` Dictionary<Node, bool> visited = new Dictionary<Node, bool>(); Dictionary<Node, Node> π = new Dictionary<Node, Node>(); Queue<Node> worklist = new Queue<Node>(); visited.Add(this, false); worklist.Enqueue(this); while (worklist.Count != 0) { Node node = worklist.Dequeue(); foreach (Node neighbor in node.Neighbors) { if (!visited.ContainsKey(neighbor)) { visited.Add(neighbor, false); π.Add(neighbor, node); worklist.Enqueue(neighbor); } } } ``` Then you can iterate through these predecessors to backtrack the path from any node, say `e`: ``` while (π[e] != null) { Console.WriteLine(e); e = π[e]; } ```
Is "this", that is, the current instance, the "root" of the graph, if there is such a thing? Is the graph cyclic or acyclic? I'm afraid I don't know all the terms for graph theory. Here's what I really wonder about: ``` A -> B -> C ------> F B -> D -> E -> F ``` Here are my questions: * Will this occur? * Can "this" in your code ever start at B? * What will the path to F be? If the graph never joins back together when it has split up, doesn't contain cycles, and "this" will always be the root/start of the graph, a simple dictionary will handle the path. ``` Dictionary<Node, Node> PreNodes = new Dictionary<Node, Node>(); ``` for each node you visit, add the neighbouring node as key, and the node it was a neighbour of as the value. This will allow you to, once you've find the target node, to backtrack back to get the reversed path. In other words, the dictionary for the graph above, after a full traversal would be: ``` B: A C: B D: B E: D F: C (or E, or both?) ``` To find the path to the E-node, simply backtrack: ``` E -> D -> B -> A ``` Which gives you the path: ``` A -> B -> D -> E ```
C# Graph Traversal
[ "", "c#", "graph", "traversal", "" ]
I am using ajax to update the location of a page in a frame. But when setting the location of the hash (on Chrome and some versions of IE (5.5) specifically, but occasionally on IE7) the page is being reloaded. The following html demonstrates the problem. the main frame.... frame.html is ``` <html><head> <frameset rows="*"> <frame src=sethash.html frameborder=0 scrolling=auto name=somebody> </frameset> </head></html> ``` the sethash.html page is . ``` <html><head> <script language=JavaScript> var Count = 0; function sethash() { top.document.location.hash = "hash" + Count; Count++; } </script> </head> <body onload="alert('loaded')"> <h1>Hello</h1> <input type='button' onClick='sethash()' value='Set Hash'> </body> </html>` ``` On most browsers loading the frame.html will show the loaded alert once when the page is loaded. Then when the set hash button is pressed the url will be changed but the hash the loaded alert will not show again. On chrome and some versions of I.E Microsoft report possibly the same problem with Internet Explorer 5.5 [link text](http://support.microsoft.com/kb/274586) I can't use the microsoft suggested solution, which is to capture the event and not fire it, but just scroll into view, as am using set the top.location.hash as part of the onLoad event.
Webkit (and by extension, Chrome) behave strangely with location.hash. There are a few open bugs about it, the most relevant is probably this one: <https://bugs.webkit.org/show_bug.cgi?id=24578> that documents your problem of having the page refresh when location.hash is changed. It looks like your best option right now is to cross your fingers and hope that it gets promptly fixed. I can't reproduce the bug in IE7 though, and you're the first person in ages I've seen that supports IE5.5 so I can't really help you there ;)
You could also use HTML5 [history.pushState()](https://developer.mozilla.org/en/DOM/Manipulating_the_browser_history#The_pushState%28%29.C2.A0method) to change hash without reloading page in Chrome. Something like this: ``` // frameset hash change function function changeHash(win, hash) { if(history.pushState) { win.history.replaceState(null, win.document.title, '#'+hash); } else { win.location.hash = hash; } } ``` In the first argument you need to pass frameset top window.
Setting location.hash in frames
[ "", "javascript", "ajax", "google-chrome", "frameset", "fragment-identifier", "" ]
Not as in "can't find the answer on stackoverflow", but as in "can't see what I'm doing wrong", big difference! Anywho, the code is attached below. What it does is fairly basic, it takes in a user created text file, and spits out one that has been encrypted. In this case, the user tells it how many junk characters to put between each real character. (IE: if I wanted to encrypt the word "Hello" with 1 junk character, it would look like "9H(eal~l.o") My problem is that for some reason, it isn't reading the input file correctly. I'm using the same setup to read in the file as I had done previously on decrypting, yet this time it's reading garbage characters, and when I tell it to output to file, it prints it on the screen instead, and it seems like nothing is being put in the output file (though it is being created, so that means I've done something correctly, point for me! code: ``` string start; char choice; char letter; int x; int y; int z; char c; string filename; while(start == "enc") { x = 1; y = 1; cout << "How many garbage characters would you like between each correct character?: " ; cin >> z; cout << endl << "Please insert the name of the document you wish to encrypt, make sure you enter the name, and the file type (ie: filename.txt): " ; cin >> filename; ifstream infile(filename.c_str()); ofstream outfile("encrypted.txt", ios::out); while(!infile.eof()) { infile.get(letter); while ((x - y) != z) { outfile << putchar(33 + rand() % 94); x++; } while((x - y) == z) { outfile << letter; y = 1; x = 1; } } outfile.close(); cout << endl << "Encryption complete...please return to directory of program, a new file named encrypted.txt will be there." << endl; infile.close(); cout << "Do you wish to try again? Please press y then enter if yes (case sensitive)."; cin >> choice; ``` What I pasted above the start of the while loop are the declaration variables, this is part of a much larger code that not only will encrypt, but decrypt as well, I left the decryption part out as it works perfectly, it's this part I'm having an issue with. Thanks in advance for the assist! EDIT:: I'm using visual C++ express 2008, and it shoots back that there are no errors at all, nor any warnings. **IMPORTANT EDIT** It turns out it is outputting to the file! However, it is outputting numbers instead of ascii characters, and it is also outputting the garbage character for the letter it should be. When it goes back to the "infile.get(letter)", it doesn't get a new character. So right now it seems to be the issues are 2 fold: 1) Printing numbers instead of ascii characters. 2) Using garbage instead of the actual character it should be getting. **Question Answered** Found out the second part in the "Important Edit" ...it turns out if you name something test.txt...that means it is actually called test.txt.txt when you type it into a C++ program. Just goes to show it's the tiny, minute, simple details that cause any program to go pooey. Thank you to George Shore. Your comment about the input file being in the wrong place is what gave me the idea to try the actual items name. Thank you to everyone who helped with the answer!
Further to the previous answers, I believe it's because the file you wish to encrypt is not being found by the original code. Is it safe to assume that you're running the code from the IDE? If so, then the file that is to be encrypted has to be in the same directory as the source. Also: ``` outfile << putchar(33 + rand() % 94); ``` seems to be the source of your garbage to the screen; the 'putchar' function echoes to the screen whilst returning the integer value of that character. What is then going to happen is that number will be output to the file, as opposed to the character. Changing that block to something like: ``` while ((x - y) != z) { c = (33 + rand() % 94); outfile << c; x++; } ``` should enable the code to run as you want it to.
Rather than doing this: ``` while (!infile.eof()) { infile.get(letter); if (infile.good()) { ``` Do this: ``` while (infile.get(letter)) { ``` This is the standard pattern for reading a file. It gets a character and the resulting infile (that is returned by get) is then checked to see if it is still good by converting it to bool. The line: ``` outfile << putchar(33 + rand() % 94); ``` Should probably be: ``` outfile << static_cast<char>(33 + rant() % 94); ``` putchar() prints to the standard output. But the return value (same as the input) goes to the outfile. To stop this just convert the value to char and send to outfile.
Error in outputting to a file in C++ that I can't find
[ "", "c++", "encryption", "fstream", "" ]
OK, this is a slightly weird question. We have a touch-screen application (i.e., no keyboard). When users need to enter text, the application shows virtual keyboard - hand-built in WinForms. Making these things by hand for each new language is monkey work. I figure that windows must have this keyboard layout information hiding somewhere in some dll. Would there be anyway to get this information out of windows? Other ideas welcome (I figure at least generating the thing from a xml file has got to be better than doing it by hand in VS). (Note: having said all which, I note that there is a Japanese keyboard, state machine and all..., so XML might not be sufficient) **UPDATE**: pretty good series on this subject (I believe) [here](http://www.siao2.com/2006/04/22/581107.aspx)
[Microsoft Keyboard Layout Creator](http://msdn.microsoft.com/en-us/goglobal/bb964665.aspx) can load system keyboards and export them as [.klc files](http://www.siao2.com/2006/11/02/928185.aspx). Since it’s written in .NET you can use [Reflector](http://www.reflector.net/) to see how it does that, and use reflection to drive it. Here's a [zip file of .klc files for the 187 keyboards in Windows 8](https://bitbucket.org/andrewdotn/stackexchange/downloads/sx-661722.zip) created using the below C# code. Note that I originally wrote this for Windows XP, and now with Windows 8 and the on-screen keyboard, it is really slow and seems to crash the taskbar :/ However, it does work :) ``` using System; using System.Collections; using System.IO; using System.Reflection; class KeyboardExtractor { static Object InvokeNonPublicStaticMethod(Type t, String name, Object[] args) { return t.GetMethod(name, BindingFlags.Static | BindingFlags.NonPublic) .Invoke(null, args); } static void InvokeNonPublicInstanceMethod(Object o, String name, Object[] args) { o.GetType().GetMethod(name, BindingFlags.Instance | BindingFlags.NonPublic) .Invoke(o, args); } static Object GetNonPublicProperty(Object o, String propertyName) { return o.GetType().GetField(propertyName, BindingFlags.Instance | BindingFlags.NonPublic) .GetValue(o); } static void SetNonPublicField(Object o, String propertyName, Object v) { o.GetType().GetField(propertyName, BindingFlags.Instance | BindingFlags.NonPublic) .SetValue(o, v); } [STAThread] public static void Main() { System.Console.WriteLine("Keyboard Extractor..."); KeyboardExtractor ke = new KeyboardExtractor(); ke.extractAll(); System.Console.WriteLine("Done."); } Assembly msklcAssembly; Type utilitiesType; Type keyboardType; String baseDirectory; public KeyboardExtractor() { msklcAssembly = Assembly.LoadFile("C:\\Program Files\\Microsoft Keyboard Layout Creator 1.4\\MSKLC.exe"); utilitiesType = msklcAssembly.GetType("Microsoft.Globalization.Tools.KeyboardLayoutCreator.Utilities"); keyboardType = msklcAssembly.GetType("Microsoft.Globalization.Tools.KeyboardLayoutCreator.Keyboard"); baseDirectory = Directory.GetCurrentDirectory(); } public void extractAll() { DateTime startTime = DateTime.UtcNow; SortedList keyboards = (SortedList)InvokeNonPublicStaticMethod( utilitiesType, "KeyboardsOnMachine", new Object[] {false}); DateTime loopStartTime = DateTime.UtcNow; int i = 0; foreach (DictionaryEntry e in keyboards) { i += 1; Object k = e.Value; String name = (String)GetNonPublicProperty(k, "m_stLayoutName"); String layoutHexString = ((UInt32)GetNonPublicProperty(k, "m_hkl")) .ToString("X"); TimeSpan elapsed = DateTime.UtcNow - loopStartTime; Double ticksRemaining = ((Double)elapsed.Ticks * keyboards.Count) / i - elapsed.Ticks; TimeSpan remaining = new TimeSpan((Int64)ticksRemaining); String msgTimeRemaining = ""; if (i > 1) { // Trim milliseconds remaining = new TimeSpan(remaining.Hours, remaining.Minutes, remaining.Seconds); msgTimeRemaining = String.Format(", about {0} remaining", remaining); } System.Console.WriteLine( "Saving {0} {1}, keyboard {2} of {3}{4}", layoutHexString, name, i, keyboards.Count, msgTimeRemaining); SaveKeyboard(name, layoutHexString); } System.Console.WriteLine("{0} elapsed", DateTime.UtcNow - startTime); } private void SaveKeyboard(String name, String layoutHexString) { Object k = keyboardType.GetConstructors( BindingFlags.Instance | BindingFlags.NonPublic)[0] .Invoke(new Object[] { new String[] {"", layoutHexString}, false}); SetNonPublicField(k, "m_fSeenOrHeardAboutPropertiesDialog", true); SetNonPublicField(k, "m_stKeyboardTextFileName", String.Format("{0}\\{1} {2}.klc", baseDirectory, layoutHexString, name)); InvokeNonPublicInstanceMethod(k, "mnuFileSave_Click", new Object[] {new Object(), new EventArgs()}); ((IDisposable)k).Dispose(); } } ``` Basically, it gets a list of all the keyboards on the system, then for each one, loads it in MSKLC, sets the "Save As" filename, lies about whether it's already configured the custom keyboard properties, and then simulates a click on the File -> Save menu item.
It is a fairly well-known fact that MSKLC is unable to faithfully import & reproduce keyboard layouts for all of the .DLL files supplied by Windows–especially those in Windows 8 & above. And it doesn't do any good to know where those files are if you can't extract any meaningful or helpful information from them. This is documented by Michael Kaplan on his blog (he was a developer of MSKLC) which I see you have linked to above. When MSKLC encounters anything it does not understand, that portion is removed. Extracting the layout using MSKLC will work for most keyboards, but there are a few–namely the Cherokee keyboard, and the Japanese & Korean keyboards (to name a few, I'm not sure how many more there are)–for which the extracted layout will NOT accurately or completely reflect the actual usage & features of the keyboard. The Cherokee keyboard has chained dead keys which MSKLC doesn't support. And the far Eastern keyboards have modifier keys which MSKLC isn't aware of–that means entire layers/shift states which are missing! Michael Kaplan supplies some code and unlocks some of the secrets of MSLKC and the accompanying software that can be used to get around some of these limitations but it requires a fair amount of doing things by hand–exactly what you're trying to avoid! Plus, Michael's objectives are aimed at creating keyboards with features that MSKLC can not create or understand, but which DO work in Windows (which is the opposite of what the OP is trying to accomplish). I am sure that my solution comes too late to be of use to the OP, but perhaps it will be helpful in the future to someone in a similar situation. That is my hope and reason for posting this. So far all I've done is explain that the other answers are insufficient. Even the best one will not and can not fully & accurately reproduce all of Windows' native keyboards and render them into KLC source files. This is really unfortunate and it is certainly not the fault of its author because that is a very clever piece of code/script! Thankfully the script & the source files (whose link may or may not still work) is useful & effective for the majority of Windows' keyboards, as well as any custom keyboards created by MSKLC. The keyboards that have the advanced features that MSKLC doesn't support were created by the Windows DDK, but those features are not officially documented. Although one can learn quite a bit about their potential by studying the source files provided with MSKLC. Sadly the only solution I can offer is 3rd party, paid software called [KbdEdit](http://kbdedit.com/). I believe it is the only currently available solution which is actually able to faithfully decode & recreate any of the Windows supplied keyboards–although there are a few advanced features which even it can not reproduce (such as keys combinations/hotkeys which perform special native language functions; for example: Ctrl+CapsLock to activate KanaLock (a Japanese modifier layer). KbdEdit DOES faithfully reproduce that modifier layer which MSKLC with strip away, it just doesn't support this alternate method of activating that shift state if you don't have a Japanese keyboard with a Kana lock key. Although, it will allow you to convert a key on your keyboard to a Kana key (perhaps Scroll Lock?). Fortunately, none of those unsupported features are even applicable to an on-screen keyboard. KbdEdit is a really powerful & amazing tool, and it has been worth every penny I paid for it! (And that's NOT something I would say about virtually any other paid software…) Even though KbdEdit is 3rd party software, it is only needed to create the keyboards, not to use them. All of the keyboards it creates work natively on any Windows system without KbdEdit being installed. It supports up to 15 modifier states and three addition modifier keys, one which is togglable–like CapsLock. It also supports chained dead keys, and remapping any of the keys on most any keyboard.
Extracting keyboard layouts from windows
[ "", "c#", "winforms", "keyboard-layout", "" ]
I'm writing a script which manages a very large table. When a user clicks a table cell, I would like to know which cell they clicked. e.g ``` -------------- | | | | | Click| -------------- ``` should give me a cell reference of (1, 1). Any way I could do this with javascript. The page it's running on uses jquery for other purposes, so any jquery based solutions are good aswell. EDIT: To clarify, the top left cell is (0, 0). For performance reasons, the event needs to bound to the *table*, not the tds.
This is done very easily using the `target` property of the `event` object: ``` $('#mytable').click(function(e) { var tr = $(e.target).parent('tr'); var x = $('tr', this).index(tr); var y = tr.children('td').index($(e.target)); alert(x + ',' + y); }); ``` This approach allows you to only bind 1 event handler to the entire table and then figure out which table cell was clicked. This is known as event delegation and can be much more efficient in the right situation, and this one fits the bill. Using this you avoid binding an event to each `<td>`, and it does not require hard-coding coordinates. So, if your table looks like this: ``` <table id='mytable'> <tr> <td>hi</td> <td>heya</td> </tr> <tr> <td>boo</td> <td>weee</td> </tr> </table> ``` It will alert the coordinates on click. You can do whatever with that. :) If you find performance to be too slow (depending on just how large your table is) you would then have to resort to hardcoding or a combination of the two, maybe only hard coding the `<tr>` index, as that would be the slowest to get, and then getting the `<td>` index dynamically. Finally, if all this coordinate business is completely unnecessary and what you really just wanted was a reference to the clicked `<td>`, you would just do this: ``` $('#mytable').click(function(e) { var td = $(e.target); // go crazy }); ```
``` $('td').click(function(event) { var row = $(this).parent('tr'); var horizontal = $(this).siblings().andSelf().index(this); var vertical = row.siblings().andSelf().index(row); alert(horizontal+','+vertical); }); ```
How to get a cell's location
[ "", "javascript", "jquery", "" ]
I am working on a game using Visual C++. I have some components in separate projects, and have set the project dependencies. How do I #include a header file from a different project? I have no idea how to use classes from one project in another.
## Settings for compiler In the project where you want to #include the header file from *another* project, you will need to add the path of the header file into the **Additional Include Directories** section in the project configuration. To access the project configuration: 1. Right-click on the project, and select Properties. 2. Select Configuration Properties -> C/C++ -> General. 3. Set the path under Additional Include Directories. ## How to include To **include the header file**, simply write the following in your code: ``` #include "filename.h" ``` Note that you don't need to specify the path here, because you include the directory in the Additional Include Directories already, so Visual Studio will know where to look for it. If you don't want to add every header file location in the project settings, you could just include a directory up to a point, and then #include relative to that point: ``` // In project settings Additional Include Directories ..\..\libroot // In code #include "lib1/lib1.h" // path is relative to libroot #include "lib2/lib2.h" // path is relative to libroot ``` ## Setting for linker If using static libraries (i.e. .lib file), you will also need to add the library to the linker input, so that at linkage time the symbols can be linked against (otherwise you'll get an unresolved symbol). Adding *another* project as a reference will add it to linker input (Project Properties -> Linker -> Input -> Additional Dependencies). To add a reference: 1. In Solution Explorer under your project there is a References node. Right-click on it, and choose Add Reference... 2. Select *another* project, and click OK. Now building your project will trigger building *another* project if necessary, and the linker will be able to resolve external symbols.
Since both projects are under the same solution, there's a simpler way for the include files and linker as described on [learn.microsoft.com](https://learn.microsoft.com/en-us/cpp/build/adding-references-in-visual-cpp-projects#consuming-static-libraries): 1. The include can be written in a relative path (E.g. `#include "../libProject/libHeader.h"`). 2. For the linker, right click on "References", Click on Add Reference, and choose the other project.
How to #include header files from other projects from the same solution
[ "", "c++", "visual-studio", "projects-and-solutions", "" ]
> This was fixed in Django 1.9 with [form\_kwargs](https://docs.djangoproject.com/en/1.9/topics/forms/formsets/#passing-custom-parameters-to-formset-forms). I have a Django Form that looks like this: ``` class ServiceForm(forms.Form): option = forms.ModelChoiceField(queryset=ServiceOption.objects.none()) rate = forms.DecimalField(widget=custom_widgets.SmallField()) units = forms.IntegerField(min_value=1, widget=custom_widgets.SmallField()) def __init__(self, *args, **kwargs): affiliate = kwargs.pop('affiliate') super(ServiceForm, self).__init__(*args, **kwargs) self.fields["option"].queryset = ServiceOption.objects.filter(affiliate=affiliate) ``` I call this form with something like this: ``` form = ServiceForm(affiliate=request.affiliate) ``` Where `request.affiliate` is the logged in user. This works as intended. My problem is that I now want to turn this single form into a formset. What I can't figure out is how I can pass the affiliate information to the individual forms when creating the formset. According to the docs to make a formset out of this I need to do something like this: ``` ServiceFormSet = forms.formsets.formset_factory(ServiceForm, extra=3) ``` And then I need to create it like this: ``` formset = ServiceFormSet() ``` Now how can I pass affiliate=request.affiliate to the individual forms this way?
I would use [functools.partial](http://docs.python.org/2/library/functools.html#functools.partial) and [functools.wraps](http://docs.python.org/2/library/functools.html#functools.wraps): ``` from functools import partial, wraps from django.forms.formsets import formset_factory ServiceFormSet = formset_factory(wraps(ServiceForm)(partial(ServiceForm, affiliate=request.affiliate)), extra=3) ``` I think this is the cleanest approach, and doesn't affect ServiceForm in any way (i.e. by making it difficult to subclass).
# Official Document Way Django 2.0: ``` ArticleFormSet = formset_factory(MyArticleForm) formset = ArticleFormSet(form_kwargs={'user': request.user}) ``` <https://docs.djangoproject.com/en/2.0/topics/forms/formsets/#passing-custom-parameters-to-formset-forms>
Django Passing Custom Form Parameters to Formset
[ "", "python", "django", "forms", "django-forms", "" ]
I'm toying with the idea of writing a physics simulation software in which each physical element would be simulated in its own thread. There would be several advantages to this approach. It would be conceptually very close to how the real world works. It would be much easier to scale the system to multiple machines. However, for this to work I need to make sure that all threads run at the same speed, with a rather liberal interpretation of 'same'. Say within 1% of each others. That's why I don't necessarily need a Thread.join() like solution. I don't want some uber-controlling school mistress that ensures all threads regularly synchronize with each others. I just need to be able to ask the runtime (whichever it is---could be Java, Erlang, or whatever is most appropriate for this problem) to run the threads at a more or less equal speed. Any suggestions would be extremely appreciated. **UPDATE 2009-03-16** I wanted to thank everyone who answered this question, in particular all those whose answer was essentially "DON'T DO THIS". I understand my problem much better now thanks to everybody's comments and I am less sure I should continue as I originally planned. Nevertheless I felt that Peter's answer was the best answer to the question itself, which is why I accepted it.
You'll need some kind of synchronization. [CyclicBarrier](http://java.sun.com/j2se/1.5.0/docs/api/java/util/concurrent/CyclicBarrier.html) class has what you need: > A synchronization aid that allows a > set of threads to all wait for each > other to reach a common barrier point. > CyclicBarriers are useful in programs > involving a fixed sized party of > threads that must occasionally wait > for each other. The barrier is called > cyclic because it can be re-used after > the waiting threads are released. After each 'tick', you can let all your threads to wait for others, which were slower. When remaining threads reach the barrier, they all will continue.
You can't really do this without coordination. What if one element ended up needing cheaper calculations than another (in a potentially non-obvious way)? You don't necessarily need an uber-controller - you could just keep some sort of step counter per thread, and have a global counter indicating the "slowest" thread. (When each thread has done some work, it would have to check whether it had fallen behind the others, and update the counter if so.) If a thread notices it's a long way ahead of the slowest thread, it could just wait briefly (potentially on a monitor). Just do this every so often to avoid having too much overhead due to shared data contention and I think it could work reasonably well.
How can I make sure N threads run at roughly the same speed?
[ "", "java", "multithreading", "join", "erlang", "simulation", "" ]
I am using Regex.Split to split a SQL script on the keyword "GO". My problem here is that I cannot seem to get my head around how to get the Regex to do the split. My regex expression also splits on "GO" even if it's in a SQL statement like: ``` Insert into x(a,b) values(‘please go get some text’,’abc’) ``` But I only want it to split on the keyword "GO". Any suggestions? EDIT: I am using c#. at the moment my regex is simply: ``` foreach (string batch in Regex.Split(script, "\\bGO\\b", RegexOptions.IgnoreCase)) { yield return batch; } ```
Split on GOs on a line by themselves, like: ``` foreach (string batch in Regex.Split(script, "^GO$\\n", RegexOptions.IgnoreCase | RegexOptions.Multiline)) { yield return batch; } ``` Depending on where your script is coming from you may need to change that to **"^GO$\\r\\n"**
This is pretty much impossible without implementing a complete SQL parser (which you probably do not want to do), in the really correct way. An alternative would be to resort to some hacks (i.e. ignore sections of the text that are within quotes), but this will still not work if your SQL contains the text '`GO`' at some other place, e.g. '`SELECT * FROM GO`'.
Regular expression for a single word
[ "", "c#", "regex", "" ]
I need to do a program to download the webpages, that is, I give a webpage to the software and it would download all the files in the website. I would pass also a level of depth, that is, the level where the software goes download each file of the website. I will develop this software in Java and I need to use concurrency also. Please, tell me your opinion about how to do this. Thanks for the help. --- Thanks to everyone for the help. I need to ask one more thing. How do I do to download a file from the website? Thaks one more time. =D
A very useful library for spiders and bots: [htmlunit](http://htmlunit.sourceforge.net/)
Well, this is a bit hard to answer without knowing how detailed guidance you need, but here's an overview. :) Java makes such applications quite easy, actually, since both HTTP-requests and threading are readily available. My solution would probably involve a global stack containing new urls, and a farm of a constant number of threads that pop urls from the stack. I'd store the urls as a custom object, so that I could keep track of the depth. I think your main issue here will be with sites that doesn't respond, or doesn't follow the HTTP standard. I've noticed many times in similiar applications that sometimes these doesn't time out properly, and eventually they end up blocking all the threads. Unfortunately I don't have any good solutions here. A few useful classes as a starting point: <http://java.sun.com/javase/6/docs/api/java/lang/Thread.html> <http://java.sun.com/javase/6/docs/api/java/lang/ThreadGroup.html> <http://java.sun.com/javase/6/docs/api/java/net/URL.html> <http://java.sun.com/javase/6/docs/api/java/net/HttpURLConnection.html>
Java concurrent recursive website download
[ "", "java", "concurrency", "" ]
Each time I use `Runtime.exec("cmd /c start....")` I am opening a cmd window. I would like to create a more seamless application by closing each previous cmd window. How can I do this? If anyone knows of a better way to run a series of commands in the same cmd window rather than opening new ones each time I execute a command, please let me know.
You cannot control the opened windows from Java. But I suggest two solutions for you: **First**: ``` Runtime.exec("cmd /c start /MIN ...") ``` The /MIN parameter will prevent windows from appearing. **Second**: put all the applications you must call inside the same batch file and call it once. :-)
Don't use start, that opens another window Replace: ``` Runtime.exec("cmd /c start....") ``` with: ``` Runtime.exec("cmd /c ....") ```
How to close command windows with Java
[ "", "java", "window", "command", "runtime.exec", "" ]
I have a table with an `IntegerField` (`hit_count`), and when a page is visited (for example, `http://site/page/3`) I want record ID 3's `hit_count` column in the database to increment by 1. The query should be like: ``` update table set hit_count = hit_count + 1 where id = 3 ``` Can I do this with the standard Django Model conventions? Or should I just write the query by hand?
If you use Django 1.1+, just use [F expressions](http://docs.djangoproject.com/en/dev/topics/db/queries/#filters-can-reference-fields-on-the-model): ``` from django.db.models import F ... MyModel.objects.filter(id=...).update(hit_count=F('hit_count')+1) ``` This will perform a single atomic database query. As gerdemb says, you should consider putting this in a middleware to make it easily reusable so it doesn't clutter up all your views. ---
As gerdemb says, you should write it into a middleware to make it really reusable. Or (simpler) write a function decorator. In fact, there are adaptors to use a middleware as a decorator and viceversa. But if you're worried about performance and want to keep the DB queries per page hit low, you can use memcached's atomic increment operation. of course, in this case, you have to take care of persistence yourself.
Increment Page Hit Count in Django
[ "", "python", "django", "django-models", "" ]
In my code I have to do a lot of distance calculation between pairs of lat/long values. the code looks like this: ``` double result = Math.Acos(Math.Sin(lat2rad) * Math.Sin(lat1rad) + Math.Cos(lat2rad) * Math.Cos(lat1rad) * Math.Cos(lon2rad - lon1rad)); ``` (lat2rad e.g. is latitude converted to radians). I have identified this function as the performance bottleneck of my application. Is there any way to improve this? (I cannot use look-up tables since the coordinates are varying). I have also looked at [this question](https://stackoverflow.com/questions/516574/how-can-i-do-efficient-range-searching-counting-with-latitude-longitude-data) where a lookup scheme like a grid is suggested, which might be a possibility. Thanks for your time! ;-)
**If your goal is to rank (compare) distances**, then approximations (`sin` and `cos` table lookups) could drastically reduce your amount of computations required (implement **quick reject**.) Your goal is to only proceed with the actual trigonometric computation if the difference between the approximated distances (to be ranked or compared) falls below a certain threshold. E.g. using lookup tables with 1000 samples (i.e. `sin` and `cos` sampled every `2*pi/1000`), the lookup uncertainty is at most 0.006284. Using [uncertainty calculation](http://spiff.rit.edu/classes/phys273/uncert/uncert.html) for the parameter to `ACos`, the cumulated uncertainty, also be the threshold uncertainty, will be at most 0.018731. So, if evaluating `Math.Sin(lat2rad) * Math.Sin(lat1rad) + Math.Cos(lat2rad) * Math.Cos(lat1rad) * Math.Cos(lon2rad - lon1rad)` using `sin` and `cos` lookup tables for two coordinate-set pairs (distances) yields a certain ranking (one distance appears greater than the other based on the approximation), and the difference's modulus is greater than the threshold above, then the approximation is valid. Otherwise proceed with the actual trigonometric calculation.
Would the [CORDIC](http://en.wikipedia.org/wiki/CORDIC) algorithm work for you (in regards to speed/accuracy)?
Optimization of a distance calculation function
[ "", "c#", "geolocation", "" ]
I am looking to do a presentation at work to our development team. I was wondering if their is any new tool which would be easy to demonstrate. It is just an after work thing for talking about new technologies. Thanks
[historical debugging](http://channel9.msdn.com/posts/VisualStudio/Historical-Debugger-and-Test-Impact-Analysis-in-Visual-Studio-Team-System-2010/). is implemented in VS.net version 10. can't wait until this makes it to the java platform. introduces by the end of 2008, but this is recent enough, methinks.
I would say, the biggest thing in 2009 so far, and probably for the whole year, has been the [release](http://GBracha.BlogSpot.Com/2009/02/newspeak-prototype-escapes-into-wild.html) of the [prototype](http://NewspeakLanguage.Org/downloads/) of [Gilad Bracha](http://GBracha.BlogSpot.Com/)'s [Newspeak Programming Language](http://NewspeakLanguage.Org/), and its accompanying [GUI Framework Brazil](http://Blog.3plus4.Org/2008/05/08/which-is-which-in-newspeak-ui-brazil/), the [Application Development Framework Hopscotch](http://Blog.3plus4.Org/2008/06/20/which-is-which-in-newspeak-ui-hopscotch/) and the [Hopscotch IDE and debugger](http://GBracha.BlogSpot.Com/2008/11/dynamic-ides-for-dynamic-languages.html).
What's the best new development tool of 2009?
[ "", "java", "sql-server", "vb.net", "developer-tools", "" ]
I'm trying to get simple encryption/decryption working with AesManaged, but I keep getting an exception when trying to close the decryption stream. The string here gets encrypted and decrypted correctly, and then I get the CryptographicException "Padding was invalid and cannot be removed" after Console.WriteLine prints the correct string. Any ideas? ``` MemoryStream ms = new MemoryStream(); byte[] rawPlaintext = Encoding.Unicode.GetBytes("This is annoying!"); using (Aes aes = new AesManaged()) { aes.Padding = PaddingMode.PKCS7; aes.Key = new byte[128/8]; aes.IV = new byte[128/8]; using (CryptoStream cs = new CryptoStream(ms, aes.CreateEncryptor(), CryptoStreamMode.Write)) { cs.Write(rawPlaintext, 0, rawPlaintext.Length); cs.FlushFinalBlock(); } ms = new MemoryStream(ms.GetBuffer()); using (CryptoStream cs = new CryptoStream(ms, aes.CreateDecryptor(), CryptoStreamMode.Read)) { byte[] rawData = new byte[rawPlaintext.Length]; int len = cs.Read(rawData, 0, rawPlaintext.Length); string s = Encoding.Unicode.GetString(rawData); Console.WriteLine(s); } } ```
The trick is to use `MemoryStream.ToArray()`. I also changed your code so that it uses the `CryptoStream` to Write, in both encrypting and decrypting. And you don't need to call `CryptoStream.FlushFinalBlock()` explicitly, because you have it in a `using()` statement, and that flush will happen on `Dispose()`. The following works for me. ``` byte[] rawPlaintext = System.Text.Encoding.Unicode.GetBytes("This is all clear now!"); using (Aes aes = new AesManaged()) { aes.Padding = PaddingMode.PKCS7; aes.KeySize = 128; // in bits aes.Key = new byte[128/8]; // 16 bytes for 128 bit encryption aes.IV = new byte[128/8]; // AES needs a 16-byte IV // Should set Key and IV here. Good approach: derive them from // a password via Cryptography.Rfc2898DeriveBytes byte[] cipherText= null; byte[] plainText= null; using (MemoryStream ms = new MemoryStream()) { using (CryptoStream cs = new CryptoStream(ms, aes.CreateEncryptor(), CryptoStreamMode.Write)) { cs.Write(rawPlaintext, 0, rawPlaintext.Length); } cipherText= ms.ToArray(); } using (MemoryStream ms = new MemoryStream()) { using (CryptoStream cs = new CryptoStream(ms, aes.CreateDecryptor(), CryptoStreamMode.Write)) { cs.Write(cipherText, 0, cipherText.Length); } plainText = ms.ToArray(); } string s = System.Text.Encoding.Unicode.GetString(plainText); Console.WriteLine(s); } ``` Also, I guess you know you will want to explicitly set the [Mode](http://msdn.microsoft.com/en-us/library/system.security.cryptography.aesmanaged.mode.aspx) of the AesManaged instance, and use [System.Security.Cryptography.Rfc2898DeriveBytes](http://msdn.microsoft.com/en-us/library/system.security.cryptography.rfc2898derivebytes.aspx) to derive the Key and IV from a password and salt. see also: - [AesManaged](http://msdn.microsoft.com/en-us/library/system.security.cryptography.aesmanaged.aspx)
This exception can be caused by a mismatch of any one of a number of encryption parameters. I used the [Security.Cryptography.Debug](https://github.com/microsoftarchive/clrsecurity/blob/7250c56ccfd40413e68af755e3de40d00c673431/Wiki/Security.Cryptography.Debug.dll.md) interface to trace all parameters used in the encrypt/decrypt methods. Finally I found out that my problem was that I set the `KeySize` property after setting the `Key` causing the class to regenerate a random key and not using the key that I was initially set up.
"Padding is invalid and cannot be removed" using AesManaged
[ "", "c#", ".net", "encryption", "" ]
Where do you seen using Scala for your project?
I thought about using Scala in my project (trading server software — I especially like its Erlang-style actor model), but Scala still has some performance problems (I hope they will fix it soon). Otherwise, it's good (getting decent IDE support in IntelliJ IDEA). I reimplemented vital parts of Scala actor model in Java, though. It works.
Well recently I looked at Scala programming language and my impressions were pretty similar to what I have for other functional programming languages. Scala does some stuff really well but it doesn't mean that I would choose it as my primary programming language in a project. It is terse and good for concurrency and hence I would like to use it for implementing a part of project where it suits well. For example take Twitter. They were having scalability issues because their message queue in Ruby wasn't able to provide them with the required throughput - the primary reason being the way threading is implemented in Ruby and its GC. A very good interview to read is <http://www.artima.com/scalazine/articles/twitter_on_scala.html>. The Twitter developers talk about why they chose Scala and what issues did they face and why they feel that it was only suited to a part of their whole application stack.
Do you plan to use the Scala programming language and on what project?
[ "", "java", "scala", "jvm", "" ]
In my web project's business object editor page, I'm sending a notification email to the administrator after an object insert or update. But instead of sending a plain text mail, i want to send the html output of another aspx page(Notification.aspx) i simply prepared for this purpose. First i thought, I can create an instance of Notification.aspx then use it's RenderControl method for getting the output. However, in the codebehind of Editor.aspx page, i can't even reach the Notification's reference to create a new instance. I wonder what is the best practice for loading and rendering a page in another one... Thanks.
You can render a page by doing this: ``` StringWriter _writer = new StringWriter(); HttpContext.Current.Server.Execute("MyPage.aspx", _writer); string html = _writer.ToString(); ```
See this question/answer: [Can I set up HTML/Email Templates in C# on ASP.NET?](https://stackoverflow.com/questions/620265/can-i-set-up-html-email-templates-in-c-on-asp-net/620337#620337). Mark Brackett has what you're looking for, though there's a lot of other helpful advice there as well.
rendering an aspx page in another one
[ "", "c#", "asp.net", "rendering", "" ]
G'day all, I have an application which needs to display an ASCII file of 15 lines in a Swing component that cannot be edited by the user. Below is my code which reads the ASCII file byte by byte. My thanks to the helpful commenters who explained that a JTextArea.setEditable(false) would be appropriate in Swing. However, my code merely displays a string of numbers, when I personally made the ASCII file to be something quite different. Does anyone know what I am doing wrong and how to get the ASCII characters themselves to display? ``` import java.io.*; import javax.swing.*; public class LoadMap extends JFrame { public LoadMap() throws IOException { FileInputStream fIn = new FileInputStream("map.srn"); BufferedReader rd = new BufferedReader(new InputStreamReader(fIn, "US-ASCII")); String map = ""; JTextArea mapArea = new JTextArea(15, 50); try { int c; while ((c = rd.read()) != -1) { map= map + c; } } finally { if (rd != null) { rd.close(); } } mapArea.setText(map); mapArea.setEditable(false); add(mapArea); pack(); setVisible(true); } } ```
Here: ``` String map = ""; int c; while ((c = rd.read()) != -1) { map= map + c; } ``` What you're doing it appending int's to the string. You should cast them to char instead. ``` int c; while ((c = rd.read()) != -1) { map= map + ( char ) c; } ``` You can see much better patterns in these questions. [How do I create a Java string from the contents of a file?](https://stackoverflow.com/questions/326390/how-to-create-a-java-string-from-the-contents-of-a-file) <https://stackoverflow.com/questions/181634/simplest-efficient-ways-to-read-binary-and-ascii-files-to-string-or-similar-in-v/324792#324792> ( see java part )
Use a JTextArea and call ``` setEditable(false); ``` to stop the user being able to edit the data I've just read your code through and realise that's not a comprehensive enough answer. You can't do "+" on a label. What you need to do is read the text in first and store it somewhere, then call ``` setText(yourTextAsString); ``` on your text component on screen (for which I'd still use the JTextArea), and you need to add the text area to the frame, so your code would look something like: ``` public LoadMap() { String data = // read your data JTextArea textArea = new JTextArea(); textArea.setText(data); textArea.setEditable(false); setLayout(new GridLayout()); add(textArea); pack(); setVisible(true); } ``` I would suggest reading the [Swing tutorial](http://java.sun.com/docs/books/tutorial/uiswing/) to get some more info on using Swing components
Java newbie: Swing and displaying ASCII files
[ "", "java", "swing", "file", "ascii", "" ]
I'm working on a project wich requires a tree of categories, organized as id, parent, title table. Which are the best ways to retrieve category and its subcategories(and a full tree, if root categories have parent=0) in Postgres? I'm looking for a pure database solution, but if there is a way for Ruby and PHP - it will be great too. The main goal is speed of select clauses, 'cause data in this table is not critical for update/insert/delete speed. UPD: there will be also path searching, i mean path from current vertex(category) to root category.
> retrieve category and its subcategories If you only have a limited depth of subitems, you can do this using a self-join, eg. two levels deep: ``` SELECT * FROM categories AS child LEFT JOIN categories AS parent ON parent.id=child.parent LEFT JOIN categories AS grandparent ON grandparent.id=parent.parent WHERE child.id=(id) OR parent.id=(id) OR grandparent.id=(id); ``` You can't do this for an arbitrary-depth hierarchy using standard SQL over a ‘parent-id-foreign-key’ type schema. Some DBMSs provide non-standard hierarchical tools that allow something like this in various ways, but if you want to stick to cross-DBMS-compatible code you'll need to rejig your schema to one of the better models of representing hierarchies. The two popular ones are: * [Nested Set](http://mikehillyer.com/articles/managing-hierarchical-data-in-mysql/). Stores a linear ordering representing a depth-first search of the tree in two columns of the target table (one of which you'll already have if your target has explicit ordering). * [Adjacency Relation](http://vadimtropashko.wordpress.com/nested-sets-and-relational-division/). Stores each ancestor/descendent pair in a separate join table. There are advantages and disadvantages to each approach, and numerous variants (eg. sparse nested set numbering, ‘distance’ in AR) which can affect how expensive various types of add/delete/move-position operations are. Personally I tend to gravitate towards a simplified nested set model by default as it contains less redundancy than AR.
I've been playing around with **[ltree](http://www.postgresql.org/docs/current/static/ltree.html)**, which is a PostgreSQL contrib module to see if it is a good fit for threaded comments. You create a column in your table that stores the path and create an ltree index on it.. You can then perform queries like this: ``` ltreetest=# select path from test where path ~ '*.Astronomy.*'; path ----------------------------------------------- Top.Science.Astronomy Top.Science.Astronomy.Astrophysics Top.Science.Astronomy.Cosmology Top.Collections.Pictures.Astronomy Top.Collections.Pictures.Astronomy.Stars Top.Collections.Pictures.Astronomy.Galaxies Top.Collections.Pictures.Astronomy.Astronauts ``` I haven't played around with it enough to determine how well it performs with things like inserts, updates or deletes. I assume a delete would look like: ``` DELETE FROM test WHERE path ~ '*.Astronomy.*'; ``` I'm thinking, a threaded comment table might look like: ``` CREATE SEQUENCE comment_id_seq INCREMENT 1 MINVALUE 1 MAXVALUE 9223372036854775807 START 78616 CACHE 1; CREATE TABLE comments ( comment_id int PRIMARY KEY, path ltree, comment text ); CREATE INDEX comments_path_idx ON comments USING gist (path); ``` An insert would crudely (and untested-ly) look like: ``` CREATE FUNCTION busted_add_comment(text the_comment, int parent_comment_id) RETURNS void AS $BODY$ DECLARE INT _new_comment_id; -- our new comment_id TEXT _parent_path; -- the parent path BEGIN _new_comment_id := nextval('comment_id_seq'::regclass); SELECT path INTO _parent_path FROM comments WHERE comment_id = parent_comment_id; -- this is probably busted SQL, but you get the idea... this comment's path looks like -- the.parent.path.US -- -- eg (if parent_comment_id was 5 and our new comment_id is 43): -- 3.5.43 INSERT INTO comments (comment_id, comment, path) VALUES (_new_comment_id, the_comment, CONCAT(_parent_path, '.', _new_comment_id)); END; $BODY$ LANGUAGE 'plpgsql' VOLATILE; ``` Or something. Basically the path is just a hierarchy made up of all the primary keys.
PostgreSQL - tree organization
[ "", "php", "ruby", "postgresql", "search", "tree", "" ]