Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
I'm trying to add a script reference to jQuery in my master page so that it will work for any page. It currently looks like this ``` <script type="text/javascript" src="jquery.js"></script> ``` The problem is that the path is always relative to the executing aspx page so this will only work if the "jquery.js" file is located in the same folder. To make it work I have to change the line to: ``` <script type="text/javascript" src="../../jquery.js"></script> ``` This is obviously less than ideal because it will only work for pages that are two levels deep from the root folder. If I try the following, IIS throws an error about an unexpected character. ``` <script runat="server" type="text/javascript" src="~/jquery.js"></script> ``` Any ideas? **EDIT:** I forgot to mention as well that the script MUST be in the head tag The current top answer throws a "*ASP.NET Ajax client-side framework failed to load.*" error when I add it to my master page. Its thrown from javascript and not the .Net compiler. If I move the ScriptManager to the head section where it should be I get a compile error about the ScriptManager needing to be inside a form tag. The third answer throws a "*Illegal characters in path.*" exception from the compiler **EDIT 2:** When I add that line to my head tag I get this error from IIS. *The Controls collection cannot be modified because the control contains code blocks (i.e. <% ... %>)* **SOLVED:** I took the edited response from the answer below and put it inside an *asp:ContentPlaceHolder* element
You could use a [`ScriptManager`](http://msdn.microsoft.com/en-us/library/system.web.ui.scriptmanager.aspx): ``` <asp:ScriptManager ID="ScriptManager1" runat="server"> <Scripts> <asp:ScriptReference Path="~/jquery.js" /> </Scripts> </asp:ScriptManager> ``` **EDIT:** If you *absolutely* need this in your `<head>` section, you could do something like: ``` <head> <script type="text/javascript" src="<%= Page.ResolveClientUrl("~/jquery.js") %>"></script> </head> ``` **EDIT 2:** According to the comments, if you are observing that > The Controls collection cannot be modified because the control contains code blocks (i.e. <% ... %>) you may need to change the above to use the data-binding syntax: ``` <head> <script type="text/javascript" src="<%# Page.ResolveClientUrl("~/jquery.js") %>"></script> </head> ```
Try `<%#` instead of `<%=` in Master page under head section ``` <script type="text/javascript" src="<%# ResolveUrl("~/YourScriptFolder/YourJQueryOrJavascript.js") %>"> </script> ``` Then in Code Behind of Master page under `Page_Load` Event ``` Page.Header.DataBind(); ``` Now you are good to go with either jQuery and JavaScript as well as CSS just you need to change your path in `ResolveUrl` which file you want to handle CSS, JavaScript, jQuery.
ASP.Net Master Page and File path issues
[ "", "asp.net", "javascript", "jquery", "runatserver", "" ]
I want to build a date widget for a form, which has a select list of months, days, years. since the list is different based on the month and year, i cant hard code it to 31 days. (e.g february has 28 days not 30 or 31 and some years even 29 days) How can I use the calendar or [joda](http://www.joda.org/joda-time/) object to build me these lists.
I *strongly* recommend that you avoid the built-in date and time APIs in Java. Instead, use [Joda Time](http://www.joda.org/joda-time/). This library is similar to the one which will (hopefully!) make it into Java 7, and is much more pleasant to use than the built-in API. Now, is the basic problem that you want to know the number of days in a particular month? EDIT: Here's the code (with a sample): ``` import org.joda.time.*; import org.joda.time.chrono.*; public class Test { public static void main(String[] args) { System.out.println(getDaysInMonth(2009, 2)); } public static int getDaysInMonth(int year, int month) { // If you want to use a different calendar system (e.g. Coptic) // this is the code to change. Chronology chrono = ISOChronology.getInstance(); DateTimeField dayField = chrono.dayOfMonth(); LocalDate monthDate = new LocalDate(year, month, 1); return dayField.getMaximumValue(monthDate); } } ```
# tl;dr ``` int lengthOfMonth = YearMonth.from( LocalDate.now( ZoneId.of( "America/Montreal" ) ) ) .lengthOfMonth() ; ``` # java.time The [Answer by Jon Skeet](https://stackoverflow.com/a/668113/642706) is correct but now outdated. The [Joda-Time](http://www.joda.org/joda-time/) project is now in maintenance mode, with the team advising migration to the java.time classes. ## `LocalDate` The code in java.time is similar to that of [Joda-Time](http://www.joda.org/joda-time/), with a `LocalDate` class. The [`LocalDate`](https://docs.oracle.com/javase/8/docs/api/java/time/LocalDate.html) class represents a date-only value without time-of-day and without time zone. A time zone is crucial in determining a date. For any given moment, the date varies around the globe by zone. For example, a few minutes after midnight in [Paris France](https://en.wikipedia.org/wiki/Europe/Paris) is a new day while still “yesterday” in [Montréal Québec](https://en.wikipedia.org/wiki/America/Montreal). ``` ZoneId z = ZoneId.of( “America/Montreal” ); LocalDate today = LocalDate.now( z ); ``` You may interrogate for each part, year number, month, etc. Note that months are number sanely, 1-12 for January-December (unlike in the legacy classes). ``` int year = today.getYear(); int monthNumber = today.getMonthValue(); // 1-12 for January-December. int dayOfMonth = today.getDayOfMonth(); ``` You can assemble a `LocalDate` object from those parts. ``` LocalDate ld = LocalDate.of( year , monthNumber , dayOfMonth ); ``` ## `YearMonth` To ask for the [length of the month](http://docs.oracle.com/javase/8/docs/api/java/time/YearMonth.html#lengthOfMonth--), use the [`YearMonth`](http://docs.oracle.com/javase/8/docs/api/java/time/YearMonth.html) class. ``` YearMonth ym = YearMonth.from( ld ); int lengthOfMonth = ym.lengthOfMonth(); ``` # About java.time The [java.time](http://docs.oracle.com/javase/8/docs/api/java/time/package-summary.html) framework is built into Java 8 and later. These classes supplant the troublesome old date-time classes such as [`java.util.Date`](https://docs.oracle.com/javase/8/docs/api/java/util/Date.html), [`.Calendar`](https://docs.oracle.com/javase/8/docs/api/java/util/Calendar.html), & [`java.text.SimpleDateFormat`](http://docs.oracle.com/javase/8/docs/api/java/text/SimpleDateFormat.html). The [Joda-Time](http://www.joda.org/joda-time/) project, now in [maintenance mode](https://en.wikipedia.org/wiki/Maintenance_mode), advises migration to java.time. To learn more, see the [Oracle Tutorial](http://docs.oracle.com/javase/tutorial/datetime/TOC.html). And search Stack Overflow for many examples and explanations. Much of the java.time functionality is back-ported to Java 6 & 7 in [ThreeTen-Backport](http://www.threeten.org/threetenbp/) and further adapted to [Android](https://en.wikipedia.org/wiki/Android_(operating_system)) in [ThreeTenABP](https://github.com/JakeWharton/ThreeTenABP) (see [*How to use…*](https://stackoverflow.com/q/38922754/642706)). The [ThreeTen-Extra](http://www.threeten.org/threeten-extra/) project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as [`Interval`](http://www.threeten.org/threeten-extra/apidocs/org/threeten/extra/Interval.html), [`YearWeek`](http://www.threeten.org/threeten-extra/apidocs/org/threeten/extra/YearWeek.html), [`YearQuarter`](http://www.threeten.org/threeten-extra/apidocs/org/threeten/extra/YearQuarter.html), and [more](http://www.threeten.org/threeten-extra/apidocs/index.html).
How can I build a list of days, months, years from a calendar object in Java?
[ "", "java", "forms", "date", "calendar", "" ]
Is a long 128 bits on a 64 bit machine? **Edit:** Duplicate question; see [sizeof(int) on x64?](https://stackoverflow.com/questions/651956/sizeofint-on-x64).
On both 32-bit and 64-bit machines: * `long` is 64-bit, it's a synonym for `System.Int64`. * `int` is 32-bit, it's a synonym for `System.Int32`.
Nope ... 64 bits
long on a 64 bit machine
[ "", "c#", ".net", "types", "" ]
Is there a way to tell the compiler (g++ in my case) to **not** optimize certain code away, even if that code is not reachable? I just want those symbols in the object file. Example: Here is a simple function, and I do want this function to be compiled, even if it's never called. ``` void foo(){ Foo<int> v; } ``` If there is no official compiler directive, is there a trick to make the compiler think that it's an important function? Or at least make it think that it can't safely be ignored? I tried something like this: ``` extern bool bar; void foo(){ if(bar){ Foo<int> v; } } ``` but that didn't seem to do it. (If you really want to know why I on earth would want that -- it has to do with [this](https://stackoverflow.com/questions/555330/templates-use-forward-declarations-to-reduce-compile-time) question, where, instead of explicit template instantiation with `template class Foo<int>` I simply want to be able to write `Foo<int> v`, since in many cases that's easier since it implicitly instantiates all functions needed, and it does work fine in debug mode without optimizations ...) **UPDATE:** Here is what I want to do (as a compilable mini example): **foo.h** (such files are given to me and not changeable) ``` template<class T> struct Foo { T val_; Foo(T val) : val_(val) { // heavy code, long compile times } }; ``` **foo-instantiation.cpp** ``` #include "foo.h" void neverCalled() { Foo<int> f(1); } // The standard way to instantiate it is this: // template class Foo<int>; // but in reality it is often hard to find out // exactly what types I have to declare. // Usage like Foo<int> f(1); will instantiate all // dependent types if necessary. ``` **foo-decl.h** (an interface that I extracted from foo.h) ``` template<class T> struct Foo { T val_; Foo(T val); // no heavy code, can include anywhere and compile fast }; ``` **main.cpp** ``` #include <iostream> #include "foo-decl.h" int main(int argc, char** argv){ Foo<int> foo(1); return 0; } ``` **Compilation (no optimization)** ``` g++ -c main.cpp g++ -c foo-instantiation.cpp g++ main.o foo-instantiation.oo ``` **Compilation (optimization)** ``` g++ -O2 -c main.cpp g++ -O2 -c foo-instantiation.cpp g++ main.o foo-instantiation.oo main.o(.text+0x13): In function `main': : undefined reference to `Foo<int>::Foo(int)' collect2: ld returned 1 exit status ``` * I tried precompiled headers instead, but the template instantiation method makes for much faster compilation. * Compiling `foo-instantiation.cpp` without optimization is not so ideal because then the library code (`foo.h` and others) will run slower.
You are running into the One Definition Rule. In one file you have a definition: ``` template<class T> struct Foo { T val_; Foo(T val) : val_(val) { // heavy code, long compile times } }; ``` and in another a different definition: ``` template<class T> struct Foo { T val_; Foo(T val); // no heavy code, can include anywhere and compile fast }; ``` This is explicitly not allowed in C++ (only one identical definition allowed) and if you break the rule your code may well seem to work sometimes, but what you actually have is the dreaded "undefined behaviour" - anything may happen depending on the phase of the moon (but more likely the internal state of the compiler at certain critical junctures). Basically, you can't write code like that - sorry.
The **compiler** cannot optimise a function body away, whether you declare it **extern** or not, because it cannot know that the function is not called from another compilation unit. It could optimise it away if you declared it **static**, but I don;t believe any compilers actually do this. The compiler *can* optimise away function calls: ``` while(false) { foo(); } ``` In the above the call to foo() can be elided. OTOH, the **linker** can remove function bodies from the final excecutable if they are not called. For the above and other reasons, we really need to see some real code in order to diagnose your problem.
How to tell compiler to NOT optimize certain code away?
[ "", "c++", "optimization", "templates", "compiler-construction", "function", "" ]
Consider the following ``` if(!count($_POST)) { echo 'something'; } if(empty($_POST)) { echo 'something'; } if(!$_POST) { echo 'something'; } ``` Each line above pretty much do the same thing. I haven't been particular about which one I use. Should I be more particular? Does it really matter?
I would use this: ``` if ($_SERVER['REQUEST_METHOD'] == 'POST') { // POST request } ```
If you want to test if the request was made using a POST request, then checking $\_SERVER['request\_method'] is the way to go. If you want to find out if an array is empty, there are some differences: * empty() Empty will check if a variable is "empty". PHP considers the following values to be empty: ``` * "" (an empty string) * 0 (0 as an integer) * "0" (0 as a string) * NULL * FALSE * array() (an empty array) * var $var; (a variable declared, but without a value in a class) ``` Empty is a language construct, which means you can't use it as a callback, so the following will fail: ``` $var = array(); call_user_func('empty', $var); ``` It also only checks variables, so the following will fail with a fatal too: ``` if (empty(array()) { // do something } ``` It is also faster than count, but this shouldn't make you consider it over the others. * count() Count is a "normal" function, it will first cast the parameter to an array, and check if it is empty. Personally I would use this to check empty arrays. * if ($value) { // do something } This differs a little from count, because $value here will be cast to a boolean, and because empty arrays cast to false, it will achieve the same result as count. There is a very big gotcha involved because of casting: ``` $var = ''; // empty string var_dump(empty($var)); // returns true var_dump(count($var)); // returns false ```
PHP - Best practices evaluating IF statement
[ "", "php", "if-statement", "" ]
What is the difference between add your imports inside the NameSpace or Outside. Is there a difference in the way assemblies are loaded? ``` Using System; namespace test { } VS namespace test { using System; } ```
Putting the the using statement inside the namespace makes it local to that namespace, outside the namespace means anything in the file can reference it. The complier will always search the inner most namespace first. Stylecop promotes putting the "using" statement inside the namespace and Microsoft claims that placing the using statement inside the namespace allows the CLR to lazy load at runtime. However there is a number of tests that have [questioned this](http://www.hanselman.com/blog/BackToBasicsDoNamespaceUsingDirectivesAffectAssemblyLoading.aspx). ``` Using System; namespace test { //Can Ref System } namespace test2 { using System2; //can Reference anything from test2, System2 and System //will look for a reference in test, then System2 then System } ```
Nope. `using` directive is absolutely a compile time thing. It will *not* affect the runtime behavior in anyway. It just help you not write the long fully qualified type names.
using Namespaces and Loading
[ "", "c#", "" ]
This behavior is so bizarre that I don't even know how best to ask the question. Given the following C# code snippet: ``` public class Foo { private bool _value = true; // ... protected void Method() { _value = true; if(!_value) { throw new Exception("What the...?!?!"); } } } ``` Attaching the Visual Studio debugger to an application executing a version of this code and stepping through the execution of `Method()` (using step into or step over), the `if` block is evaluated and the exception is thrown. Setting a watch on the `_value` variable, I can see that the value of `_value` is `false` at the beginning of the method and does not change as I step over/into the assignment statement. More interestingly, the exception is *not* thrown if I Continue execution (F5), though things still aren't working correctly. I came across this when trying to figure out why NUnit test cases were working when run using ReSharper from within visual studio, but fail when run within the the NUnit GUI. I attached the debugger to the NUnit GUI, set some breakpoints on the tests that were unexpectedly failing, found places where variables weren't being set properly which should be set based on the above-mentioned `_value` variable which is somewhat of a flag indicating whether stuff is dirty or not), and thus noticed the strange behavior where `_value` wasn't changing (the exception throwing thing was added later and verifies I was using the right compiled assemblies!). So, how about it? What could possibly explain the above-mentioned behavior?
Since the exception isn't actually thrown in some scenario's I think this is a case of the debugger looking at the wrong source or wrong version.
Look if any property getters changes `_value`. The debugger will evaluate properties and thus your value may get changed.
Under what circumstances can an assignment in C# not change a variable's value?
[ "", "c#", "visual-studio", "debugging", "" ]
C#, .NET 3.5 This just smells of ugly to me, but I can't think of another way. Given a string with the format of "Joe Smith (jsmith)" (sans quotes), I'd like to parse out just the 'jsmith' string within the parenthesis. I've come up with this: ``` private static string DecipherUserName( string user ) { if( !user.Contains( "(" ) ) return user; int start = user.IndexOf( "(" ); return user.Substring( start ).Replace( "(", string.Empty ).Replace( ")", string.Empty ); } ``` Other than my (un)healthy aversion to RegEx, is there a simpler way to parse out the substring? **Edit:** To clarify, the string to parse will always be of: "Joe Smith (jsmith)" (sans quotes).
You shouldn't need the first replace since you can just add 1 to the "(" position. ``` private static string DecipherUserName (string user) { int start = user.IndexOf( "(" ); if (start == -1) return user; return user.Substring (start+1).Replace( ")", string.Empty ); } ```
Regexes are so useful that you'll save yourself a ton of heartache biting the bullet and learning them. Not the whole shebang, just the basics. One regex that'll work is "\w+\((.\*)\)" - jsmith would be in Match.Groups[1]. One easy way to pick up regexes is to find a website that'll let you type in a regex and some text then spit out the matches...
Parsing a string in C#; is there a cleaner way?
[ "", "c#", ".net", "parsing", "" ]
Does everything in a single namespace compile into its own assembly?
No, you can have multiple namespaces within an assembly. In VS terms, you can think of an assembly as a project. Each project within a solution, gets compiled into it's own assembly. Within an assembly though, you can have multiple namespaces.
No. You can have several namespaces in an assembly, and you can use the same namespace in different assemblies.
Assemblies and Namespace
[ "", "c#", ".net", "" ]
I have a query roughly like this: ``` select * from A_TABLE where A_COLUMN = '&aVariable' union select * from A_TABLE where B_COLUMN = '&aVariable'; ``` But when I run it, SQL Developer prompts me for the variable twice, even though it's the same variable. If there's a way to make it prompt only once for a variable that is used twice, how do I do it? I do **not** want to use a script, it must be a single executable query.
As I was forming this post, I figured out how to do it: ``` :a_var select * from A_TABLE where A_COLUMN = :a_var union select * from A_TABLE where B_COLUMN = :a_var; ``` SQL Developer will then prompt for a bind variable, you can enter it and hit apply.
``` select * from A_TABLE where A_COLUMN = '&aVariable' union select * from A_TABLE where B_COLUMN = '&&aVariable'; ``` Notice how the 2nd (and subsequent) variables will use double-ampersand (&&)
How can I make SQL Developer/SQL+ prompt only once for a substitution variable that occurs multiple times in a single statement?
[ "", "sql", "plsql", "variables", "substitution", "" ]
Many people here are probably familiar with one of [Joel Spolsky](http://www.joelonsoftware.com/) most popular blog posts, [Please Sir, May I Have a Linker](http://www.joelonsoftware.com/articles/PleaseLinker.html), where he cries out for a way to remove dependencies on the .NET framework so a stand-alone application can be developed and sold. [Jason Zander](http://blogs.msdn.com/jasonz/) of the Visual Studio development team, at the time, replied [with his views on the topic](http://blogs.msdn.com/jasonz/archive/2004/01/31/65653.aspx), arguing that the topic is somewhat moot - the ability to fix security problems in the runtime (among other points) was their chief concern. Overall, the small overhead was worth it. Fast forward to 2009. There's a few groups out there now claiming to have C# linkers. (Jason Zander even said himself that it wouldn't take much to implement one.) Instead of the cute, dozen-so meg download of .NET 1.0, we now have a massive 200-300 mb cross-platform complete .NET 3.5 installer that contains versions of .NET for x86, x64, and ia64. Microsoft's suggestions to decrease the runtime size include: * Unpack the redistributable, remove the target platforms you don't want, and put it back together * Use the web bootstrapper that only downloads the libraries for your platform * Use the Client Profile installer (new as of late 2008) which has limited libraries and only works for x86 To make matters worse, as I understand it (please correct me if I'm wrong) the client profile don't even register with windows as having .NET 3.5 installed. This means if multiple .NET 3.5 client applications are installed on the computer, none will see each other and the runtime will be re-installed again and again! I really don't know what Microsoft is thinking here. Even assuming the worst case install will be for one target platform (eg, x64) and only those libraries need to be included, you're still looking at upwards of 60 mb overhead on your app. Even one of the most well known .NET apps, Paint.NET, was fraught with [Difficulties installing the application because of the massive .NET dependencies.](http://blog.getpaint.net/2008/08/24/the-paintnet-install-experience-part-1-version-3xx/) If THEY have problems distributing a free app, what about the rest of the world? In the end, they had to [Make a bootstrapper that installed Microsoft Installer 3.1, the .NET runtime bootstrapper, and all their other dependent libraires](http://blog.getpaint.net/2008/08/25/the-paintnet-install-experience-part-2-version-40/) before they could install their own application. So how about it. A linker. Do any good ones exist - or a tool that simply makes it possible to build a C# application without requiring that the user install the massive .NET runtime? Update: so, it looks like there's a couple of options: Mono: * [Mono has its own linker](http://www.mono-project.com/Linker). From the answer below, it looks like it works pretty well. .NET: * [Xenocode](http://www.xenocode.com/) seems to be one that's available and works. * [Thinstall](http://www.thinstall.com/) is another that was recommended, and it's by VMware. * [There's another linker by Remotesoft](http://www.remotesoft.com/linker/). They bill it as an 'obfuscator'. Any thoughts there? * [Found another by Rustemsoft called Skater .NET Obfuscator](http://www.skaterpro.net/linking-net-dlls.html). Anyone familiar with them? * [ILmerge by Microsoft was also suggested](http://research.microsoft.com/en-us/people/mbarnett/ILMerge.aspx); this looks like it only performs part of the task (ie, merging libraries, not stripping out unused bits). It looks like the Mono tools are getting use; how about the .NET based tools? Any other experience with them, or are we just going to have to wait for Microsoft to push it 3.5 out to everyone? I shudder to think how long it'll take for .NET 4.0 to be put out...
The case of the [Mono Linker](http://mono-project.com/Linker). I can't talk much about the other pieces of software that are listed here, but as the author of the Mono Linker, I can tell what it does and what it does not. The Mono Linker is only a managed linker, so by definition, it takes assemblies, and removes what's not necessary for a program to run. It doesn't merge assemblies all together, and it doesn't make a native program out of them. There's a Mono.Merge clone of ILMerge, but it's not complete, and its author is not maintaining it. To generate a native program containing both the Mono runtime and assemblies, Mono provides the [mkbundle tool](http://www.mono-project.com/Guide:Running_Mono_Applications#Bundles). Also, as it is only a managed tool, which is altering assemblies, if you give it strong named assemblies, and that you don't have the private keys to sign them back, you'll have troubles running those assemblies. I wrote a couple of blog posts about the linker: * [A presentation of the linker](http://evain.net/blog/articles/2006/08/21/link-to-link) * [A combined used of the linker and mkbundle](http://evain.net/blog/articles/2006/08/22/linking-all-the-way-down) About our experience with the Linker. The Linker is currently used in two parts of the Mono project. It's used to generate the assembly that we distribute for people to embed our C# compiler, Mono.CSharp.dll. You can watch [Miguel's presentation](http://channel9.msdn.com/pdc2008/PC54/) at the PDC, which describes how we do that. It's pretty straightforward, and it's a basic usage of the Linker, which is a customizable tool, and it's pretty easy to write custom steps for it. A more complex use of the Linker is the way [we create our Moonlight assemblies](http://www.mono-project.com/MoonlightNotes#Assemblies). Moonlight being our implementation of Silverlight, the assemblies are a subset of the desktop assemblies. So we link our desktop assemblies to reduce their sizes, and using custom steps, we're transforming the public API to match Silverlight's. So yeah, the Linker has some pretty rough edges, such as the command line interface for instance, or the fact that you have to really know what you're doing, or you may end up with some weird assemblies, but all in all, it works really well for us.
FWIW Mono has [had a linker](http://www.mono-project.com/Linker) for quite a while. Here is an [example](https://stackoverflow.com/questions/558707/mono-mkbundle-tool-unable-to-create-binary-with-complaint-that-output-file-is-una) of how to use mkbundle.
The State of Linkers for .NET apps (aka "Please Sir, May I have a Linker" 2009 edition)
[ "", "c#", ".net", "vb.net", "mono", "linker", "" ]
How can I properly access the web browser control from within myFunct()? Main.myWebBrowserControl & Main::myWebBrowserControl don't work. ``` namespace foo{ public partial class Main : Form{ public Main(){ InitializeComponent(); // Do some things... MyFunct(); } public static void MyFunct(){ myWebBrowserControl.Navigate("http://www.google.com"); // causing an error. } } } ```
You can't access instance members from static functions, change you function declaration to ``` public void MyFunct(){ myWebBrowserControl.Navigate("http://www.google.com"); } ```
In addition to not being static (as was said above) you also have to ensure that what you're executing is on the "main thread" of the application. This is the same thread that handles events (such as handling a "click event" from the app), and so if you're calling the method from there, then you're fine, but if not, you MUST wrap an Invoke() or BeginInvoke() call around Navigate().
C# accessing form control from custom function
[ "", "c#", "winforms", "webbrowser-control", "" ]
the problem I'm facing is this: * I have a textbox for a date range along side a calendar control. * When the user selects a date from the calendar, it fills that date into the textbox * When this happens I want to fire a javascript function, however, the 'onchange' event doesn't seem to happen. I'd ideally like to be able to add the event as an attribute to the textbox, something like: ``` txtCreateDate.Attributes.Add("onchange", string.Format("JSfunction({0},'{1}');", arg1, arg2)); ``` more info: The date is entered into the textbox in c#. The calendar control has an eventhandler on the page. When a date is selected, the eventhandler puts the date into the textbox. I have tried setting the focus to the textbox at this point, then putting an onBlur attribute on the textbox, but the textbox never seems to get focus. I suppose I could directly call the javascript function at this point doing ClientScript.RegisterClientScriptBlock or something like that, but that seems sloppy and never works like I want it to.
You're misinterpreting what the onchange event does when applied to a textarea. It won't fire until it loses focus or you hit enter. Why not fire the function from an onchange on the select that fills in the text area? Check out here for more on the onchange event: [w3schools](http://www.w3schools.com/JS/js_htmldom_events.asp)
This is an old question, and I'm not sure if it will help, but I've been able to programatically fire an event using: ``` if (document.createEvent && ctrl.dispatchEvent) { var evt = document.createEvent("HTMLEvents"); evt.initEvent("change", true, true); ctrl.dispatchEvent(evt); // for DOM-compliant browsers } else if (ctrl.fireEvent) { ctrl.fireEvent("onchange"); // for IE } ```
Call Javascript onchange event by programmatically changing textbox value
[ "", "javascript", "textbox", "onchange", "" ]
I've got xampp installed on my laptop runing XP, and it's been running without any problems for ages. I've just tried installing cakephp, and have altered the database config and enabled mod\_rewrite. But now I get the following on the welcome page: > Your tmp directory is writable. > > The FileEngine is being used for > caching. To change the config edit > APP/config/core.php > > Your database configuration file is > present. > > Cake is NOT able to connect to the > database. I have no idea why it's not connecting to the database. Has anyone else ever come across this problem and have any idea how to resolve it? \*edit Advice on configuring datalogging in cake would be a great help too
First, edit `~/app/config/core.php` and raise debug to 2, this will give you more detailed error reporting. Second, triple check your `~/app/config/database.php` and be 110% sure there is no typo in there. If there is no typo, try connecting with that same data with a non-cake script. If that fails too, you might want to check Apache and MySQL log files, or even your firewall if you have one.
When using phpmyadmin to add a user for phpcake to connect with I had to set the host to `localhost` instead of `%`.
Installing cake php on xampp
[ "", "php", "mysql", "configuration", "cakephp", "xampp", "" ]
Is this the best way to include javascript on your website? <http://www.webdigi.co.uk/blog/2009/avoid-javascript-blocking-content-download-on-your-website-during-page-load/>
The best way to include JavaScript on your website is to include as few files as possible [at the *end* of the page](http://developer.yahoo.com/performance/rules.html#js_bottom)\*, after all of the markup and other assets have been loaded. Doing it that way also has the added benefit of encouraging a "[progressive enhancement](http://www.alistapart.com/articles/understandingprogressiveenhancement)" development model. \*Yahoo actively spends a great deal of money researching this and has dedicated, full-time people (including the brilliant Steve Souders) who publish their findings [online](http://developer.yahoo.com/performance/) and in [book form](https://rads.stackoverflow.com/amzn/click/com/0596529309).
Doesn't seem like a one-size-fits-all situation, so I often resort to this famous article to help me answer questions like that: <http://developer.yahoo.com/performance/rules.html>
Javascript blocking content download on your website during page
[ "", "javascript", "web", "blocking", "" ]
I have an ASP.NET web application, and I wanted to know how I could display an error message box when an exception is thrown. For example, ``` try { do something } catch { messagebox.write("error"); //[This isn't the correct syntax, just what I want to achieve] } ``` [The message box shows the error] Thank you
You can't reasonably display a message box either on the client's computer or the server. For the client's computer, you'll want to redirect to an error page with an appropriate error message, perhaps including the exception message and stack trace if you want. On the server, you'll probably want to do some logging, either to the event log or to a log file. ``` try { .... } catch (Exception ex) { this.Session["exceptionMessage"] = ex.Message; Response.Redirect( "ErrorDisplay.aspx" ); log.Write( ex.Message + ex.StackTrace ); } ``` Note that the "log" above would have to be implemented by you, perhaps using log4net or some other logging utility.
You cannot just call messagebox.write cause you are disconnected from the client. You should register javascript code that shows a messagebox: ``` this.RegisterClientScriptBlock(typeof(string), "key", string.Format("alert('{0}');", ex.Message), true); ```
How to display an error message box in a web application asp.net c#
[ "", "c#", "asp.net", "web-applications", "messagebox", "" ]
I'm importing data from a CSV that contains approx 350 columns. This CSV import is fixed and I have absolutely no control over it. If I attempt to open the CSV in Excel 2003, it only partially loads due to the column limit of 255 (IV). When I load the CSV into a DataSet using OleDb and Microsoft.Jet.OLEDB.4.0 it also only shows 255 columns. Worse still though, when attempting to access the data for some of these 255 columns it shows incorrect data and is splitting up the values incosistently. If I open the CSV in Excel, let it truncate the data and re-save it, my Import works fine. My question is, has anyone else encountered this limitation with the Jet.OLEDB provider. If yes, is there a workaround to the problem? If no, is there an alternative solution available that can load such a large CSV? Note: This is not a one off task, I need to provide an end user with a browse / upload button that performs this import as and when they need it.
We've used <http://www.codeproject.com/KB/database/CsvReader.aspx> with much success.
You can go through this code , Use [ExcelDataReader](https://exceldatareader.codeplex.com) and add reference in your project. and use below code ... ``` FileStream stream = File.Open(strFileName, FileMode.Open, FileAccess.Read); IExcelDataReader excelReader = ExcelReaderFactory.CreateOpenXmlReader(stream); DataSet result = excelReader.AsDataSet(); excelReader.Close(); return result.Tables[0]; ```
Column limitation on CSV using Microsoft Jet OLEDB
[ "", "c#", ".net", "asp.net", "csv", "oledb", "" ]
I'd like to make an http request to a remote server while properly handling cookies (eg. storing cookies sent by the server, and sending those cookies when I make subsequent requests). It'd be nice to preserve any and all cookies, but really the only one I care about is the session cookie. With java.net, it appears that the preferred way to do this is using java.net.CookieHandler (abstract base class) and java.net.CookieManager (concrete implementation). Android has java.net.CookieHandler, but it does not seem to have java.net.CookieManager. I could code it all by hand by inspecting http headers, but it seems like there must be an easier way. What is the proper way to make http requests on Android while preserving cookies?
It turns out that Google Android ships with Apache HttpClient 4.0, and I was able to figure out how to do it using the "Form based logon" example in the [HttpClient docs](https://hc.apache.org/httpcomponents-client-ga/examples.html): <https://github.com/apache/httpcomponents-client/blob/master/httpclient5/src/test/java/org/apache/hc/client5/http/examples/ClientFormLogin.java> --- ``` import java.util.ArrayList; import java.util.List; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.cookie.Cookie; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.message.BasicNameValuePair; import org.apache.http.protocol.HTTP; /** * A example that demonstrates how HttpClient APIs can be used to perform * form-based logon. */ public class ClientFormLogin { public static void main(String[] args) throws Exception { DefaultHttpClient httpclient = new DefaultHttpClient(); HttpGet httpget = new HttpGet("https://portal.sun.com/portal/dt"); HttpResponse response = httpclient.execute(httpget); HttpEntity entity = response.getEntity(); System.out.println("Login form get: " + response.getStatusLine()); if (entity != null) { entity.consumeContent(); } System.out.println("Initial set of cookies:"); List<Cookie> cookies = httpclient.getCookieStore().getCookies(); if (cookies.isEmpty()) { System.out.println("None"); } else { for (int i = 0; i < cookies.size(); i++) { System.out.println("- " + cookies.get(i).toString()); } } HttpPost httpost = new HttpPost("https://portal.sun.com/amserver/UI/Login?" + "org=self_registered_users&" + "goto=/portal/dt&" + "gotoOnFail=/portal/dt?error=true"); List <NameValuePair> nvps = new ArrayList <NameValuePair>(); nvps.add(new BasicNameValuePair("IDToken1", "username")); nvps.add(new BasicNameValuePair("IDToken2", "password")); httpost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8)); response = httpclient.execute(httpost); entity = response.getEntity(); System.out.println("Login form get: " + response.getStatusLine()); if (entity != null) { entity.consumeContent(); } System.out.println("Post logon cookies:"); cookies = httpclient.getCookieStore().getCookies(); if (cookies.isEmpty()) { System.out.println("None"); } else { for (int i = 0; i < cookies.size(); i++) { System.out.println("- " + cookies.get(i).toString()); } } // When HttpClient instance is no longer needed, // shut down the connection manager to ensure // immediate deallocation of all system resources httpclient.getConnectionManager().shutdown(); } } ```
A cookie is just another HTTP header. You can always set it while making a HTTP call with the apache library or with HTTPUrlConnection. Either way you should be able to read and set HTTP cookies in this fashion. You can read [this article](http://android-developers.blogspot.in/2011/09/androids-http-clients.html) for more information. I can share my peace of code to demonstrate how easy you can make it. ``` public static String getServerResponseByHttpGet(String url, String token) { try { HttpClient client = new DefaultHttpClient(); HttpGet get = new HttpGet(url); get.setHeader("Cookie", "PHPSESSID=" + token + ";"); Log.d(TAG, "Try to open => " + url); HttpResponse httpResponse = client.execute(get); int connectionStatusCode = httpResponse.getStatusLine().getStatusCode(); Log.d(TAG, "Connection code: " + connectionStatusCode + " for request: " + url); HttpEntity entity = httpResponse.getEntity(); String serverResponse = EntityUtils.toString(entity); Log.d(TAG, "Server response for request " + url + " => " + serverResponse); if(!isStatusOk(connectionStatusCode)) return null; return serverResponse; } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } return null; } ```
How do I make an http request using cookies on Android?
[ "", "java", "android", "http", "url", "cookies", "" ]
I have two methods that basically converts underlying checkboxes' text or tag as CSV strings. These two methods * GetSelectedTextAsCsv() * GetTagAsCsv() differ only by which *property* to extract value from `SelectedCheckBoxes`, which is of type `IList<CheckBox>` ``` public string GetSelectedTextAsCsv() { var buffer = new StringBuilder(); foreach (var cb in SelectedCheckBoxes) { buffer.Append(cb.Text).Append(","); } return DropLastComma(buffer.ToString()); } public string GetTagAsCsv() { var buffer = new StringBuilder(); foreach (var cb in SelectedCheckBoxes) { buffer.Append(cb.Tag).Append(","); } return DropLastComma(buffer.ToString()); } ``` I was trying to extract a method that returns a `Func<T, TResult>` but not sure how I can pull that off. My poor attempt was like the following but I cannot figure out how to extract the property portion as shown in the comment within `ConvertToCsv()` ``` public Func<T, string> ConvertToCsv<T>() { return propertyName => { var buffer = new StringBuilder(); foreach (var checkBox in SelectedCheckBoxes) { buffer.Append( /* How can you abstract this portion? like following? */ checkBox.propertyName ).Append(","); } return DropLastComma(buffer.ToString()); }; } ``` If I am on a wrong track, would you please advise me on how I can refactor above code to use a common method? **[UPDATE 1]** Here is the combination of both Brian and Jon's answers ``` public string ConvertToCsv<T>(Func<CheckBox, T> getValue) { var stringValues = SelectedCheckBoxes.Select( cb => getValue(cb).ToString()).ToArray(); return string.Join(",", stringValues); } public string GetSelectedTextAsCsv() { return ConvertToCsv(cb => cb.Text); } public string GetTagAsCsv() { return ConvertToCsv(cb => cb.Tag); } ``` **[UPDATE 2]** version 2 ``` public string GetAsCsv<T>(Func<CheckBox, T> getValue) { return string.Join(",", SelectedCheckBoxes.Select( cb => getValue(cb).ToString()).ToArray()); } public string GetSelectedTextAsCsv() { return GetAsCsv(cb => cb.Text); } public string GetTagAsCsv() { return GetAsCsv(cb => cb.Tag == null ? string.Empty : cb.Tag.ToString()); } ``` **[UPDATE 3]** Made the parameter of `GetAsCsv()` as a closed generic of CheckBox and string > `Func<CheckBox, T>` to `Func<CheckBox, string>`. That allowed me to make `GetAsCsv()` even simpler and more readable. ``` private string GetAsCsv(Func<CheckBox, string> getValue) { return string.Join(",", SelectedCheckBoxes.Select(getValue).ToArray()); } ```
``` public string GetAsCsv(Func<CheckBox, string> getValue) { var buffer = new StringBuilder(); foreach (var cb in SelectedCheckBoxes) { buffer.Append(getValue(cb)).Append(","); } return DropLastComma(buffer.ToString()); } ``` Then: ``` GetAsCsv(cb => cb.Tag != null ? cb.Tag.ToString() : string.Empty); GetAsCsv(cb => cb.Text); ```
I'd use `string.Join` instead: ``` string tags = string.Join(",", SelectedCheckBoxes.Select(cb => Convert.ToString(cb.Tag)) .ToArray()); string text = string.Join(",", SelectedCheckBoxes.Select(cb => cb.Text).ToArray()); ``` Sure, you could put that into a method, but I probably wouldn't bother for just two calls. If you wanted to though, here's how it would look using Brian's template: ``` public string GetAsCsv(Func<CheckBox, string> getValue) { string[] array = SelectedCheckBoxes.Select(getValue).ToArray(); return string.Join(",", array); } ```
Can you refactor out a common functionality from these two methods?
[ "", "c#", ".net", "refactoring", "csv", "" ]
I have some objects: ``` class Foo { public Guid id; public string description; } var list = new List<Foo>(); list.Add(new Foo() { id = Guid.Empty, description = "empty" }); list.Add(new Foo() { id = Guid.Empty, description = "empty" }); list.Add(new Foo() { id = Guid.NewGuid(), description = "notempty" }); list.Add(new Foo() { id = Guid.NewGuid(), description = "notempty2" }); ``` I would like to process this list in such a way that the `id` field is unique, and throw away the non-unique objects (based on id). The best I could come up with is: ``` list = list.GroupBy(i => i.id).Select(g=>g.First()).ToList(); ``` Is there a nicer/better/quicker way to achieve the same result.
A very elegant and intention revealing option is to define a new extension method on IEnumerable So you have: ``` list = list.Distinct(foo => foo.id).ToList(); ``` And ... ``` public static IEnumerable<T> Distinct<T,TKey>(this IEnumerable<T> list, Func<T,TKey> lookup) where TKey : struct { return list.Distinct(new StructEqualityComparer<T, TKey>(lookup)); } class StructEqualityComparer<T,TKey> : IEqualityComparer<T> where TKey : struct { Func<T, TKey> lookup; public StructEqualityComparer(Func<T, TKey> lookup) { this.lookup = lookup; } public bool Equals(T x, T y) { return lookup(x).Equals(lookup(y)); } public int GetHashCode(T obj) { return lookup(obj).GetHashCode(); } } ``` A similar helper class can be built to compare objects. (It will need to do better null handling)
Using the `Distinct()` method is about 4x faster than using GroupBy() in my informal tests. For 1 million Foo's my test has Distinct() at about 0.89 seconds to make a unique array out of a non-unique array where GroupBy() takes about 3.4 seconds. My Distinct() call looks like, ``` var unique = list.Distinct(FooComparer.Instance).ToArray(); ``` and `FooComparer` looks like, ``` class FooComparer : IEqualityComparer<Foo> { public static readonly FooComparer Instance = new FooComparer(); public bool Equals(Foo x, Foo y) { return x.id.Equals(y.id); } public int GetHashCode(Foo obj) { return obj.id.GetHashCode(); } } ``` and my `GroupBy()` version looks like, ``` var unique = (from l in list group l by l.id into g select g.First()).ToArray(); ```
Distinct list of objects based on an arbitrary key in LINQ
[ "", "c#", ".net", "linq", "" ]
I've seen a few examples but none so far in C#, what is the best way to select a random file under a directory? In this particular case I want to select a wallpaper from "C:\wallpapers" every 15 or so minutes. Thanks.
[select random file from directory](https://stackoverflow.com/questions/742887/select-random-file-from-directory) ``` private string getrandomfile2(string path) { string file = null; if (!string.IsNullOrEmpty(path)) { var extensions = new string[] { ".png", ".jpg", ".gif" }; try { var di = new DirectoryInfo(path); var rgFiles = di.GetFiles("*.*").Where( f => extensions.Contains( f.Extension.ToLower())); Random R = new Random(); file = rgFiles.ElementAt(R.Next(0,rgFiles.Count())).FullName; } // probably should only catch specific exceptions // throwable by the above methods. catch {} } return file; } ```
Get all files in an array and then retrieve one randomly ``` var rand = new Random(); var files = Directory.GetFiles("c:\\wallpapers","*.jpg"); return files[rand.Next(files.Length)]; ```
select random file from directory
[ "", "c#", ".net", "file", "random", "" ]
I currently try to implement some interprocess communication using the Windows [CreateFileMapping](http://msdn.microsoft.com/en-us/library/aa366551.aspx) mechanism. I know that I need to create a file mapping object with CreateFileMapping first and then create a pointer to the actual data with MapViewOfFile. The example then puts data into the mapfile by using CopyMemory. In my application I have an image buffer (1 MB large) which I want to send to another process. So now I inquire a pointer to the image and then copy the whole image buffer into the mapfile. But I wonder if this is really necessary. Isn't it possible to just copy an actual pointer in the shared memory which points to the image buffer data? I tried a bit but didn't succeed.
Different processes have different address spaces. If you pass a valid pointer in one process to another process, it will probably point to random data in the second process. So you will have to copy all the data.
I **strongly** recommend you use [Boost::interprocess](http://www.boost.org/doc/libs/1_38_0/doc/html/interprocess.html). It has lots of goodies to manage this kind of stuff & even includes some special Windows-only functions in case you need to interoperate w/ other processes that use particular Win32 features. The most important thing is to use [offset pointers](http://www.boost.org/doc/libs/1_38_0/doc/html/interprocess/offset_ptr.html) rather than regular pointers. Offset pointers are basically relative pointers (they store the difference between where the pointer is and where the thing pointed to is). This means that even if the two pointers are mapped to different address spaces, as long as the mappings are identical in structure then you are fine. I've used all kinds of complicated data structures with offset smart pointers and it worked like a charm.
Using shared memory under Windows. How to pass different data
[ "", "c++", "windows", "shared-memory", "" ]
In Java, an Enum can do the great things that Enums do, but can also have methods (behavior and logic). What advantage does that have over using a class using an enum? Simple examples to illustrate the point would also be welcome.
Here's a simple example: ``` enum RoundingMode { UP { public double round(double d) { return Math.ceil(d); } }, DOWN { public double round(double d) { return Math.floor(d); } }; public abstract double round(double d); } ```
`Enum` types are also a great way to implement true singletons. Classic singleton patterns in Java typically involve private constructors and public static factory methods but are still vulnerable to instantiation via reflection or (de-)serialization. An enum type guards against that.
Java Enums can have behavior?
[ "", "java", "oop", "enums", "" ]
I'm trying to find an authentication library for CodeIgniter 1.7.x, but am not having much luck. I originally found this stack**overflow** post: [How should I choose an authentication library for CodeIgniter?](https://stackoverflow.com/questions/346980/what-code-igniter-authentication-library-is-best), which listed several, but most were either too simple and/or were designed for CodeIgniter 1.5.x I've played with FreakAuth, UserAuth, Redux, and several others, but had issues getting any of them to properly work. Does anyone know of a good library to use with CodeIgniter 1.7.x?
Have you tried [DX Auth](http://codeigniter.com/forums/viewthread/98465/)? It's very full featured and works with 1.7 (says so in the post, and I have personally used it).
I was looking for the simplest Authentication library a few months ago, and I found 'The Authentication Library'. It is very easy to use, the author has a CI-User\_guide-type for help, and it doesn't have any of the bloat I've found in other auth libraries. You can find it here: <http://programmersvoice.com/codeigniter/the-authentication-library-1-0-6> The author is very responsive on the CI boards and on his facebook/twitter page for comments and assistance. Try it out, I've had success with it in my 1.7 apps.
CodeIgniter 1.7 Authentication Library
[ "", "php", "authentication", "codeigniter", "" ]
I have a form where users can specify various parameters to dig through some data (status, date etc.). I can produce a query that is: ``` SELECT * FROM table WHERE: status_id = 3 date = <some date> other_parameter = <value> ``` etc. Each `WHERE` is optional (I can select all the rows with `status = 3`, or all the rows with `date = 10/10/1980`, or all the rows with `status = 3 AND date = 10/10/1980` etc.). Given a large number of parameters, all optional, what is the best way to make up a dynamic stored procedure? I'm working on various DB, such as: MySQL, Oracle and SQLServer.
One of the easiest ways to accomplish this: ``` SELECT * FROM table WHERE ((@status_id is null) or (status_id = @status_id)) and ((@date is null) or ([date] = @date)) and ((@other_parameter is null) or (other_parameter = @other_parameter)) ``` etc. This completely eliminates dynamic sql and allows you to search on one or more fields. By eliminating dynamic sql you remove yet another security concern regarding sql injection.
Create your procedure like this: ``` CREATE PROCEDURE [dbo].[spXXX] @fromDate datetime = null, @toDate datetime = null, @subCode int = null as begin set NOCOUNT ON /* NOCOUNT limits the server feedback on select results record count */ SELECT fields... FROM source WHERE 1=1 --Dynamic where clause for various parameters which may or may not be passed in. and ( @fromDate is null or [dateField] >= @fromDate) and ( @toDate is null or [dateField] <= @toDate) and ( @subCode is null or subCode= @leaveTypeSubCode) order by fields... ``` This will allow you to execute the procedure with 0 params, all params, or any # of params.
Stored Procedure with optional "WHERE" parameters
[ "", "sql", "mysql", "sql-server", "oracle", "" ]
If I enter the following into the browser: ``` http://domain.com/script.php?1234 ``` And script.php has the following script: ``` $key=array_keys($_GET); echo $key[0]; ``` The output will be: ``` 1234 ``` (I'm trying to do away with the ugly ?r=1234 and if this works, it will be perfect.) My question is, is this officially correct or it's poor programming?
You could as well do ``` echo $_SERVER['QUERY_STRING'] ``` As for creating friendly URLs, there are better ways to do it. See e.g.: [$\_GET and URL Rewriting for PHP](https://stackoverflow.com/questions/505338/get-and-url-rewriting-for-php)
You shouldn't use this approach. If you don't want your variables to be shown you can use [URL rewrite](http://httpd.apache.org/docs/2.0/misc/rewriteguide.html) to make the URL look good. Also, don't forget to sanitize your $\_GET :) Actually, in your example, 1234 is the variable you send through GET, with no value, if you want to look it this way.
php get variables as key with no value assigned
[ "", "php", "" ]
I'm having trouble installing Tomcat on my windows XP machine. I already have Apache and JDK 6 installed, what I need to know is: * Which file to download from the [Lastest Tomcat download page](http://tomcat.apache.org/download-60.cgi) * And how to install it so I can run the sample web app by going to `http://localhost/` In my `C:\Program Files\Java` folder, I see the following folders, this should give you an idea of whether I need any additional stuff installed: * jdk1.6.0\_10 * jre1.6.0\_04 * jre1.6.0\_06 * jre1.6.0\_07 * jre6 Thanks.
Tomcat 6 doesn't really need the full JDK and it runs with Java 1.5 as well, so Java wise you should be well off. Just make sure that JAVA\_HOME environment variable is set. You can either get the core zip or tar.gz file, or the Windows Service installer file. Core zip file: <http://www.apache.org/dist/tomcat/tomcat-6/v6.0.18/bin/apache-tomcat-6.0.18.zip> Just unzip it and run bin/startup.bat. If you'd like to install it as a Windows service (and get the "usual" program entry in Windows add/remove programs) you can get the Windows Service Installer file instead: <http://www.apache.org/dist/tomcat/tomcat-6/v6.0.18/bin/apache-tomcat-6.0.18.exe> By default tomcat listens to port 8080, so to check out the sample apps you need to go to <http://localhost:8080/examples/>. You can change the default port by editing server.xml in the conf directory.
I'm not sure what that URL is that you provided ("CGI" seems strange from a J2EE site), but the download links for tomcat are on its home page: <http://tomcat.apache.org/> You should probably download version 6, particularly if you're using it for personal development. The older versions are available and maintained primarily to support users who don't want to migrate J2EE versions. Finally: unless you are already using Apache, don't bother with it. Most commercial sites use Apache as a front-end because of its configurability (particularly URL rewriting). If you're just looking to develop web apps, Tomcat will act as web server in addition to servlet/JSP container. Installation instructions (as well as all other instructions) are here:<http://tomcat.apache.org/tomcat-6.0-doc/index.html> If you haven't done any J2EE development before, you'll need some docs on it. The Sun Tutorial is OK, but targeted to the Sun app-server and covers a lot of XML that isn't really necessary. Look at the intro chapters on web apps, then jump to chapter 11: <http://java.sun.com/j2ee/1.4/docs/tutorial/doc/index.html>
How to install Tomcat on Windows XP?
[ "", "java", "apache", "tomcat", "jakarta-ee", "" ]
On an [official sqlite3 web page](http://www.sqlite.org/) there is written that I should think about sqlite as a replacement of fopen() function. What do you think about it? Is it always good solution to replece application internal data storage with sqlite? What are the pluses and the minuses of such solution? Do you have some experience in it? EDIT: How about your experience? Is it easy to use? Was it painful or rather joyful? Do you like it?
It depends. There are some contra-indications: * for configuration files, use of plain text or XML is much easier to debug or to alter than using a relational database, even one as lightweight as SQLite. * tree structures are easier to describe using (for example) XML than by using relational tables * the SQLite API is quite badly documented - there are not enough examples, and the hyperlinking is poor. OTOH, the information is all there if you care to dig for it. * use of app-specific binary formats directly will be faster than storing same format as a BLOB in a database * database corruption can mean the los of **all** your data rather than that in a single bad file OTOH, if your internal data fits in well with the relational model and if there is a a lot of it, I'd recommend SQLite - I use it myself for one of my projects. Regarding experience - I use it, it works well and is easy to integrate with existing code. If the documentation were easier to navigate I'd give it 5 stars - as it is I'd give it four.
As always it depends, there are no "one size fits all" solutions If you need to store data in a stand-alone file and you can take advantage of relational database capabilities of an SQL database than SQLite is great. If your data is not a good fit for a relational model (hierarchical data for example) or you want your data to be humanly readable (config files) or you need to interoperate with another system than SQLite won't be very helpful and XML might be better. If on the other hand you need to access the data from multiple programs or computers at the same time than again SQLite is not an optimal choice and you need a "real" database server (MS SQL, Oracle, MySQL, PosgreSQL ...).
Sqlite as a replacement for fopen()?
[ "", "c++", "c", "sqlite", "fopen", "" ]
how to compare value in an array? I have array named list which contains 12 elements. I see if value in index 0 is equal or not equal to value in index 2. I have tried this code but it doesnt seems to work. ``` if ((list.get(0)==list.get(2) && list.get(1)==list.get(3)) { System.out.println("equal") } ```
``` if(list[0] == list[2] && list[1] == list[3]){ System.out.println("equal"); } ``` If they are strings: ``` if(list[0].equals(list[2]) && list[1].equals(list[3])){ System.out.println("equal"); } ```
If it's *really* an array, you want: ``` if (list[0] == list[2] && list[1] == list[3]) ``` Note that if the array is of reference types, that's comparing by reference identity rather than for equality. You might want: ``` if (list[0].equals(list[2])) && list[1].equals(list[3])) ``` Although that will then go bang if any of the values is null. You might want a helper method to cope with this: ``` public static objectsEqual(Object o1, Object o2) { if (o1 == o2) { return true; } if (o1 == null || o2 == null) { return false; } return o1.equals(o2); } ``` Then: ``` if (objectsEqual(list[0], list[2]) && objectsEqual(list[1], list[3])) ``` If you've really got an `ArrayList` instead of an array then all of the above still holds, just using `list.get(x)` instead of `list[x]` in each place.
How to compare value in array?
[ "", "java", "arrays", "" ]
I'm a guy used to mootools' way of chaining selectors, and I can't seem to find anywhere how to do the same in jQuery. Suppose I have a *select element* in the `selectObj` variable. What I need is to get the last option in that select. In mootools I would have done something like: ``` var option = $(selectObj).getElement('nth-child(last)') ``` Can I do something similar, or what is the way of getting that last `option` in jQuery? PS. I know about the [parent > child selector](http://docs.jquery.com/Selectors/child#parentchild), but I can't really use it because I don't know what selector has been used to get the `select`. I only have the resulting element.
``` var option = $(selectObj).children(":last"); ``` will return the last child of any element
``` $(selectObj).find(':last') ``` You can use [`find`](http://docs.jquery.com/Traversing/find#expr) to perform another query within the current query. In general, you can check out the [Selectors](http://docs.jquery.com/Selectors) and [Traversal](http://docs.jquery.com/Traversing) pages on jQuery docs when you're trying to figure out how to select something.
Chaining selectors in jQuery
[ "", "javascript", "jquery", "css-selectors", "method-chaining", "" ]
After I do the .post thing, I want to hide the first div with a left slide, then show the second with a right slide. My right-slide was working fine and then I went and tried to put in the left slide and I broke it all. ``` if(hasError == false) { $.post("/process-email-signups",{email_address: email_addressVal}, function(data){ $("#email_signup_form").hide("slide", { direction: "left" }, 1000); function() { $("#thank_you_message").show("slide", { direction: "right" }, 1000); }); } ); } ```
I'm not sure what the extra function() is doing, maybe try removing that? ``` if(hasError == false) { $.post("/process-email-signups",{email_address: email_addressVal}, function(data){ $("#email_signup_form").hide("slide", { direction: "left" }, 1000); $("#thank_you_message").show("slide", { direction: "right" }, 1000); } ); } ```
You've got an extraneous function block in there. Try this instead: ``` function(data){ $("#email_signup_form").hide("slide", { direction: "left" }, 1000); $("#thank_you_message").show("slide", { direction: "right" }, 1000); } ); ```
Why do I get a jQuery syntax error with .post and hide("slide")?
[ "", "javascript", "jquery", "syntax", "" ]
In python is it possible to run each function inside a class? **EDIT:** What i am trying to do is call of the functions inside a class, collect their return variables and work with that.
Depends what you mean by "function". Something like this could work, though: ``` import inspect def methods(c): return (m for m in (getattr(c, d) for d in dir(c)) if inspect.ismethoddescriptor(m) or inspect.ismethod(m)) ``` Then: ``` class C: def f(self): pass >>> list(methods(C)) [<unbound method C.f>] ```
yes, you can. Quick and dirty: ``` class foo: def one(self): print "here is one" def two(self): print "here is two" def three(self): print "here is three" obj = foo() for entry in dir(obj): print entry, callable(getattr(obj,entry)) if callable(getattr(obj,entry)): getattr(obj,entry)() ``` If you want a more refined concept, check the unittest.py module. There should be code that executes all methods starting with the string "test"
For each function in class within python
[ "", "python", "reflection", "oop", "" ]
I want to open All external link into new window/tab through php without touching every external link code. and i don't want to this without target="blank". I can do this through javascript but i want to know if there is a PHP solution.
This job cannot be done with PHP. PHP is on the server side while your problem requires interaction with the client. This is a classical thing you'd use javascript for. In case you use JQuery things become extremely simple: ``` // pretend you have links in your page <a href="link.htm" rel="external">Link</a> // please note that the rel-value can be chosen at will $(document).ready(function(){ $('a[rel="external"]').click(function() { window.open(this.href, '_blank'); return false; }); }); ```
Not sure if I got this one right, but if you're looking for a JS alternative to "target=blank" then this one works and is xhtml valid: onclick="window.open(this.href, '\_blank'); return false;"
How to open exernal link in new window through PHP?
[ "", "javascript", "html", "" ]
I am trying to replicate a database from SQL server 2000 to 2005 they are located on two different servers both running Windows Server 2003 R2. Im am using SERVER1(SQL2000) as the Transactional publisher and distributor and SERVER2(SQL2005) is the subscriber. I can set up the publication and subscription but when I try to syncronize them I get the following error: SERVER1-TestReplication-TestReplication-IBSCNVII-ReplicationCNVII\_2-99956FE2-402A-48D5-B801-2CBADF12BD3E has server access (reason: Could not obtain information about Windows NT group/user '', error code 0x5. [SQLSTATE 42000] (Error 15404)). Do I need to add my domain user to a certain user group on server? Any ideas?
0x5 means "access denied" and that you're not allowed to query active directory user information. Likely, the sql server service account does not have proper domain privileges to perform look ups in AD. This could be caused by an account password simply being expired and therefore not enabling SQL to validate against AD or some other issue like services running as local system and not a domain account. I would recommend confirming that both SQL servers are using a valid domain account and not something like local system. Then check that that domain account isn't locked up or expired.
make sure that the service account you are using to execute the replication has the appropriate rights to both your SQL servers
Database Replication MSSQL 2000 to 2005
[ "", "sql", "sql-server", "database", "sql-server-2005", "replication", "" ]
I would like to use my function, for example `DebugR()`, but I don't want to use a require or include (with `include_path`) to load the function file that contains the source. I know I could use an autoload, but this action must be generic in my php configuration. I think I must create a PHP extension, but is there another way?
There is a PHP configuration line you can do. The documentation says this : auto\_prepend\_file string ``` Specifies the name of a file that is automatically parsed before the main file. The file is included as if it was called with the require() function, so include_path is used. The special value none disables auto-prepending. ```
Without building the extension, or auto-loading a class of functions or directly requiring the function into the page, or writing the function in the same file, I'm pretty sure there isn't a way without adjusting your PHP configuration. Out of curiosity, what are the reasons for not wanting to do any of those things?
How to use php function without load source file?
[ "", "php", "function", "" ]
I am using .NET 3.5 and building pages inside of the Community Server 2008 framework. On one of the pages, I am trying to get an UpdatePanel working. I took a sample straight from ASP.NET website, *update a time in an UpdatePanel to current time by clicking a button,* but for some reason when I try and perform the function the whole page refreshes. Here is what I have: ``` protected void Button1_Click(object sender, EventArgs e) { Label1.Text = "Panel refreshed at " + DateTime.Now.ToString(); Label2.Text = "Panel refreshed at " + DateTime.Now.ToString(); } ``` ``` <asp:ScriptManager ID="ScriptManager1" runat="server"/> <asp:UpdatePanel ID="UpdatePanel1" runat="server"> <ContentTemplate> <fieldset> <legend>UpdatePanel</legend> <asp:Label ID="Label1" runat="server" Text="Panel created."></asp:Label><br /> <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Button" /> </fieldset> </ContentTemplate> </asp:UpdatePanel> ``` Whenever I click the button, sure the panel updates - but the whole page posts back! I can see the whole page flashing. What the heck am I doing wrong? I am inside of a nested Masterpage, but I'm not sure if this is a problem. Could there be something in this Community Server framework that I'm using that causes all events to postback?
Did you try setting `Button1` as an `AsyncPostBackTrigger` in the Triggers section? Set the `ChildrenAsTriggers` property to `true` and the `UpdateMode` property to `Conditional`. ``` protected void Button1_Click(object sender, EventArgs e) { Label1.Text = "Panel refreshed at " + DateTime.Now.ToString(); UpdatePanel1.Update(); } ``` ``` <asp:ScriptManager ID="ScriptManager1" runat="server"/> <asp:UpdatePanel ID="UpdatePanel1" runat="server" ChildrenAsTriggers="true" UpdateMode="Conditional"> <Triggers> <asp:AsyncPostBackTrigger ControlID="Button1" EventName="Click" /> </Triggers> <ContentTemplate> <fieldset> <legend>UpdatePanel</legend> <asp:Label ID="Label1" runat="server" Text="Panel created."></asp:Label><br /> <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Button" /> </fieldset> </ContentTemplate> </asp:UpdatePanel> ```
I'm not seeing Label2 in your code sample above. If Label2 is located outside the UpdatePanel, a full page refresh will occur because that is what is required for the page to properly update Label2. By default, UpdatePanels will only dynamically refresh the content within them, when triggered by controls within them. If you need to do some fancier updates, say a button outside of the panel causing the refresh or a label in a different panel to be updated, then you need to set the Conditional attribute on your UpdatePanel(s) and make some manual Update calls in your code.
How to stop UpdatePanel from causing whole page postback?
[ "", "c#", "asp.net", ".net-3.5", "updatepanel", "community-server", "" ]
I am switching from plain mysql in php to PDO and I have noticed that the common way to test for errors is using a try / catch combination instead of if / else combinations. What is the advantage of that method, can I use one try / catch block instead of several nested if / else blocks to handle all errors for the different steps (connect, prepare, execute, etc.)?
I'd use the try/catch block when the normal path through the code should proceed without error unless there are truly some exceptional conditions -- like the server being down, your credentials being expired or incorrect. I wouldn't necessarily use it to handle non-exceptional errors -- say like the current user not being in the correct role. That is, when you can reasonably expect and handle an error that is not an exceptional condition, I think you should do your checks. In the case that you've described -- setting up and performing a query, a try/catch block is an excellent way to handle it as you normally expect the query to succeed. On the other hand, you'll probably want to check that the contents of result are what you expect with control flow logic rather than just attempting to use data that may not be valid for your purpose. One thing that you want to look out for is sloppy use of try/catch. Try/catch shouldn't be used to protect yourself from bad programming -- the "I don't know what will happen if I do this so I'm going to wrap it in a try/catch and hope for the best" kind of programming. Typically you'll want to restrict the kinds of exceptions you catch to those that are not related to the code itself (server down, bad credentials, etc.) so that you can find and fix errors that are code related (null pointers, etc.).
In general, try-catch blocks are great because they will break (move to the catch statement) whenever the exception occurs. If-else blocks rely on you predicting when the error will happen. Edit: Also, catch blocks won't stop your code from halting when an error is hit.
What is the advantage of using try {} catch {} versus if {} else {}
[ "", "php", "mysql", "pdo", "" ]
We have an RMI client application written in Java which needs to send periodic "stay alive" messages to a server application. We have implemented this as a separate heartbeat thread, which sends the stay alive message to the server, then sleeps for 15 seconds using Thread.sleep(). The thread is set to be high priority: ``` Thread heartbeatThread = new Thread(new HeartbeatRunnable(server)); heartbeatThread.setPriority(Thread.MAX_PRIORITY); heartbeatThread.start(); ``` However, when the box on which the client is running is using lots of CPU, we find that heartbeats are missed, which causes the server to assume our client application has died. We have added Thread.yield() calls in my main thread, although this has not made the problem go away. Is there any way of guaranteeing that heartbeats are sent on time while my application is still running?
You can implement user-mode threading in a non-threaded environment by liberally scattering a self-written "yield" function in your code. Similarly, you could liberally scatter heartbeat check function calls in your code. Forgo the thread, simply regularly call a heartbeat function which checks to see if a heartbeat yet needs to be sent. It's a crude solution, but given you've tried the proper solution and it doesn't work, perhaps it's something you have to fall back to. In fact what you could do is place a macro at the beginning of every function call, which does a quick check on the time and calls the heartbeat function when necessary. (Ah, do you have macros in Java? I think not - but you get the idea).
You can not really guarantee it. You could send the heartbeat in a different thread to prevent the time it takes to send the heartbeat being added to your delay. It may also be advisable to set the delay between two heartbeats to half the time the server uses to decide a client is dead, i.e. if your server times out your client after 15 seconds, (try to) send a heartbeat every 7.5 seconds.
How can I guarantee a "stay alive" heartbeat is sent?
[ "", "java", "concurrency", "rmi", "heartbeat", "" ]
I'm currently writing a very basic Java game based on the idea of *[Theme Hospital](https://en.wikipedia.org/wiki/Theme_Hospital)*. I'm quite new to Java and am currently studying at the university my first year. I have done Java for nearly two years now on and off, but I'm finally devoting my time to a decent project. I'm at the stage where I need to create a person (patient) to be admitted to the hospital. They need to go to the reception desk, then GP's office, and then back to their starting position. I have looked into A\* path finding, but it seems really complicated to me. I understand how it works I think, but am unsure how to implement it into my game. So far, the user can place a reception desk, and build a GP's office. Each of these has a "point of usage" which will be the place the patient has to get to. The grid squares can only be full or not, there will be no different terrain. I'm hesitant to paste any code yet, as it's messy as I've learn a lot of new techniques to do with GUI in the past few months. My plan is to get to the milestone 1, making the patient go to the desk then the office and then leave. Once I have this, I will tidy up the code more. I've seen many implementations of A\* and many different types. Can someone give me a starting point I can work with? Should I try and adapt an already written set of classes, or try to write my own from the scratch?
You do want A\*, it is the optimal implementation for grid based pathfinding. This might help you out: <http://www.cokeandcode.com/main/tutorials/path-finding/> **EDIT:** The preceeding link is good for both as an implementable set of classes and as a guide for customizing the path finding methods to meet your satisfaction.
Naturally you will learn a lot about pathfinding if you write your own implementation. But you will also spend a lot of time doing it. Check out the [JGraphT](http://jgrapht.sourceforge.net/) library that deals with graphs in general, has a nice API and supports [more](http://www.jgrapht.org/javadoc/org/jgrapht/alg/DijkstraShortestPath.html) shortest path algorithms than just A\*.
Pathfinding 2D Java game?
[ "", "java", "path", "path-finding", "" ]
I am using the MVC to add a title to the masterpage with a content place holder. The default MVC masterpage template uses the following code: ``` <head runat="server"> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /> <title><asp:ContentPlaceHolder ID="TitleContent" runat="server"/></title> <link href="../../Content/Site.css" rel="stylesheet" type="text/css" /> </head> ``` When I try to add defaulted text to the front of the content holder, it doesn't show the text in the final rendered page. I am trying to get the page to show a default title with appended contentplaceholder text. Example: (Default Text) (ContentPlaceHolder Text) My Page - About Us ``` <head runat="server"> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /> <title>My Page - <asp:ContentPlaceHolder ID="TitleContent" runat="server"/></title> <link href="../../Content/Site.css" rel="stylesheet" type="text/css" /> </head> ``` I am looking for a way to accomplish this without having to use code behind. Any ideas?
After looking further, Phil Haack actually posted an article which was a solution to my question. It can be found at [Haacked](http://haacked.com/archive/2009/04/03/tipjar-title-tags-and-master-pages.aspx). In summary he said that everything that is rendered in the head is rendered as a control, and the fix for my question above is to put an asp literal control in the title to have it correctly generate the text. ``` <%@ Master ... %> <html> <head runat="server"> <title> <asp:ContentPlaceHolder ID="titleContent" runat="server" /> <asp:LiteralControl runat="server" Text=" - MySite" /> </title> </head> ... ```
It seems we should use ``` <asp:Literal runat="server" Text=" - MySite" /> ``` instead of ``` <asp:LiteralControl runat="server" Text=" - MySite" /> ``` mentioned in the article, because otherwise we get "Unknown server tag" error.
Appending to default title in asp.net masterpage
[ "", "c#", "asp.net", "asp.net-mvc", "" ]
Is it possible to specify the JVM to use when you call "java jar jar\_name.jar" . I have two JVM installed on my machine. I can not change JAVA\_HOME as it may break code that is all ready running. Kind Regards Stephen
Yes - just explicitly provide the path to java.exe. For instance: ``` c:\Users\Jon\Test>"c:\Program Files\java\jdk1.6.0_03\bin\java.exe" -version java version "1.6.0_03" Java(TM) SE Runtime Environment (build 1.6.0_03-b05) Java HotSpot(TM) Client VM (build 1.6.0_03-b05, mixed mode, sharing) c:\Users\Jon\Test>"c:\Program Files\java\jdk1.6.0_12\bin\java.exe" -version java version "1.6.0_12" Java(TM) SE Runtime Environment (build 1.6.0_12-b04) Java HotSpot(TM) Client VM (build 11.2-b01, mixed mode, sharing) ``` The easiest way to do this for a running command shell is something like: ``` set PATH=c:\Program Files\Java\jdk1.6.0_03\bin;%PATH% ``` For example, here's a complete session showing my default JVM, then the change to the path, then the new one: ``` c:\Users\Jon\Test>java -version java version "1.6.0_12" Java(TM) SE Runtime Environment (build 1.6.0_12-b04) Java HotSpot(TM) Client VM (build 11.2-b01, mixed mode, sharing) c:\Users\Jon\Test>set PATH=c:\Program Files\Java\jdk1.6.0_03\bin;%PATH% c:\Users\Jon\Test>java -version java version "1.6.0_03" Java(TM) SE Runtime Environment (build 1.6.0_03-b05) Java HotSpot(TM) Client VM (build 1.6.0_03-b05, mixed mode, sharing) ``` This won't change programs which explicitly use JAVA\_HOME though. Note that if you get the wrong directory in the path - including one that doesn't exist - you won't get any errors, it will effectively just be ignored.
You should be able to do this via the command line arguments, assuming these are Sun VMs installed using the usual Windows InstallShield mechanisms with the JVM finder EXE in *system32*. Type *java -help* for the options. In particular, see: ``` -version:<value> require the specified version to run -jre-restrict-search | -jre-no-restrict-search include/exclude user private JREs in the version search ```
Setting the JVM via the command line on Windows
[ "", "java", "windows", "command-line", "jvm", "" ]
What is the simplest way to use database persistence in Java? I know, many frameworks exists around the Internet, but it could be fun to learn how to develop a persistence layer by myself and its design patterns. Where to start? Books, websites, how-tos, code-examples, etc.
I would start with Sun's Java Persistence API (JPA). Here's a [good starter article](http://web.archive.org/web/20091028153606/http://java.sun.com/developer/technicalArticles/J2EE/jpa/).
Start by looking at features and source code of pre-existing ones. Here are a couple (just to name a few in alphabetical order) * [DbUtils](http://commons.apache.org/dbutils/): A very simple wrapper for JDBC. Maybe start looking here for ideas! * [EBean](http://www.avaje.org/): Similar to JPA itself * [Hibernate](http://www.hibernate.org/): The de-facto standard that heavily influenced Java's JPA specifications * [iciql](http://iciql.com/): A friendly fork of JaQu * [JaQu](http://www.h2database.com/html/jaqu.html): H2's own domain specific language for querying databases * [JDBI](http://jdbi.codehaus.org): Exposes relational database access in idiommatic Java * [JDO](http://db.apache.org/jdo/): Apache Java Data Objects * [jOOQ](http://www.jooq.org "jOOQ is a fluent API for typesafe SQL query construction and execution"): Modelling SQL as a domain specific language directly in Java * [MyBatis](http://www.mybatis.org/): "the world's most popular SQL mapping framework." [sic] (formerly iBatis) * [QueryDSL](http://www.querydsl.com/): A SQL-like fluent API with many different backends (not just SQL) * [Quaere](http://quaere.codehaus.org/): Similar to QueryDSL And soon, you can edit this answer and add your own framework!
Java persistence in database
[ "", "java", "persistence", "" ]
I have a weird issue. I am opening a popup window in IE6 with SSL enabled on the server. When the following executes it seems to lock the browser up. I know this is vague. This is the JScript that appears to be the problem. Gotta love your IE6! ``` function PopoffWindow(url) { var features = "height=400,width=550,top=60,left=100," + "toolbar=no,location=no,menubar=no,status=no," + "scrollbars=yes,resizable=yes"; var win = window.open(url, "DSRocks", features); win.focus(); return win; } ``` This is not a problem in IE7 or Firefox. And the problem seems to be isolated to this server (with SSL). Anyone have any insight on this? Thanks, Nick
The problem was with a JSON webservice call. Please see this link for details: <http://codeclimber.net.nz/archive/2006/12/22/How-to-enable-an-ASP.NET-WebService-to-listen-to-HTTP.aspx>
Is it possible that the window.open call does not return quickly enough to allow you to perform a .focus() on it, in the next line? What happens if you throw an alert() between those two lines?
PopUp window in IE 6 SSL
[ "", "asp.net", "javascript", "ssl", "internet-explorer-6", "popup", "" ]
Does anyone have an extension method to quickly convert the types in a `LinkedList<T>` using a `Converter<TInput, TOutput>`? I'm a bit surprised, where is the `ConvertAll<TOutput>(delegate)`?
The `ConvertAll` equivalent in extension methods for Linq is called `Select`! ``` var result = myLinkedList.Select(x => FancyCalculationWith(x)) ```
Depends on what you want to get out of it, but you can use Cast then enumerate through the resulting IEnumerable. ``` public class Foo { ... } public class Bar : Foo { ... } var list = new LinkedList<Bar>(); .... make list.... foreach (var foo in list.Cast<Foo>()) { ... } ```
No ConvertAll for LinkedList<T>?
[ "", "c#", ".net", "vb.net", "linked-list", "converters", "" ]
[Kohana](http://docs.kohanaphp.com/helpers/security#encode_php_tags) and [Codeigniter](http://codeigniter.com/user_guide/helpers/security_helper.html) both have `encode_php_tags()`. I understand XSS cleaning (for Javascript), but when and why would you use `encode_php_tags()`? What is the security threat?
A smart fellow on the #kohana forum suggested that it is there because Expression Engine uses eval() for templates. If someone were to embed PHP in a string it is possible it would be eval()'d and executed. Since Kohana does not use eval() for templates it is possible that it is just left over from Codeigniter days.
This ensures that any PHP code in user input will not be executed if, for example, the application writes the input to a file or passes it to `eval()`. Or if you just want to write out some PHP code to show the browser.
Encoding PHP Tags for Security?
[ "", "php", "security", "xss", "" ]
Is there extra overhead in using the `object.ReferenceEquals` method verses using `((object)obj1 == (object)obj2)`? In the first case, there would be a static method call involved, and in both cases some form of casting to an object would be involved. Even if the compiler balances out those methods, what about inequality? ``` (object)obj != null ``` as compared to... ``` !object.ReferenceEquals(obj,null) ``` I suppose that at some point, a logical negation would occur, either within the != operator, or as applied to the result of the ReferenceEquals method. What do you think? There's also the issue of readability to consider. ReferenceEquals seems clearer when checking equality, but for inequality, one might miss the **`!`** preceding `object.ReferenceEquals`, whereas the **`!=`** in the first variation is hard to overlook.
> Is there extra overhead in using the object.ReferenceEquals method No. The method directly contains the minimal IL description to perform the reference equality check (for the record: it's equivalent to VB's `Is` operator) and will often be inlined by the JIT (especially when targeting x64) so there's **no** overhead. About readability: I personally think that `object.ReferenceEquals` is potentially more readable (even in the negated form) because it explicitly expresses its semantics. The cast to `object` may be confusing to some programmers. I've just found [an article](http://onezero.org/blog/archives/45) discussing this. It prefers `(object)x == y` because the IL footprint is smaller. It argues that this might facilitate inlining of method `X` using this comparison. However (without any detailed knowledge of the JIT but logically and intuitively) I believe this is wrong: if the JIT behaves anything like an optimizing C++ compiler, it will consider the method *after* inlining the call to `ReferenceEquals`, so (for the sake of inlining method `X`) the memory footprint will be exactly the same either way. That is to say: choosing one way over the other will have no impact whatsoever on the JIT and consequently on performance.
Contrary to answers here, I found `(object) ==` faster than `object.ReferenceEquals`. As to how faster, very negligible! **Test bed:** I know you need reference equality check, but I'm including static `object.Equals(,)` method as well in case of classes where its not overriden. > Platform: x86; Configuration: Release build ``` class Person { } public static void Benchmark(Action method, int iterations = 10000) { Stopwatch sw = new Stopwatch(); sw.Start(); for (int i = 0; i < iterations; i++) method(); sw.Stop(); MsgBox.ShowDialog(sw.Elapsed.TotalMilliseconds.ToString()); } ``` Test: ``` Person p1 = new Person(); Person p2 = new Person(); bool b; Benchmark(() => { b = (object)p1 == (object)p2; //960 ~ 1000ms b = object.ReferenceEquals(p1, p2); //~ 1250ms b = object.Equals(p1, p2); //2100ms b = EqualityComparer<Person>.Default.Equals(p1, p2); //~4000ms }, 100000000); Person p1 = new Person(); Person p2 = null; bool b; Benchmark(() => { b = (object)p1 == (object)p2; //990 ~ 1000ms b = object.ReferenceEquals(p1, p2); // 1230 ~ 1260ms b = object.Equals(p1, p2); //1250 ~ 1300ms b = EqualityComparer<Person>.Default.Equals(p1, p2); //~3100ms }, 100000000); Person p1 = null; Person p2 = null; bool b; Benchmark(() => { b = (object)p1 == (object)p2; //960 ~ 1000ms b = object.ReferenceEquals(p1, p2); //1260 ~ 1270ms b = object.Equals(p1, p2); //1180 ~ 1220ms b = EqualityComparer<Person>.Default.Equals(p1, p2); //~3100ms }, 100000000); Person p1 = new Person(); Person p2 = p1; bool b; Benchmark(() => { b = (object)p1 == (object)p2; //960 ~ 1000ms b = object.ReferenceEquals(p1, p2); //1260 ~ 1280ms b = object.Equals(p1, p2); //1150 ~ 1200ms b = EqualityComparer<Person>.Default.Equals(p1, p2); //3700 ~ 3800ms }, 100000000); ``` `object.Equals(,)` calls `ReferenceEquals` internally and if they are not equal it would call the overriden virtual `Equals` method of the class, and hence you see the notice the speed difference. Results were consistent in `Debug` configuration too... **As pointed out, emphasis should be on Readability/meaningfulness/revealing intent.**
Reference equality performance difference? ((object)obj1 == (object)obj2) vs. object.ReferenceEquals( obj1, obj2 )
[ "", "c#", "performance", "coding-style", "equality", "readability", "" ]
I was reading a book called C# Yellow Book by Rob Miles when I came across this statement: > Programmer’s love new shiny toys. They are very keen to use language features to show off. Properties can be a bit like this. When considering properties versus get and set methods I am rather a fan of the old fashioned get and set methods because you know where you are with these. On the other hand I can see where properties might make life easier, if used in the correct way. I'm not really sure what he means by this. What do you guys suggest? What does MS suggest?
I think you should consider a bit of non-programming advice > When in Rome, do as the Romans do. .NET has properties ingrained into all of it's libraries, designers and code generators. It is almost an inseperable part of the platform. If you choose to use get/set accessors instead of normal properties you will be creating a library which has a very different appearance than what every other programmer is expecting. Using get/set accessors will only increase the chances that you create code which is incompatible with various tools. For instance, there are many tools out there which special case properties and fields and provide special features for them. You will have an equivalent construct but no tool support.
I wrote that part of the book as a Java programmer moving over to C# a few years ago. I think I'll revisit the text in the next version and make it a bit clearer. If you want to make sure that the user of your class is aware that some code is going to run when they use a thing, then putting it into a method makes this explicit. Furthermore, using methods allows you to return error conditions without having to throw exceptions. There is no perfomance hit, since the compiler converts properties into methods anyway. I use properties a lot in the code I write though, particularly for things like state. I was never really advocating not using properties, more making sure that you use the right thing in the right situation.
Should I use properties in my C# programs or should I use get/set accessors?
[ "", "c#", "properties", "coding-style", "" ]
I need some advice in tackling a query. I can handle this in a front-end application, however, due to design, I have to inplement this in the back-end. I have the following ``` CREATE TABLE [dbo].[openitems]( [id] [varchar](8) COLLATE SQL_Latin1_General_CP1_CI_AS NULL, [type] [char](5) COLLATE SQL_Latin1_General_CP1_CI_AS NULL, [date] [smalldatetime] NULL, [amount] [decimal](9, 2) NULL, [daysOpen] [smallint] NULL, [balance] [decimal](9, 2) NULL ) ON [PRIMARY] insert into openitems values('A12399','INV','2008-12-05',491.96,123) insert into openitems values('A12399','INV','2008-12-12',4911.37,116) insert into openitems values('A12399','INV','2008-12-05',3457.69,109) ``` The table above have all open invoices for a customer. I need to apply a payment to these invoices starting from the oldest invoice (daysOpen column in the table). So if I have a $550.00 payment, I'll first apply it to the invoice with 123 daysOld, that's $491.96 -$500 (which leaves $8.04 to be applied to the next invoice... and so on), then update that record (balance column in table) to 0.00 and move to the next and apply the remaining. That would be $4911.37 - $8.04, which would leave $4903.33. Since there is no balance left to be applied, the loop exits. The balance column should now read ``` 0 4903.33 3457.69 ``` Note: I need to do this for all customers in a table (around 10,000). A customer has an average of about 20 invoices open. Thanks
Consider the following: a payment either applies in full to a balance, applies in part to a balance, or overpays a balance. Now, imagine that we could find, for any balance, the cumulative balance of invoices to date. Rather than imagine that, let's do it: ``` create view cumulative_balance as select a.*, (select sum( balance ) from openitems b where b.id = a.id and b.type = a.type and a.daysOpen >= a.daysOpen) as cumulative_balance from openitems a; ``` Now we can find the first cumulative balance less than or equal to the payment, for any id and type, and store that, and daysOpen, and cumulative balance in server variables. Then we update all openItems with that id and type, where daysOpen <= the value we got, setting all those balances to zero. Then we find the first non-zero balance of that id and type, and set its balance to be it's balance - (payment - the cumulative balance we stored). if there's an overpayment, this balance will be correctly negative. With the correct query, you'll be able to do the lookup and first update in one statement. There are two problems. One is that you can't determine, of two or more alances with the same id and type and daysOpen, which should be paid first. Adding a *unique* id to your table would serve as a tie-breaker for those cases. Second is the need to save the cumulative balance to use it in the query for the second update. if you designed your table correctly, with a column for invoice\_amount that wasn't updated by payments, and a payment column that was, this would solve your problem. An even better refactoring would be to have two tables, one for invoices and one for payment: then a view could just do all the work, by comparing cumulative balances to cumulative payments, producing a list of unpaid balances or overpayments. In fact, I designed just such a system for a major mortgage guarantee company with the initials FM. It was a bit more complicated than what you have, in that balances were calculated from a number of formulas of amounts and percentages, and multiple payers (actually, insurers, this was for mortgages that had gone into default) had to be invoiced in a prescribed order according to other rules, per defauted mortgage. All of this was done in views, with a short (100 line or so) stored procedure that essentially did what I've outlined above: used a view that ordered the billing of invoices by these rules, applied payments (in the view), calculating what additional payments to invoice on what date to which insurer. The stored procedure then just generated invoices for the current date (which current date could be set, again using a view, to any date for testing purposes). (The irony is that I'd taken the job onteh promise I'd get to write C++; the only C++ I wrote used the Oracle and Sybase C APIs to transfer data from the Oracle system to the Sybase one.)
This should do it. I've declared a local variable, but you could make that a parameter from a stored procedure. I've also added an invoice\_id to the table to uniquely identify invoices since id and date don't seem to be unique. ``` DECLARE @paid_amount DECIMAL(9, 2) SET @paid_amount = 500 UPDATE OI SET balance = CASE WHEN @paid_amount - SQ.running_total > balance THEN 0 ELSE balance - (@paid_amount - SQ.running_total) END FROM dbo.OpenItems OI INNER JOIN ( SELECT I1.id, I1.invoice_id, I1.date, ISNULL(SUM(I2.amount), 0) AS running_total FROM OpenItems I1 LEFT OUTER JOIN OpenItems I2 ON I2.id = I1.id AND I2.type = 'INV' AND I2.daysopen > I1.daysopen GROUP BY I1.id, I1.invoice_id, I1.date ) AS SQ ON SQ.id = OI.id AND SQ.invoice_id = OI.invoice_id WHERE @paid_amount > SQ.running_total ```
ADVICE on billing Query in SQL Server 2000
[ "", "sql", "sql-server-2000", "billing", "" ]
I have a FloatBuffer of known size and just want to dump the data to a file (in binary) for inspection outside my app. What's the easiest way to do this?
UPDATE FOR BINARY OUTPUT: ``` // There are dependencies on how you create your floatbuffer for this to work // I suggest starting with a byte buffer and using asFloatBuffer() when // you need it as floats. // ByteBuffer b = ByteBuffer.allocate(somesize); // FloatBuffer fb = b.asFloatBuffer(); // There will also be endiance issues when you write binary since // java is big-endian. You can adjust this with Buffer.order(...) // b.order(ByteOrder.LITTLE_ENDIAN) // If you're using a hex-editor you'll probably want little endian output // since most consumer machines (unless you've got a sparc / old mac) are little FileOutputStream fos = new FileOutputStream("some_binary_output_file_name"); FileChannel channel = fos.getChannel(); channel.write(byteBufferBackingYourFloatBuffer); fos.close(); ``` TEXT OUTPUT: Since you want this to be viewable I assume you want a text file. You'll want to use a PrintStream. ``` // Try-catch omitted for simplicity PrintStream ps = new PrintStream("some_output_file.txt"); for(int i = 0; i < yourFloatBuffer.capacity(); i++) { // put each float on one line // use printf to get fancy (decimal places, etc) ps.println(yourFloagBuffer.get(i)); } ps.close(); ``` Didn't have time to post a full raw/binary (non-text) version of this. If you want to do that use a [FileOutputStream](http://java.sun.com/javase/6/docs/api/java/io/FileOutputStream.html), get the [FileChannel](http://java.sun.com/javase/6/docs/api/java/nio/channels/FileChannel.html), and directly write the [FloatBuffer](http://java.sun.com/javase/6/docs/api/java/nio/FloatBuffer.html) (since it's a [ByteBuffer](http://java.sun.com/javase/6/docs/api/java/nio/ByteBuffer.html))
Asusming you want the data as binary: Start with a `ByteBuffer`. Call `asFloatBuffer` to get your `FloatBuffer`. When you've finished doing your stuff, save the `ByteBuffer` out to a `WritableByteChannel`. If you already have `FloatBuffer` it can be copied into the buffer from step 2 with a `put`. A low performance but easier way would be to use `Float.floatToIntBit`. (Watch for endianess, obviously.)
How to save a Java FloatBuffer (or any Buffer) to a file
[ "", "java", "file", "buffer", "" ]
What's the best way to calculate a time difference in C++? I'm timing the execution speed of a program, so I'm interested in milliseconds. Better yet, seconds.milliseconds.. The accepted answer works, but needs to include ctime or time.h as noted in the comments.
See [`std::clock()`](http://en.cppreference.com/w/cpp/chrono/c/clock) function. ``` const clock_t begin_time = clock(); // do something std::cout << float( clock () - begin_time ) / CLOCKS_PER_SEC; ``` If you want calculate execution time for self ( not for user ), it is better to do this in clock ticks ( not seconds ). **EDIT:** responsible header files - `<ctime>` or `<time.h>`
I added this answer to clarify that the accepted [answer](https://stackoverflow.com/a/728070/5330223) shows CPU time which may not be the time you want. Because according to [the reference](http://en.cppreference.com/w/cpp/chrono/c/clock), there are **CPU time and wall clock time**. Wall clock time is the time which shows the actual elapsed time regardless of any other conditions like CPU shared by other processes. For example, I used multiple processors to do a certain task and the CPU time was high **18s** where it actually took **2s** in actual wall clock time. To get the actual time you do, ``` #include <chrono> auto t_start = std::chrono::high_resolution_clock::now(); // the work... auto t_end = std::chrono::high_resolution_clock::now(); double elapsed_time_ms = std::chrono::duration<double, std::milli>(t_end-t_start).count(); ```
How to calculate a time difference in C++
[ "", "c++", "" ]
I need to update a row in a table, and get a column value from it. I can do this with ``` UPDATE Items SET Clicks = Clicks + 1 WHERE Id = @Id; SELECT Name FROM Items WHERE Id = @Id ``` This generates 2 plans/accesses to the table. Is possibile in T-SQL to modify the UPDATE statement in order to update and return the Name column with 1 plan/access only? I'm using C#, ADO.NET `ExecuteScalar()` or `ExecuteReader()` methods.
You want the [OUTPUT](http://msdn.microsoft.com/en-us/library/ms177564.aspx) clause ``` UPDATE Items SET Clicks = Clicks + 1 OUTPUT INSERTED.Name WHERE Id = @Id ```
Accesses table only once : ``` DECLARE @Name varchar(MAX); UPDATE Items SET Clicks = Clicks + 1 , @Name = Name WHERE Id = @Id; SELECT @Name; ```
SQL: Update a row and returning a column value with 1 query
[ "", "c#", "sql-server", "t-sql", "ado.net", "" ]
**Background** In every other programming language I use on a regular basis, it is simple to operate on the return value of a function without declaring a new variable to hold the function result. In PHP, however, this does not appear to be so simple: ### example1 (function result is an array) ``` <?php function foobar(){ return preg_split('/\s+/', 'zero one two three four five'); } // can php say "zero"? /// print( foobar()[0] ); /// <-- nope /// print( &foobar()[0] ); /// <-- nope /// print( &foobar()->[0] ); /// <-- nope /// print( "${foobar()}[0]" ); /// <-- nope ?> ``` ### example2 (function result is an object) ``` <?php function zoobar(){ // NOTE: casting (object) Array() has other problems in PHP // see e.g., http://stackoverflow.com/questions/1869812 $vout = (object) Array('0'=>'zero','fname'=>'homer','lname'=>'simpson',); return $vout; } // can php say "zero"? // print zoobar()->0; // <- nope (parse error) // print zoobar()->{0}; // <- nope // print zoobar()->{'0'}; // <- nope // $vtemp = zoobar(); // does using a variable help? // print $vtemp->{0}; // <- nope ```
This is specifically array dereferencing, which is currently unsupported in php5.3 but should be possible in the next release, 5.4. Object dereferencing is on the other hand possible in current php releases. I'm also looking forward to this functionality!
PHP can not access array results from a function. Some people call this an issue, some just accept this as how the language is designed. So PHP makes you create unessential variables just to extract the data you need. So you need to do. ``` $var = foobar(); print($var[0]); ```
PHP syntax for dereferencing function result
[ "", "php", "arrays", "syntax", "function", "" ]
I was wondering how i should go about writing an XML data layer for a fairly simple php web site. The reasons for this are: 1. db server is not available. 2. Simple data schema that can be expressed in xml. 3. I like the idea of having a self contained app, without server dependencies. 4. I would possibly want to abstract it to a small framework for reuse in other projects. The schema resembles a simple book catalog with a few lookup tables plus i18n. So, it is quite simple to express. The size of the main xml file is in the range of 100kb to 15mb. But it could grow at some point to ~100mb. I am actually considering extending my model classes to handle xml data. Currently I fetch data with a combination of XMLReader and SimpleXml, like this: ``` public function find($xpath){ while($this->xml_reader->read()){ if($this->xml_reader->nodeType===XMLREADER::ELEMENT && $this->xml_reader->localName == 'book' ){ $node = $this->xml_reader->expand(); $dom = new DOMDocument(); $n = $dom->importNode($node, true); $dom->appendChild($n); $sx = simplexml_import_dom($n); // xpath returns an array $res = $sx->xpath($xpath); if(isset($res[0]) && $res[0]){ $this->results[] = $res; } } return $this->results; } ``` So, instead of loading the whole xml file in memory, I create a SimpleXml object for each section and run an xpath query on that object. The function returns an array of SimpleXml objects. For conservative search I would probably break on first found item. The questions i have to ask are: 1. Would you consider this as a viable solution, even for a medium to large data store? 2. Are there any considerations/patterns to keep in mind, when handling XML in PHP? 3. Does the above code scale for large files (100mb)? 4. Can inserts and updates in large xml files be handled in a low overhead manner? 5. Would you suggest an alternative data format as a better option?
> If you have a saw and you need to > pound in a nail, don't use the > saw. Get a hammer. (folk saying) In other words, if you want a data store, use a data-base, not a markup language. PHP has good support for various database systems via [PDO](http://www.php.net/manual/en/intro.pdo.php); for small data sets, you can use SQLite, which doesn't need a server (it is stored in a normal file). Later, should you need to switch to a full-featured database, it is quite simple. To answer your questions: 1. Viable solution - no, definitely not. XML has its purposes, but simulating a database is not one, not even for a small data set. 2. With XML, you're shuffling strings around, all the time. That might be just bearable on read, but is a real nightmare on write (slow to parse,large memory footprint, etc.). While you could subvert XML to work as a data store, it is simply the wrong tool for the job. 3. No (everything will take forever, if you don't run out of memory before that). 4. No, for many reasons (locking, re-writing the whole XML-string/file, not to mention memory again). 5a. [SQLite](http://www.sqlite.org/) was designed with very small and simple databases in mind - simple, no server dependencies (the db is contained in one file). As @Robert Gould points out [in a comment](https://stackoverflow.com/questions/717003/xml-as-a-data-layer-for-a-php-application/717015#717015), it doesn't scale for larger applications, but then 5b. for a medium to large data store, consider a relational database (and it is usually easier to switch databases than to switch from XML to a database).
No, it won't scale. It's not feasible. You'd be better off using e.g. [SQLite](http://www.php.net/manual/en/book.sqlite.php). You don't need a server, it's bundled in with PHP by default and stores data in regular files.
XML as a Data Layer for a PHP application
[ "", "php", "xml", "" ]
Does a plugin exists for Python/Django into Dreamweaver? Just wondering since Dreamweaver is a great web dev tool.
I remember looking for a plugin too, but came across [this](http://www.djangobook.com/en/beta/chapter04/) stumbling block: > **Designers are assumed to be comfortable with HTML code**. The template system isn’t designed so that templates necessarily are displayed nicely in WYSIWYG editors such as Dreamweaver. That is too severe of a limitation and wouldn’t allow the syntax to be as nice as it is. Django expects template authors are comfortable editing HTML directly. That being said, I found a [Dreamweaver extension](http://www.adobe.com/cfusion/exchange/index.cfm?event=extensionDetail&loc=en_us&extid=1557518) whilst having another quick look, so give it a try and let us know how it goes! From experience, the Eclipse solution offered by Paolo works very nicely, and the [Komodo](http://www.activestate.com/komodo/) [plugins](http://code.google.com/p/django-komodo-kit/wiki/ActiveState) look great, too. I know you are looking for a graphical editor, but [emacs](http://code.djangoproject.com/wiki/Emacs) does a very nice job ;)
As far as I know there's no Django-specific IDE plugins out there. However I use [Eclipse](http://www.eclipse.org/) with [PyDev](http://pydev.sourceforge.net/) for my Django/Python needs and it is quite nice.
Python/Django plugin for Dreamweaver
[ "", "python", "django", "dreamweaver", "" ]
I can't seem to find the answer to this anywhere. What default editors/converters are building into 3.5 Framework PropertyGrid control. Otherwise what object types can I throw at it and it be able to reliably show and edit? I've found a lot of tutorials on using custom editors (which I may do at some point). But right now in my program I'm allowing the user to create their own custom properties and I want to know what object types I should allow assuming they will be editing them in a PropertyGrid.
You might want to take a look at classes that derive from [`UITypeEditor`](http://msdn.microsoft.com/en-us/library/system.drawing.design.uitypeeditor.aspx) (in the [`System.Drawing.Design` namespace](http://msdn.microsoft.com/en-us/library/system.drawing.design.aspx)). These types will be passed as parameters to the [`EditorAttribute`](http://msdn.microsoft.com/en-us/library/system.componentmodel.editorattribute.aspx) (in the [`System.ComponentModel` namespace](http://msdn.microsoft.com/en-us/library/z82ykwhb.aspx)). You can also look at the metadata for the type to see where the `EditorAttribute` is applied. However, **do not** use reflection here, as that is not what the [`PropertyGrid` class](http://msdn.microsoft.com/en-us/library/system.windows.forms.propertygrid.aspx) uses. Rather use the [`TypeDescriptor` class](http://msdn.microsoft.com/en-us/library/system.componentmodel.typedescriptor.aspx) to get property descriptors for the properties on the type (call the static [`GetProperties` method](http://msdn.microsoft.com/en-us/library/e2k1x8zt.aspx)). Then, with the [`PropertyDescriptor`](http://msdn.microsoft.com/en-us/library/system.componentmodel.propertydescriptor.aspx) instance, call the [`GetEditor` method](http://msdn.microsoft.com/en-us/library/system.componentmodel.propertydescriptor.geteditor.aspx) to get an instance of the editor for that property.
Bear in mind that there some non-public classes. ``` System.Object System.Drawing.Design.UITypeEditor System.ComponentModel.Design.CollectionEditor System.ComponentModel.Design.ArrayEditor System.Web.UI.Design.CollectionEditorBase System.Web.UI.Design.WebControls.WizardStepCollectionEditor System.Web.UI.Design.WebControls.EmbeddedMailObjectCollectionEditor System.Web.UI.Design.WebControls.HotSpotCollectionEditor System.Web.UI.Design.WebControls.ListItemsCollectionEditor System.Web.UI.Design.WebControls.MenuItemStyleCollectionEditor System.Web.UI.Design.WebControls.RoleGroupCollectionEditor System.Web.UI.Design.WebControls.StyleCollectionEditor System.Web.UI.Design.WebControls.SubMenuStyleCollectionEditor System.Web.UI.Design.WebControls.TableCellsCollectionEditor System.Web.UI.Design.WebControls.TableRowsCollectionEditor System.ComponentModel.Design.BinaryEditor System.ComponentModel.Design.DateTimeEditor System.ComponentModel.Design.MultilineStringEditor System.ComponentModel.Design.ObjectSelectorEditor System.Windows.Forms.Design.AnchorEditor System.Windows.Forms.Design.BorderSidesEditor System.Windows.Forms.Design.DockEditor System.Windows.Forms.Design.FileNameEditor System.Windows.Forms.Design.FolderNameEditor System.Windows.Forms.Design.ShortcutKeysEditor System.Web.UI.Design.ConnectionStringEditor System.Web.UI.Design.DataBindingCollectionEditor System.Web.UI.Design.ExpressionsCollectionEditor System.Web.UI.Design.UrlEditor System.Web.UI.Design.XmlFileEditor System.Web.UI.Design.WebControls.DataGridColumnCollectionEditor System.Web.UI.Design.WebControls.DataControlFieldTypeEditor System.Web.UI.Design.WebControls.MenuBindingsEditor System.Web.UI.Design.WebControls.MenuItemCollectionEditor System.Web.UI.Design.WebControls.ParameterCollectionEditor System.Web.UI.Design.WebControls.RegexTypeEditor System.Web.UI.Design.WebControls.TreeNodeCollectionEditor System.Web.UI.Design.WebControls.TreeViewBindingsEditor System.Web.UI.Design.WebControls.DataPagerFieldTypeEditor System.Messaging.Design.QueuePathEditor System.Drawing.Design.ImageEditor System.Drawing.Design.ColorEditor System.Drawing.Design.ContentAlignmentEditor System.Drawing.Design.CursorEditor System.Drawing.Design.FontEditor System.Drawing.Design.FontNameEditor System.Drawing.Design.IconEditor System.Workflow.ComponentModel.Design.TypeBrowserEditor System.Workflow.ComponentModel.Design.BindUITypeEditor ```
Default built-in editors for the PropertyGrid control
[ "", "c#", "editor", "propertygrid", "" ]
I am attempting to return the number of customers located in a specific state that have rented a specific movie, where the rents table contains two columns, one for customer ID and one for the movie ID. The function takes in a movie ID and the state and returns an integer with the amount of customers. Right now I have an implementation, but it counts up the amount of rows the entire query returns: ``` SELECT COUNT(*) as numCustomers FROM CUSTOMER C, RENTS R WHERE C.ST = '" + state + "' AND R.mid = " + movieID ``` And then I count the amount of rows. I would like to just be able to check numCustomers for the correct data. Thanks!
Firstly, you are lacking a clause to link your RENTS table and your CUSTOMER table on CustomerId? Secondly, you should use the INNER JOIN functionality in the FROM clause to add your two tables. Thirdly, you should NOT build your sql as a string like this as you will be open to SQL Injection. At a guess, the sort of SQL you may be after is as follows. ``` DECLARE @movieId int DECLARE @state varchar(2) SET @movieId = 12345 SET @state = 'NY' SELECT COUNT(DISTINCT C.CustomerID) as numCustomers FROM CUSTOMER C INNER JOIN RENTS R ON C.CustomerID = R.CustomerId WHERE C.ST = @state AND R.mid = @movieId ```
Guessing something about your schema (how RENTS relates to CUSTOMER): ``` SELECT COUNT(*) as numCustomers FROM CUSTOMER c WHERE c.ST = @State AND EXISTS ( SELECT * FROM RENTS r WHERE r.CustomerID = c.CustomerID AND r.mid = @movieID ) ``` Also, you should research SQL injection attacks, if you're not already familiar with that subject.
Select COUNT() from multiple databases in SQL
[ "", "sql", "select", "count", "aggregate", "" ]
If I am in the middle of the function, I would like go to the very end of it in vim. I run into this problem as we sometimes have function of 500+ lines long (don't ask why). I use vim, gvim.
You can use the "]}" command. You may have to repeat it depending on how nested you are.
`][` goes to the next '}' in the first column. Read `:help 29.3` to find out more about moving through a program.
Go to the end of the C++ function in Vim
[ "", "c++", "vim", "" ]
How do you import an SSL certificate created by java into a project in Eclipse?
Probably you want to import a "fake" SSL cert in JRE's trustcacerts for avoiding not-a-valid-certificate issues. Isn't it? As Jon said, you can do the job with [keytool](http://java.sun.com/j2se/1.5.0/docs/tooldocs/solaris/keytool.html): ``` keytool -import -alias <provide_an_alias> -file <certificate_file> -keystore <your_path_to_jre>/lib/security/cacerts ``` Use "changeit" as the default password when asked ([thanks Brian Clozel](https://stackoverflow.com/questions/684081/importing-ssl-certificate-into-eclipse#comment2400032_685036)). Ensure to use this runtime at your server or launch configuration.
In case you have the certificate already in your Windows' certificate store (this is common in corporate/company deployments with MITM certificates), you can also use the following steps (with help from [another Stackoverflow answer with more detailed explaination](https://stackoverflow.com/a/49011158/12932497)): 1. Locate the `eclipse.ini` file in your Eclipse installation and open it 2. Below the line `-vmargs`, add the following lines, then save the file: ``` -Djavax.net.ssl.trustStore=NUL -Djavax.net.ssl.trustStoreType=Windows-ROOT ``` 3. Restart eclipse.
Importing SSL Certificate into Eclipse
[ "", "java", "eclipse", "ssl", "ssl-certificate", "" ]
In an application I maintain, we've encountered a problem with file descriptor limitations affecting the stdlib. This problem only affects the 32-bit version of the standard lib. I have devised a fix for my code and would like to implement it, but only when compiling for 32-bit executable. What pre-processor symbol can I #ifdef for to determine whether the code is being compiled for a 32 or 64-bit target? **EDIT** Sorry, didn't mention, the code is cross-platform, linux, windows, solaris and a few other unix flavors, mostly using GCC for compilation. Any de-facto standards I can use cross-platform? **EDIT 2** I've found some definitions "\_\_ILP23" and "\_\_LP64" that seem like they may work... a discussion [here](http://www.unix.org/version2/whatsnew/lp64_wp.html) explains the background on the unix platform. Anyone had any experience with using these defines? Is this going to be usable?
I'm not sure if there is a universal #if def that is appropriate. The C++ standard almost certainly does not define one. There are certainly platform spcefic ones though. For example, Windows ``` #if _WIN64 // 64 bit build #else // 32 bit build #endif ``` **EDIT** OP mentioned this is a cross compile between Windows and Non-Windows using GCC and other compilers There is no universal macro that can be used for all platforms and compilers. A little bit of preprocessor magic though can do the trick. Assuming you're only working on x86 and amd64 chips the following should do the trick. It can easily be expanded for other platforms though ``` #if _WIN64 || __amd64__ #define PORTABLE_64_BIT #else #define PORTABLE_32_BIT #endif ```
I recommend bookmarking the [predef SourceForge](http://predef.sourceforge.net/). There's no one answer, but it can certainly help you get started. EDIT: For GCC-only code, you can use `__i386__` to check for 32-bit x86 chips, and I suggest trying `__X86_64__` or something similar to check for 64-bit x86 chips. (Note: It has come to my attention that the previous answer involving `__ia86__` is actually a different chip, not a 64-bit x86 chip. This just shows my lack of hardware experience. For those more knowledgeable about hardware than I, consule the SourceForge page on predefined macros that I link to above. It's much more accurate than I am.) There are some other ones that would work, but those two should be fairly universal amongs GCC versions.
#ifdef for 32-bit platform
[ "", "c++", "c", "gcc", "64-bit", "32-bit", "" ]
I have a web page (made with JSF) where some links allow the user to get a PDF file. When the user clicks on such a link, a waiting popup (it is a modal panel) is displayed (because the generation of the PDF can be long), and once the file is created, IE displays the "File download" popup that proposes "Open", "Save" and "Cancel" options. Is there a way in Javascript to know from my web page when this popup is closed, i.e. when the user has saved (or opened) the PDF file? To be a little more precise, in the web page that displays the link to the PDF file, a modal popup is displayed (the "waiting popup") in order to make the user waits for the "File download" popup. The problem is that when the user Saves (or open) the PDF file, the "File download" popup closes, but the user then "returns" to the original webpage, with the waiting popup still displayed. Note that my application runs only in IE6, so I am not against a IE(6)-only solution... I have also no problem with solutions that need jQuery ;) **Edit:** If a solution exists to catch any event that is fired exactly when the "File download" popup is displayed to the user (i.e. before the user chooses to Save, Open or Cancel), it will be fine for me too!
I had to work on this kind of issue, on another project. I finally found a smart solution, as explained in another [Stackoverflow question](https://stackoverflow.com/questions/1106377/detect-when-browser-receives-file-download). The explanation is given in the following post: <http://gruffcode.com/2010/10/28/detecting-the-file-download-dialog-in-the-browser> The idea is to "simply" use a cookie to define when the file is downloaded.
No such event exists. You need to take a different approach to solve this. 1. target the download link to a hidden iframe with a name (`target="myhiddeniframe"`) 2. on click of the download link, show your loading spinner 3. set the `onload` attribute of the iframe to a callback that hides your spinner Net effect: you "spin" while the pdf is generated, and "unspin" when the "File download" dialog appears (as opposed to when the "File download" dialog is *closed*).
detecting when the "File download" popup is closed
[ "", "javascript", "internet-explorer", "download", "" ]
I have an array with some info. For example: > (writer) & or > with (additional dialogue) I want to clean this so I only get the text between the parenthesis () and clear everything else result: > writer or > additional dialogue
``` $string = "this (is (a) test) with (two parenthesis) duh"; ``` For a string like this you can use preg\_match\_all and use implode. ``` $string = "this (is (a) test) with (two parenthesis) duh"; $regex = '#\((([^()]+|(?R))*)\)#'; if (preg_match_all($regex, $string ,$matches)) { echo implode(' ', $matches[1]); } else { //no parenthesis echo $string; } ``` Or you can use preg\_replace, but with multiple parenthesis you'll lose the whitespace between them. ``` $regex = '#[^()]*\((([^()]+|(?R))*)\)[^()]*#'; $replacement = '\1'; echo preg_replace($regex, $replacement, $string); ``` I got a lot of help from this page, [Finer points of PHP regular expressions](http://www.skdevelopment.com/php-regular-expressions.php).
The easiest way will be with a regular expression: ``` preg_match_all('/\((.*?)\)/', $input, $matches); ``` `$matches[1]`, `$matches[2]`, etc will contain everything that was between parentheses in $input. That is, `$matches[1]` will have whatever was between the first set of parentheses, and so on (to handle cases with multiple sets).
PHP: how to get only the words between a parenthesis () and clear everything else
[ "", "php", "" ]
I've been looking at the [Common Service Locator](http://commonservicelocator.codeplex.com/) as a way of abstracting my IoC container but I've been noticing that some people are strongly against this type of this. Do people recommend never using it? Always using it? or sometimes using it? If sometimes, then in what situations would you use it and what situations would you not use it.
Imagine you are writing library code to be used by 3rd party developers. Your code needs to be able to create service objects that these developers provide. However you don’t know which IoC container each of your callers will be using. The Common Service Locator lets you cope with the above without forcing a given IoC on your users. Within your library itself you may wish to register your own classes in the IoC, now it gets a lot harder as you need to choose a IoC for your own use that will not get in the way of your callers.
I noticed that one of the arguments against using the CSL is a false one because developers think this library is only capable of doing the Service Locator pattern. This however isn't the case, because it is easy to use it with the Dependency Injection pattern as well. However, the CSL library was specially designed for framework designers who need to allow users to register dependencies. Because the library will be calling the CSL directly, from the framework's perspective we're talking about the SL pattern, hence its name. As a framework designer, however, setting a dependency on the CSL shouldn't be taken lightly. For the usability of your framework, it is normally much better to have your own DI mechanism. A very common mechanism is to set up dependencies in the configuration file. This pattern is used throughout the whole .NET framework. Almost every dependency can be replaced by another. The .NET provider pattern is built on top of this. When you, as a framework designer, take a dependency on the CSL, it will be harder for users to use your application. Users will have to configure an IoC container and hook it up to the CSL. However, it is not possible for the framework to validate the configuration as can be done while using the .NET configuration system, which has all kinds of validation support in it.
When would you use the Common Service Locator?
[ "", "c#", "dependency-injection", "inversion-of-control", "service-locator", "common-service-locator", "" ]
I have a table DEAL and a table DEAL\_TYPE. I would like to map this code: ``` public class Deal { DealType type; } public enum DealType { BASE("Base"), EXTRA("Extra"); } ``` The problem is that the data already exist in the database. And I'm having a hard time mapping the classes to the database. The database looks something like that: ``` TABLE DEAL { Long id; Long typeId; } TABLE DEAL_TYPE { Long id; String text; } ``` I know I could use a simple @OneToMany relationship from deal to deal type, but I would prefer to use an enum. Is this possible? I almost got it working by using a EnumType.ORDINAL type. But unfortunately, my IDs in my deal type table are not sequential, and do not start at 1. Any suggestions?
Hibernate is kind of terrible at Enums. It's a strange failing of an otherwise pretty good ORM. The "easiest" way to get around it is to declare your Enum a custom hibernate type. Fortunately, Hibernate wrote an example implementation which you can crib verbatim into your app: <http://www.hibernate.org/265.html> They even include instructions on how to use it. This is the pattern I use whenever I end up with the need to persist enums.
I've created a similar class like the one suggested by hibernate only that is configurable and there is no need to create a new type only for this persistence. Can be used like ``` @Type(type = "ro.raisercostin.hibernate.EnumUserType", parameters = @Parameter(name = "type", value = "DealType")) DealType dealType; ``` I added an implementation of ParameterizedType to support the passed parameter. ``` public class EnumUserType implements UserType, ParameterizedType { private static final int[] SQL_TYPES = { Types.VARCHAR }; private Class clazz = null; public EnumUserType() { } @Override public void setParameterValues(Properties parameters) { String className = (String) parameters.get("type"); try { this.clazz = Class.forName(className); } catch (ClassNotFoundException e) { throw new RuntimeException("Couldn't get the class for name [" + className + "].", e); } } public int[] sqlTypes() { return SQL_TYPES; } public Class returnedClass() { return clazz; } public Object nullSafeGet(ResultSet resultSet, String[] names, Object owner) throws HibernateException, SQLException { String name = resultSet.getString(names[0]); Object result = null; if (!resultSet.wasNull()) { result = Enum.valueOf(clazz, name); } return result; } public void nullSafeSet(PreparedStatement preparedStatement, Object value, int index) throws HibernateException, SQLException { if (null == value) { preparedStatement.setNull(index, Types.VARCHAR); } else { preparedStatement.setString(index, ((Enum) value).name()); } } public Object deepCopy(Object value) throws HibernateException { return value; } public boolean isMutable() { return false; } public Object assemble(Serializable cached, Object owner) throws HibernateException { return cached; } public Serializable disassemble(Object value) throws HibernateException { return (Serializable) value; } public Object replace(Object original, Object target, Object owner) throws HibernateException { return original; } public int hashCode(Object x) throws HibernateException { return x.hashCode(); } public boolean equals(Object x, Object y) throws HibernateException { if (x == y) { return true; } if ((null == x) || (null == y)) { return false; } return x.equals(y); } } ```
Mapping enum to a table with hibernate annotation
[ "", "java", "hibernate", "enums", "orm", "" ]
I have two dates of the form: ``` Start Date: 2007-03-24 End Date: 2009-06-26 ``` Now I need to find the difference between these two in the following form: ``` 2 years, 3 months and 2 days ``` How can I do this in PHP?
> Use this for legacy code (PHP < 5.3; Jun 2009). For up to date solution see [jurka](https://stackoverflow.com/users/474405/jurka)s' [answer above](https://stackoverflow.com/a/3923228/367456). You can use strtotime() to convert two dates to unix time and then calculate the number of seconds between them. From this it's rather easy to calculate different time periods. ``` $date1 = "2007-03-24"; $date2 = "2009-06-26"; $diff = abs(strtotime($date2) - strtotime($date1)); $years = floor($diff / (365*60*60*24)); $months = floor(($diff - $years * 365*60*60*24) / (30*60*60*24)); $days = floor(($diff - $years * 365*60*60*24 - $months*30*60*60*24)/ (60*60*24)); printf("%d years, %d months, %d days\n", $years, $months, $days); ``` **Edit:** Obviously the preferred way of doing this is like described by jurka below. My code is generally only recommended if you don't have PHP 5.3 or better. Several people in the comments have pointed out that the code above is only an approximation. I still believe that for most purposes that's fine, since the usage of a range is more to provide a sense of how much time has passed or remains rather than to provide precision - if you want to do that, just output the date. Despite all that, I've decided to address the complaints. If you truly need an exact range but haven't got access to PHP 5.3, use the code below (it should work in PHP 4 as well). This is a direct port of the code that PHP uses internally to calculate ranges, with the exception that it doesn't take daylight savings time into account. That means that it's off by an hour at most, but except for that it should be correct. ``` <?php /** * Calculate differences between two dates with precise semantics. Based on PHPs DateTime::diff() * implementation by Derick Rethans. Ported to PHP by Emil H, 2011-05-02. No rights reserved. * * See here for original code: * http://svn.php.net/viewvc/php/php-src/trunk/ext/date/lib/tm2unixtime.c?revision=302890&view=markup * http://svn.php.net/viewvc/php/php-src/trunk/ext/date/lib/interval.c?revision=298973&view=markup */ function _date_range_limit($start, $end, $adj, $a, $b, $result) { if ($result[$a] < $start) { $result[$b] -= intval(($start - $result[$a] - 1) / $adj) + 1; $result[$a] += $adj * intval(($start - $result[$a] - 1) / $adj + 1); } if ($result[$a] >= $end) { $result[$b] += intval($result[$a] / $adj); $result[$a] -= $adj * intval($result[$a] / $adj); } return $result; } function _date_range_limit_days($base, $result) { $days_in_month_leap = array(31, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31); $days_in_month = array(31, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31); _date_range_limit(1, 13, 12, "m", "y", &$base); $year = $base["y"]; $month = $base["m"]; if (!$result["invert"]) { while ($result["d"] < 0) { $month--; if ($month < 1) { $month += 12; $year--; } $leapyear = $year % 400 == 0 || ($year % 100 != 0 && $year % 4 == 0); $days = $leapyear ? $days_in_month_leap[$month] : $days_in_month[$month]; $result["d"] += $days; $result["m"]--; } } else { while ($result["d"] < 0) { $leapyear = $year % 400 == 0 || ($year % 100 != 0 && $year % 4 == 0); $days = $leapyear ? $days_in_month_leap[$month] : $days_in_month[$month]; $result["d"] += $days; $result["m"]--; $month++; if ($month > 12) { $month -= 12; $year++; } } } return $result; } function _date_normalize($base, $result) { $result = _date_range_limit(0, 60, 60, "s", "i", $result); $result = _date_range_limit(0, 60, 60, "i", "h", $result); $result = _date_range_limit(0, 24, 24, "h", "d", $result); $result = _date_range_limit(0, 12, 12, "m", "y", $result); $result = _date_range_limit_days(&$base, &$result); $result = _date_range_limit(0, 12, 12, "m", "y", $result); return $result; } /** * Accepts two unix timestamps. */ function _date_diff($one, $two) { $invert = false; if ($one > $two) { list($one, $two) = array($two, $one); $invert = true; } $key = array("y", "m", "d", "h", "i", "s"); $a = array_combine($key, array_map("intval", explode(" ", date("Y m d H i s", $one)))); $b = array_combine($key, array_map("intval", explode(" ", date("Y m d H i s", $two)))); $result = array(); $result["y"] = $b["y"] - $a["y"]; $result["m"] = $b["m"] - $a["m"]; $result["d"] = $b["d"] - $a["d"]; $result["h"] = $b["h"] - $a["h"]; $result["i"] = $b["i"] - $a["i"]; $result["s"] = $b["s"] - $a["s"]; $result["invert"] = $invert ? 1 : 0; $result["days"] = intval(abs(($one - $two)/86400)); if ($invert) { _date_normalize(&$a, &$result); } else { _date_normalize(&$b, &$result); } return $result; } $date = "1986-11-10 19:37:22"; print_r(_date_diff(strtotime($date), time())); print_r(_date_diff(time(), strtotime($date))); ```
I suggest to use DateTime and DateInterval objects. ``` $date1 = new DateTime("2007-03-24"); $date2 = new DateTime("2009-06-26"); $interval = $date1->diff($date2); echo "difference " . $interval->y . " years, " . $interval->m." months, ".$interval->d." days "; // shows the total amount of days (not divided into years, months and days like above) echo "difference " . $interval->days . " days "; ``` read more [php DateTime::diff manual](http://www.php.net/manual/en/datetime.diff.php) From the manual: > As of PHP 5.2.2 [May 2007], DateTime objects can be compared using comparison operators. ``` $date1 = new DateTime("now"); $date2 = new DateTime("tomorrow"); var_dump($date1 == $date2); // bool(false) var_dump($date1 < $date2); // bool(true) var_dump($date1 > $date2); // bool(false) ```
How to calculate the difference between two dates using PHP?
[ "", "php", "datetime", "datediff", "" ]
I have been messing around with pygame and python and I want to be able to call a function when an attribute of my class has changed. My current solution being: ``` class ExampleClass(parentClass): def __init__(self): self.rect = pygame.rect.Rect(0,0,100,100) def __setattr__(self, name, value): parentClass.__setattr__(self,name,value) dofancystuff() Firstclass = ExampleClass() ``` This works fine and dofancystuff is called when I change the rect value with `Firsclass.rect = pygame.rect.Rect(0,0,100,100)`. However if I say `Firstclass.rect.bottom = 3`. `__setattr__` and there for dofancystuff is not called. So my question I guess is how can I intercept any change to an attribute of a subclass? edit: Also If I am going about this the wrong way please do tell I'm not very knowledgable when it comes to python.
Well, the simple answer is you can't. In the case of `Firstclass.rect = <...>` your `__setattr__` is called. But in the case of `Firstclass.rect.bottom = 3` the `__setattr__` method of the Rect instance is called. The only solution I see, is to create a derived class of pygame.rect.Rect where you overwrite the `__setattr__` method. You can also monkey patch the Rect class, but this is discouraged for good reasons.
You could try `__getattr__`, which should be called on `Firstclass.rect`. But do this instead: Create a separate class (subclass of `pygame.rect`?) for `ExampleClass.rect`. Implement `__setattr__` in that class. Now you will be told about anything that gets set in your `rect` member for `ExampleClass`. You can still implement `__setattr__` in `ExampleClass` (and *should*), only now make sure you instantiate a version of your own `rect` class... BTW: Don't call your objects `Firstclass`, as then it looks like a class as opposed to an object...
Intercepting changes of attributes in classes within a class - Python
[ "", "python", "class", "attributes", "subclass", "pygame", "" ]
Is there any way to generate words based on characters and checking if a domain exists with this word (ping)? What I want to do is to generate words based on some characters, example "abcdefgh", and then ping generatedword.com to check if it exists.
You don't want to use the ping command, but you can use Python's [`socket.gethostbyname()` function](http://docs.python.org/library/socket.html#socket.gethostbyname) to determine whether a host exists. ``` def is_valid_host(hostname): try: addr = socket.gethostbyname(hostname) except socket.gaierror, ex: return False return True hosts = ['abc', 'yahoo.com', 'google.com', 'nosuchagency.gov'] filter(is_valid_host, hosts) ``` This is going to take tons of time and maybe make your ISP mad at you. You're better off either: 1. Using a lower-level DNS interface such as [dnspython](http://www.dnspython.org/), or 2. Finding a direct interface to domain registrars, such as [whois](http://pypi.python.org/pypi?%3Aaction=search&term=whois&submit=search), and querying that. You aren't going to use this to spam people, are you?
Just because a site fails a ping doesn't mean the domain is available. The domain could be reserved but not pointing anywhere, or the machine may not respond to pings, or it may just be down.
Looping through chars, generating words and checking if domain exists
[ "", "python", "ping", "" ]
I am performing a jQuery `.ajax()` call that returns a `List<string>` of IP addresses on a specified subnet. I use a `[WebMethod]` on an .aspx page to return the values. ASP.NET's built-in JSON serializer does the magic to return the actual JSON used in my Javascript. I have profiled the the server-side time, and it takes about 8 msec to populate and return the list, so the server-side code is not the issue. However, when the Ajax call is initiated, in Internet Explorer it can take upwards of 3 seconds to populate a listbox with a small list of IP addresses returned. In Firefox, the listbox is essentially populated instantly. I'm not entirely certain where the bottleneck could be. My best guess is that the fault lies with IE6's javascript engine, but even so, adding only 255 list items should not take this much time. Can anyone point me in the right direction as to why this is happening? **Example Code** ``` $.ajax({ type: "POST", url: $("Example.aspx/GetIPsOnNetwork", data: "{NetworkID: " + networkID + "}", contentType: "application/json; charset=utf-8", dataType: "json", success: function(data) { $('#ipAddresses').empty(); // Loop through each IP address and add it to the listbox $.each(data.d, function(){ var ip = this.toString(); $(document.createElement('option')).attr('value', ip).text(ip).appendTo('#ipAddresses'); }); }, error: function(msg) { alert('Error: ' + msg); } }); ```
It could be a rendering issue. try this ``` success: function(data) { // Loop through each IP address and add it to the listbox var list = $("<select />"); $.each(data.d, function(){ var ip = this.toString(); list.append($('<option />').val(ip).text(ip)); }); $('#ipAddress').empty().append(list.find('option')); }, ``` Basically, what you're doing is loading the options into a dummy list, then you're adding the contents to the ipAddresses list. The other thing that I changed was the `document.createElement(...)`. If you look at the internals of `$('<option />')` it performs the createElement for you. Finally I choose to append the data to the list instead of calling `option.appendTo('#ipAddress')`, which would have to find the ipAddress element every time.
I suspect it might be a difference in speed of creating the option elements in IE and adding each one by one to the DOM. On this line ``` $(document.createElement('option')).attr('value', ip).text(ip).appendTo('#ipAddresses'); ``` You could try ``` var optionArray = []; for (var i= 0; i < this.length; i++) { optionArray[i] = $('<option>').val(ip).text(ip); } $('#ipAddresses').empty().append(optionArray.join("")); ``` or this (data.d is an object, right?) ``` var optionArray = []; var i = 0; $.each(data.d, function(key, value) { optionArray[i++] = $('<option>').val(value).text(value); }); $('#ipAddresses').empty().append(optionArray.join("")); ``` You might find this [article on jQuery's append()](http://www.learningjquery.com/2009/03/43439-reasons-to-use-append-correctly) useful
jQuery Ajax call very slow in IE, but instant in Firefox
[ "", "javascript", "jquery", "ajax", "internet-explorer-6", "pagemethods", "" ]
I like ORM tools, but I have often thought that for large updates (thousands of rows), it seems inefficient to load, update and save when something like ``` UPDATE [table] set [column] = [value] WHERE [predicate] ``` would give much better performance. However, assuming one wanted to go down this route for performance reasons, how would you then make sure that any objects cached in memory were updated correctly. Say you're using LINQ to SQL, and you've been working on a DataContext, how do you make sure that your high-performance UPDATE is reflected in the DataContext's object graph? This might be a "you don't" or "use triggers on the DB to call .NET code that drops the cache" etc etc, but I'm interested to hear common solutions to this sort of problem.
You're right, in this instance using an ORM to load, change and then persist records is not efficient. My process goes something like this 1) Early implementation use ORM, in my case NHibernate, exclusively 2) As development matures identify performance issues, which will include large updates 3) Refactor those out to sql or SP approach 4) Use Refresh(object) command to update cached objects, My big problem has been informing other clients that the update has occured. In most instances we have accepted that some clients will be stale, which is the case with standard ORM usage anyway, and then check a timestamp on update/insert.
Most ORMs also have facilities for performing large or "bulk" updates efficiently. The Stateless Session is one such mechanism available in Hibernate for Java which apparently will be available in NHibernate 2.x: <http://ayende.com/Blog/archive/2007/11/13/What-is-going-on-with-NHibernate-2.0.aspx>
Large volume database updates with an ORM
[ "", "sql", "database", "performance", "orm", "caching", "" ]
I'm seeing performance problems with retrieving multiple instances of objects that have many relationships with other objects. I'm using Spring and Hibernate's JPA implementation with MySQL. The issue is that when executing a JPA query, Hibernate does not automatically join to other tables. This results in n\*r + 1 SQL queries, where n is the number of objects being retrieved and r is the number of relationships. Example, a Person lives at an Address, has many Hobbies, and has visited many Countries: ``` @Entity public class Person { @Id public Integer personId; public String name; @ManyToOne public Address address; @ManyToMany public Set<Hobby> hobbies; @ManyToMany public Set<Country> countriesVisited; } ``` When I perform a JPA query to get all Persons named Bob, and there are 100 Bobs in the database: ``` SELECT p FROM Person p WHERE p.name='Bob' ``` Hibernate translates this to 301 SQL queries: ``` SELECT ... FROM Person WHERE name='Bob' SELECT ... FROM Address WHERE personId=1 SELECT ... FROM Address WHERE personId=2 ... SELECT ... FROM Hobby WHERE personId=1 SELECT ... FROM Hobby WHERE personId=2 ... SELECT ... FROM Country WHERE personId=1 SELECT ... FROM Country WHERE personId=2 ... ``` According to the Hibernate FAQ ([here](http://www.hibernate.org/118.html#A23) and [here](http://www.hibernate.org/117.html#A30)), the solution is to specify LEFT JOIN or [LEFT OUTER JOIN (for many-to-many)](http://www.hibernate.org/117.html#A12) in the query. So now my query looks like: ``` SELECT p, a, h, c FROM Person p LEFT JOIN p.address a LEFT OUTER JOIN p.hobbies h LEFT OUTER JOIN p.countriesVisited c WHERE p.name = 'Bob' ``` This works, but there appears to be a bug if there's more than one LEFT OUTER JOIN in which case Hibernate is incorrectly looking for a non-existent column: ``` could not read column value from result set: personId69_2_; Column 'personId69_2_' not found. ``` The bug behavior appears to be possibly addressed by [Hibernate Core bug HHH-3636](http://opensource.atlassian.com/projects/hibernate/browse/HHH-3636). Unfortunately the fix is not part of any released Hibernate JAR. I've ran my application against the snapshot build but the bug behavior is still present. I've also built my own Hibernate Core JAR from the latest code in the repository and the bug behavior is still present. So maybe HHH-3636 doesn't address this. This Hibernate performance limitation is very frustrating. If I query for 1000 objects then 1000\*r + 1 SQL queries are made to the database. In my case I have 8 relationships so I get 8001 SQL queries, which results in horrible performance. The official Hibernate solution to this is to left join all relationships. But this isn't possible with more than one many-to-many relationships due to the bug behavior. So I'm stuck with left joins for many-to-one relationships and n\*r+1 queries due to the many-to-many relationships. I plan to submit the LEFT OUTER JOIN problem as a Hibernate bug, but in the meantime my customer needs an app that has reasonable performance. I currently use a combination of batch fetch (BatchSize), ehcache and custom in-memory caching but the performance is still pretty poor (it improved retrieving 5000 objects from 30 to 8 seconds). The bottom line is that too many SQL queries are hitting the database. So, my questions, is it possible to use Hibernate in performance sensitive applications where tables have multiple relationships with each other? I would love to hear how successful Hibernate uses address performance. Should I be hand writing SQL (which somewhat defeats the purpose of using Hibernate)? Should I de-normalize my database schema to reduce the number of joined tables? Should I not be using Hibernate if I need fast query performance? Is there something faster?
See my answer to your [other question](https://stackoverflow.com/questions/467282/jpa-hibernate-maximum-number-of-joins), if you read the whole of the FAQ you linked to: > Follow the best practices guide! Ensure that all and mappings specify lazy="true" in Hibernate2 (this is the new default in Hibernate3). Use HQL LEFT JOIN FETCH to specify which associations you need to be retrieved in the initial SQL SELECT. > > A second way to avoid the n+1 selects problem is to use ***fetch="subselect"*** in Hibernate3. > > If you are still unsure, refer to the Hibernate documentation and Hibernate in Action. See the tips on [improving performance](http://www.hibernate.org/hib_docs/v3/reference/en-US/html/performance.html). If you are not careful with joins, you will end up with [Cartesian Product](http://en.wikipedia.org/wiki/Cartesian_product) problems.
Besides "fetch" strategy you might also try setting batch fetch size in hibernate properties, so it will run joining queries not one by one but in batches. In your appContext.xml: ``` <bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean"> ... <property name="hibernateProperties"> <props> ... <prop key="hibernate.default_batch_fetch_size">32</prop> </props> </property> </bean> ``` So instead of: ``` SELECT ... FROM Hobby WHERE personId=1 SELECT ... FROM Hobby WHERE personId=2 ``` You will get: ``` SELECT ... FROM Hobby WHERE personId in (1,2,...,32); SELECT ... FROM Hobby WHERE personId in (33,34,...,64); ```
Can Hibernate be used in performance sensitive applications?
[ "", "java", "performance", "hibernate", "jpa", "jakarta-ee", "" ]
I would like to make a free open-source C++ application for both Linux and Windows which will create live stock market charts (i.e. they're refreshed frequently). Please could you give me some pointers on these issues: * What should I use as the data source? Are there free services I can implement? I would like to use the same or similar information as companies like [Google](http://www.google.co.uk/finance?q=LON:RBS). * I'm not sure what GUI toolkit would be best to use, is there one which has charting built in, or would I need to use a specialized library for this? Some things to note: * This is my first attempt at both cross-platform C++ development, and a GUI application for Linux. * I'm based in the UK, so I'd like to use data sources that provide information for the London stock exchange (LON) as well as NASDAQ, etc.
## As of Nov 2014, these links are dead. * Google Finance API: <http://code.google.com/apis/finance/> * Yahoo! Finance API: <http://developer.yahoo.com/finance/> * Cross-platform C++ charts w/ [Qt](http://www.qtsoftware.com/products/): <http://www.int.com/products/2d/carnac/chart_component.htm>
Assuming the rules in the UK are the same as in the US, you basically have 3-tiered choices. You can hack together a lame feed from things like Google or Yahoo but you absolutely are not getting every tick, if that is what you are after. A step up from the obvious internet sources are some of the online brokers. Their data is more reliable and timely but obviously you need an account and they have to offer some kind of API. Check into something like InteractiveBrokers.com. They are mostly java centric but offer a Window's based C++ DLL as well. Several other brokers offer similar APIs but IB is excellent in that it covers a multitude of exchanges including, I believe, London. They also make it relatively easy to transfer currencies if that is a concern. Lastly you have to go to commercial brokers. You can find them easily enough with a search but be prepared to pay a couple of hundred dollars per month minimum. I think Mark's suggestion of QT is a good way to go for a GUI. Java tends to be adequate for putting up a grid of running quotes but tends to fail in the charting area, IMO.
What data source could I use for my stock market program?
[ "", "c++", "open-source", "stocks", "trading", "" ]
## Edit: For personn interested in a cleaner way to implemenent that, have a look to that [answer](https://stackoverflow.com/questions/847279/code-reuse-in-exception-handling/847316#847316). --- In my job I often need to use third-made API to access remote system. For instance to create a request and send it to the remote system: ``` #include "external_lib.h" void SendRequest(UserRequest user_request) { try { external_lib::Request my_request; my_request.SetPrice(user_request.price); my_request.SetVolume(user_request.quantity); my_request.SetVisibleVolume(user_request.quantity); my_request.SetReference(user_request.instrument); my_request.SetUserID(user_request.user_name); my_request.SetUserPassword(user_request.user_name); // Meny other member affectations ... } catch(external_lib::out_of_range_error& e) { // Price , volume ???? } catch(external_lib::error_t& e) { // Here I need to tell the user what was going wrong } } ``` Each lib's setter do checks the values that the end user has provided, and may thow an exception when the user does not comply with remote system needs. For instance a specific user may be disallowed to send a too big volume. That's an example, and actually many times users tries does not comply: no long valid instrument, the prices is out of the limit, etc, etc. *Conseqently, our end user **need** an explicit error message to tell him what to modify in its request to get a second chance to compose a valid request. I have to provide hiim such hints* Whatever , external lib's exceptions (mostly) never specifies which field is the source of aborting the request. What is the best way, according to you, to handle those exceptions? My first try at handling those exceptions was to "wrap" the Request class with mine. Each setters are then wrapped in a method which does only one thing : a try/catch block. The catch block then throws a new exceptions of mine : my\_out\_of\_range\_volume, or my\_out\_of\_range\_price depending on the setter. For instance SetVolume() will be wrapped this way: ``` My_Request::SetVolume(const int volume) { try { m_Request.SetVolume(volume); } catch(external_lib::out_range_error& e) { throw my_out_of_range_volume(volume, e); } } ``` What do you think of it? What do you think about the exception handling overhead it implies? ... :/ Well the question is open, I need new idea to get rid of that lib constraints!
If there really are a lot of methods you need to call, you could cut down on the code using a [reflection library](http://www.codeproject.com/KB/library/libreflection.aspx), by creating just one method to do the calling and exception handling, and passing in the name of the method/property to call/set as an argument. You'd still have the same amount of try/catch calls, but the code would be simpler and you'd already know the name of the method that failed. Alternatively, depending on the type of exception object that they throw back, it may contain stack information or you could use another library to walk the stack trace to get the name of the last method that it failed on. This depends on the platform you're using.
I always prefer a wrapper whenever I'm using third party library. It allows me to define my own exception handling mechanism avoiding users of my class to know about external library. Also, if later the third party changes the exception handling to return codes then my users need not be affected. But rather than throwing the exception back to my users I would implement the error codes. Something like this: ``` class MyRequest { enum RequestErrorCode { PRICE_OUT_OF_LIMIT, VOLUME_OUT_OF_LIMIT, ... ... ... }; bool SetPrice(const int price , RequestErrorCode& ErrorCode_out); ... private: external_lib::Request mRequest; }; bool MyRequest::SetPrice(const int price , RequestErrorCode& ErrorCode_out) { bool bReturn = true; try { bReturn = mRequest.SetPrice(price); } catch(external_lib::out_of_range_error& e) { ErrorCode_out = PRICE_OUT_OF_LIMIT; bReturn = false; } return bReturn; } bool SendRequest(UserRequest user_request) { MyRequest my_request; MyRequest::RequestErrorCode anErrorCode; bool bReturn = my_request.SetPrice(user_request.price, anErrorCode); if( false == bReturn) { //Get the error code and process //ex:PRICE_OUT_OF_LIMIT } } ```
Exception handling aware of execution flow
[ "", "c++", "exception", "" ]
I am using: ``` if (RadioButtonList_VolunteerType.SelectedItem != null) ``` or how about: ``` if (RadioButtonList_VolunteerType.Index >= 0) ``` or how about (per Andrew Hare's answer): ``` if (RadioButtonList_VolunteerType.Index > -1) ``` To those who may read this question, **the following is not a valid method**. As Keltex pointed out, the selected value could be an empty string. ``` if (string.IsNullOrEmpty(RadioButtonList_VolunteerType.SelectedValue)) ```
In terms of readability they all lack something for me. This seems like a good candidate for an extension method. ``` public static class MyExtenstionMethods { public static bool HasSelectedValue(this RadioButtonList list) { return list.SelectedItem != null; } } ... if (RadioButtonList_VolunteerType.HasSelectedValue) { // do stuff } ```
Those are all valid and perfectly legitimate ways of checking for a selected value. Personally I find ``` RadioButtonList_VolunteerType.SelectedIndex > -1 ``` to be the clearest.
What is the best way to see if a RadioButtonList has a selected value?
[ "", "c#", "asp.net", "validation", "radiobuttonlist", "" ]
C# looks to have 4 different symmetric crypto algorithms: RijndaelManaged, DESCryptoServiceProvider, RC2CryptoServiceProvider, and TripleDESCryptoServiceProvider. I am looking for more information between them. Mainly what is the differences between each of them. MSDN isn't being much help, or I am just tired. ;) I am sure there is pro and cons between each of them, just like anything where there are multiple ways of doing something. Thank you for any enlightenment. Tony
This the Ranking (for year 2015) the strongest algorithm appears on top: * Rijndael (more commonly referred to as [AES](http://en.wikipedia.org/wiki/Advanced_Encryption_Standard)) * [Triple DES](http://en.wikipedia.org/wiki/Triple_DES) * [DES](http://en.wikipedia.org/wiki/Data_Encryption_Standard) * [RC2](http://en.wikipedia.org/wiki/RC2) Use AES. In more details: * DES is the old "data encryption standard" from the seventies. Its key size is too short for proper security (56 effective bits; this can be brute-forced, as has been demonstrated [more than ten years ago](http://en.wikipedia.org/wiki/Data_Encryption_Standard)). Also, DES uses 64-bit blocks, which raises some potential issues when encrypting several gigabytes of data with the same key (a gigabyte is not that big nowadays). * 3DES is a trick to reuse DES implementations, by cascading three instances of DES (with distinct keys). 3DES is believed to be secure up to at least "*2112*" security (which is quite a lot, and quite far in the realm of "not breakable with today's technology"). But it is slow, especially in software (DES was designed for efficient hardware implementation, but it sucks in software; and 3DES sucks three times as much). * AES is the successor of DES as standard symmetric encryption algorithm for US federal organizations (and as standard for pretty much everybody else, too). AES accepts keys of 128, 192 or 256 bits (128 bits is already very unbreakable), uses 128-bit blocks (so no issue there), and is efficient in both software and hardware. It was selected through an open competition involving hundreds of cryptographers during several years. Basically, you cannot have better than that. So, when in doubt, use AES. Note that a block cipher is a box which encrypts "blocks" (128-bit chunks of data with AES). When encrypting a "message" which may be longer than 128 bits, the message must be split into blocks, and the actual way you do the split is called the [mode of operation](http://en.wikipedia.org/wiki/RC2) or "chaining". The naive mode (simple split) is called ECB and has issues. Using a block cipher properly is not easy, and it is more important than selecting between, e.g., AES or 3DES. <http://en.wikipedia.org/wiki/EFF_DES_cracker> <http://en.wikipedia.org/wiki/Block_cipher_modes_of_operation>
Short answer: ***use Rijndael***. What the various options are: [RC2](http://en.wikipedia.org/wiki/RC2) is a weak, broken cipher built in the late 80s for export, because at the time American companies were restricted from exporting 'strong' encryption. It has a key length of 40 bits, which makes brute forcing it on today's hardware trivial (it is, after all, 20 years later). It's name stands for Rivest Cipher No. 2, after it's creator Ron Rivest (a world-renown crpytographer, the 'R' in RSA). [DES](http://en.wikipedia.org/wiki/Data_Encryption_Standard) was the Data Encryption Standard, and was termed strong crpytography. With a key length of 56 bits, however, it is now [within range of brute-force decryption](http://en.wikipedia.org/wiki/DESCHALL_Project). [3DES](http://en.wikipedia.org/wiki/3des) is running DES three times. Just running DES twice doesn't make it much stronger, actually, but the third time does. It is effectively 116 bit encrpytion (with a 196-bit key). 3DES is a very good, strong encrpytion by today's standard. So RC2, DES and 3DES are in the cipher suite to provide compatibility with business systems that use those ciphers. Rijndael is however the modern cipher of choice. It is the official replacement for DES, termed the [Advanced Encryption Standard (AES)](http://en.wikipedia.org/wiki/Advanced_Encryption_Standard). It comes in a range of keysizes, but it is [important](http://www.schneier.com/blog/archives/2009/07/another_new_aes.html) to ***use 128-bit***. Only use other key lengths (including the longest, 256-bit) for compatibility reasons.
Difference between symmetric crypto algorithms
[ "", "c#", "encryption", "rijndaelmanaged", "" ]
I'm looking for a better way to call functions based on a variable in Python vs using if/else statements like below. Each status code has a corresponding function ``` if status == 'CONNECT': return connect(*args, **kwargs) elif status == 'RAWFEED': return rawfeed(*args, **kwargs) elif status == 'RAWCONFIG': return rawconfig(*args, **kwargs) elif status == 'TESTFEED': return testfeed(*args, **kwargs) ... ``` I assume this will require some sort of factory function but unsure as to the syntax
The canonical way to do this is to use a dictionary to emulate `switch` or `if/elif`. You will find several questions to similar problems here on SO. Put your functions into a dictionary with your status codes as keys: ``` funcs = { 'CONNECT': connect, 'RAWFEED': rawfeed, 'RAWCONFIG' : rawconfig, 'TESTFEED': testfeed } funcs[status](*args, **kwargs) ```
you might find [`getattr`](http://docs.python.org/library/functions.html?highlight=getattr#getattr) useful, I guess ``` import module getattr(module, status.lower())(*args, **kwargs) ```
Python dynamic function names
[ "", "python", "factory", "" ]
Is there any select statement to return the list of columns in the table?
The INFORMATION\_SCHEMA.COLUMNS view will provide the column names for a particular table name. ``` SELECT Column_Name + ', ' FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'Table_Name' ``` There are several other views as well as the one above which you may find useful. These INFORMATION\_SCHEMA views provide information on the schema of your database. ``` Select top 10 * from Information_Schema.tables Select top 10 * from Information_Schema.views Select top 10 * from Information_Schema.routines Select top 10 * from Information_Schema.parameters ```
sp\_help TableName Will give you all columns, plus lots of other information.
What is the Select statement to return the column names in a table
[ "", "sql", "sql-server", "sql-server-2005", "" ]
Today, I found myself coding something like this ... ``` public class LocalEnums { public LocalEnums() { } public void foo() { enum LocalEnum { A,B,C }; // .... // class LocalClass { } } } ``` and I was kind of surprised when the compiler reported an error on the local `enum`: > The member enum LocalEnum cannot be > local Why can't **enums** be declared local like **classes**? I found this very useful in certain situations. In the case I was working, the rest of the code didn't need to know anything about the `enum`. Is there any *structural/design* conflict that explains why this is not possible or could this be a *future* feature of Java?
Other Answers are outmoded as of Java 16 (released 2021-03) and Java 17 (released 2021-09). # Local enums in Java 16+ As part of the [records](https://openjdk.java.net/jeps/395) feature introduced in [Java 16](https://en.wikipedia.org/wiki/Java_version_history#Java_SE_16), enums may now be defined locally. Indeed, **records, enums, and interfaces can all be local** now. To quote JEP 395: > The ability to declare local record classes, local enum classes, and local interfaces was introduced. > > … > > The addition of local record classes is an opportunity to add other kinds of implicitly-static local declarations. > > Nested enum classes and nested interfaces are already implicitly static, so for consistency we define local enum classes and local interfaces, which are also implicitly static. You can now run the following example code to use an enum defined within a method. ``` private void demoLocalEnum ( ) { enum Color { PURPLE, SAFETY_ORANGE } System.out.println( Color.PURPLE ); } ``` In this screenshot, we can see how the local enum exists only within its defining method. A sibling method cannot see that enum. Trying to call that enum from another method generates an error. [![Screenshot of an error caused by a sibling method trying to call a local enum defined in some other method.](https://i.stack.imgur.com/0q6TU.png)](https://i.stack.imgur.com/0q6TU.png) See a [demo of such code running](https://www.youtube.com/watch?v=lgZRMCpfYM4&feature=youtu.be&t=91) in the [IntelliJ](https://en.wikipedia.org/wiki/IntelliJ_IDEA) 2020.2 [IDE](https://en.wikipedia.org/wiki/Integrated_development_environment). ## Implicitly `static` There is one limitation with a locally defined enum: No access to state in surrounding class. Example code: ``` private void demoLocalEnum () { int x = 42; enum Color { PURPLE, SAFETY_ORANGE; public void demo () { System.out.println( "Now is " + Instant.now() ); // This line works. System.out.println( "x = " + x ); // ERROR — Non-static variable 'x' cannot be referenced from a static context. } } Color.PURPLE.demo(); } ``` My [IntelliJ](https://en.wikipedia.org/wiki/IntelliJ_IDEA) [IDE](https://en.wikipedia.org/wiki/Integrated_development_environment) reports error: > Non-static variable 'x' cannot be referenced from a static context As mentioned in the JEP 395 quote above, a local enum is implicitly `static`. So any methods you may define on your local enum cannot access state on the surrounding outer class. To quote JEP 395, regarding local records but applying to local enums as well: > Local record classes are a particular case of nested record classes. Like nested record classes, local record classes are implicitly static. This means that their own methods cannot access any variables of the enclosing method; in turn, this avoids capturing an immediately enclosing instance which would silently add state to the record class. The fact that local record classes are implicitly static is in contrast to local classes, which are not implicitly static. In fact, local classes are never static — implicitly or explicitly — and can always access variables in the enclosing method.
**Enums are static nested classes** because they *define static member variables (the enum values)*, and this is *disallowed for inner classes*: <http://docs.oracle.com/javase/specs/jls/se7/html/jls-8.html#jls-8.1.3> **Update:** I was looking through the `JLS` (*java language specification*) for more detail on the restrictions of static nested classes, and didn't find it (although it's probably there, hidden under a different topic). From a pure implementation perspective, there's no reason that this couldn't be done. So I suspect that it was a language philosophy issue: it shouldn't be done, therefore won't be supported. But I wasn't there, so that's pure speculation. **As a comment:** if your methods are large enough that they require their own enums, then it's a strong sign that you need refactoring.
Why can't enums be declared locally in a method?
[ "", "java", "enums", "" ]
I have an LDAP query, which I am using to perform a search in C#. It uses two string variables (username and domain) which need to be escaped for security reasons. How should I escape the strings? Is there a function available in C#.NET to do this? --- Example LDAP search conditions : ``` (objectCategory=person) (userprincipalname=username@domain*) (samaccountname=username) ``` Example LDAP query string in C# : ``` string search = "(&(&(objectCategory=person)(userprincipalname=" + username + "@" + domain + "*)(samaccountname=" + username + ")))"; ``` Edit: I already have the LDAP query working, and returning results. All I want is to escape the parameters.
The following is my translation from the Java code mentioned by Sophia into C#. ``` /// <summary> /// Escapes the LDAP search filter to prevent LDAP injection attacks. /// </summary> /// <param name="searchFilter">The search filter.</param> /// <see cref="https://blogs.oracle.com/shankar/entry/what_is_ldap_injection" /> /// <see cref="http://msdn.microsoft.com/en-us/library/aa746475.aspx" /> /// <returns>The escaped search filter.</returns> private static string EscapeLdapSearchFilter(string searchFilter) { StringBuilder escape = new StringBuilder(); // If using JDK >= 1.5 consider using StringBuilder for (int i = 0; i < searchFilter.Length; ++i) { char current = searchFilter[i]; switch (current) { case '\\': escape.Append(@"\5c"); break; case '*': escape.Append(@"\2a"); break; case '(': escape.Append(@"\28"); break; case ')': escape.Append(@"\29"); break; case '\u0000': escape.Append(@"\00"); break; case '/': escape.Append(@"\2f"); break; default: escape.Append(current); break; } } return escape.ToString(); } ```
I found a solution here, in [a blog post about LDAP Injection](http://web.archive.org/web/20160922224553/http://blogs.oracle.com/shankar/entry/what_is_ldap_injection) This solution involves adding your own function to escape the username and domain name, his solution is in Java, but the idea is there. Also [MSDN](http://msdn.microsoft.com/en-us/library/aa746475.aspx) lists which special characters need to be replaced by escape sequences. As far as I can tell there doesn't seem to be any method for escaping LDAP strings in System.DirectoryServices (like there is in HttpServerUtility for URLs etc)
How to escape a string in C#, for use in an LDAP query
[ "", "c#", ".net", "active-directory", "ldap", "ldap-query", "" ]
Consider this... I am writing a class named Cache which will accept either a path to a file/url or a string. I am going to use PHP's functions such as `parse_url()` and `is_file()` to determine which input I am receiving. here is my example, in PHP ``` class Cache { public function __construct($pathUriOrString) { } } ``` What is the best practice for naming this argument? Is this even a valid way of creating an class, or should this be a base class and have separate classes that extend it? I got this idea from [php image](http://code.google.com/p/php-image/) where the construct either receives one argument (a path) or 2 arguments (a width and height). So, am I on the right track, and if so, what is best practice for naming an argument which takes different inputs (and won't confuse another developer down the track?)
Could you possibly call the variable $resourcelocation and document it accordingly, i.e. it should take a file path, uri path or a string. I don't think it's good practice to call a variable aOrB, it should be generic. You could possibly improve this by checking the input to the function as to what type it is, and whether it is valid. If it matches neither of the supported argument types then you should throw an error for an illegal parameter. The class declaration is fine (but missing an opening bracket) btw...
Better to subclass it twice, once for strings and another for urls. And if the user is entering one or the other, refactor so they must specify. (If not, then presumably your app knows which it's dealing with - pass through explicitly what it knows.) Try to design out this kind of ambiguity. I hate to ask, but what's the third thing it could mean?
Best practice for naming an argument that can mean 3 different things
[ "", "php", "" ]
I'm a blitz++ newbie. So far, so good, but I'm a bit mystified why the commented out line in the code below fails to compile with ``` error: conversion from ‘blitz::_bz_tinyMatExpr<blitz::_bz_tinyMatrixMatrixProduct<double, double, 3, 3, 3, 3, 1, 3, 1> >’ to non-scalar type ‘const m33’ requested ``` I'm on Debian/Lenny (g++ 4.3.2, Blitz 0.9). Here's the code: ``` #include <blitz/blitz.h> #include <blitz/array.h> #include <blitz/matrix.h> #include <blitz/matexpr.h> #include <blitz/tinymat.h> #include <blitz/tinymatexpr.h> #include <blitz/tinyvec.h> #include <blitz/tinyvec-et.h> #include <blitz/vector.h> #include <blitz/vector-et.h> typedef blitz::TinyVector<double,3> v3; typedef blitz::TinyMatrix<double,3,3> m33; int main(int,char**) { const m33 a; const m33 b; m33 c;c=blitz::product(a,b); // Compiles OK //const m33 d=blitz::product(a,b); // Fails to compile. return 0; } ``` I do like to be const-ed to the hilt, so it'd be nice to know if there's a way of getting it to work (experience with Blitz++ so far suggests it might just be a matter of picking the right includes...).
I have had a look at the source code of Blitz++. As surprising as it may seem, there is **no** template constructor for TinyMatrix, but there is a template = operator. That means that you cannot do what you are trying to do. So I'd suggest forgetting about your matrix being *const*. Or find another way like creating a non-const matrix that you would pass as a const reference as the parameter of a function. Now, just for fun, the truth is you could copy template operator=() code and make a new template constructor inside blitz/tinymat.h out of it, but i wouldn't ! If you **really** want to, here's how : ``` // Turn the following code... template<typename T_expr> TinyMatrix<T_numtype, N_rows, N_columns>& operator=(_bz_tinyMatExpr<T_expr> expr) { // USEFUL CODE return *this; } // ...into this : template<typename T_expr> TinyMatrix(_bz_tinyMatExpr<T_expr> expr) { // USEFUL CODE } ``` and your code compiles (and probably works).
``` //const m33 d=blitz::product(a,b); // Fails to compile. const m33 d; const_cast<m33>(d) = blitz::product(a,b); ```
Why doesn't this Blitz++ code compile?
[ "", "c++", "templates", "linear-algebra", "blitz++", "expression-templates", "" ]
I am writing a server program which is used to run unit tests of an API *(displaying lots of information and providing web access to control / monitor the whole thing)...* This API is **known to the server during compile time** and is provided as a JAR. To be able to compare between unit test results of **different versions** of the API (without restarting the server), I want to be able to unload the 'current' version of the API, and to reload a newer one (or an older one). I don't want to use URLClassLoader and invoke every single method by name ( using **`getDeclaredMethod("someMethod")`** ), because the server heavily depends on the API and it would be complicated to 'wrap' every method call in such dirty way. I was thinking: Since all interfaces of **all** versions of the JAR are **same**, couldn't I do it by somehow reloading an other version of the JAR (without that by-name-invokation?). *Note: I am using latest Java SE (6) and Java EE (5).* If you think, what I'm trying to achieve is not possible, please suggest a 'workaround' or a different concept.
I think if you load a class using ``` Class.forName(clsname, init, classloader); ``` ([Javadoc](http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Class.html#forName(java.lang.String,%20boolean,%20java.lang.ClassLoader)) here) you will get an instance of the class provided by the given classloader. Everything loaded because of that class will also be loaded via the same classloader. As long as you're very careful with the objects instantiated from this point on (to allow for GC), you should be able to reload different versions. I did this once before with Java 1.3, it took a lot of debugging, but at the end I had a "bootstrap" application that loaded a `Runnable` class by name and was able to "soft-restart" by instantiating a new classloader against a different URL and going again.
You can use the opensource package : **JclLoader** which helps in loading different versions of the same jar. This was also a need in one of our systems to do testing . Link: <http://sourceforge.net/projects/jcloader/>
Can I dynamically unload and reload (other versions of the same) JAR?
[ "", "java", "jakarta-ee", "jar", "" ]
I am working on rendering a set of cart items using a user control. Each cart item can be removed via a button in the user control. When a cart item is removed I need to visually show it's removal. However, since the cart item existed during the loading of the page it remains until the page is refreshed again. What I am after is a means to refresh the page after the work to remove the cartitem has been completed. The code behind cart.aspx.cs looks like: ``` protected void Page_Init(object sender, EventArgs e) { CreateCartItemControls(); } private void CreateCartItemControls() { foreach (CartItem ci in Profile.Cart.Items) { ASP.CartItemControl cic = new ASP.CartItemControl(); cic.ItemName = ci.Name; cic.CartID = ci.ID; cic.Cost = ci.BaseCost.ToString("c"); cic.ItemComponents = ci.Components; cic.CartItemRemoved += new EventHandler(CartItemRemoved); Content.Controls.Add(cic); } } void CartItemRemoved(object sender, EventArgs e) { Master.UpdateCartItemCount(); } ``` Markup for CartItemControl.ascx ``` <%@ Control Language="C#" ClassName="CartItemControl" AutoEventWireup="true" CodeFile="CartItemControl.ascx.cs" Inherits="UserControls_CartItemControl" %> <fieldset id="FieldSet" runat="server"> <legend> <asp:HyperLink ID="ItemLink" runat="server" /> </legend> <asp:ImageButton ID="RemoveCartItem" AlternateText="Remove Item" ImageUrl="~/img/buttons/remove_4c.gif" runat="server" CommandName="Remove" OnCommand="RemoveCartItem_Command" /> <asp:Label ID="TotalItemCost" runat="server" Text="$0.00" /> <ol> <li runat="server" id="ComponentsLI" visible="false"> <fieldset id="ComponentsFieldSet" runat="server"> <legend>Item Components</legend> <asp:CheckBoxList ID="ItemComponentsCheckList" runat="server" /> </fieldset> </li> </ol> </fieldset> ``` Code behind for the UserControl CartItemControl.ascx.cs ``` public partial class UserControls_CartItemControl : System.Web.UI.UserControl { public string ItemName { get; set; } public int CartID { get; set; } public string Cost { get; set; } public IDictionary<int, SoftwareComponent> ItemComponents { get; set; } protected void Page_PreRender(object sender, EventArgs e) { SetCartItemControlAttributes(); } private void SetCartItemControlAttributes() { ItemLink.Text = ItemName; TotalItemCost.Text = Cost; RemoveCartItem.CommandArgument = CartID.ToString(); if (!ItemComponents.Count.Equals(0)) { ComponentsLI.Visible = true; foreach (KeyValuePair<int, ItemComponent> kvp in ItemComponents) { ItemComponentsCheckList.Items.Add( new ListItem(string.Format("{0} {1}", kvp.Value.ComponentName, kvp.Value.ComponentCost.ToString("c")), kvp.Key.ToString())); } } } public event EventHandler CartItemRemoved; protected void RemoveCartItem_Command(object sender, CommandEventArgs e) { int itemID; if (int.TryParse(e.CommandArgument.ToString(), out itemID)) { Profile.Cart.RemoveCartItem(itemID); CartItemRemoved(sender, e); Parent.Controls.Remove(this); } } } ```
Just as you add CartItemControls to Content's Controls collection on init, you need to remove them on RemoveCartItem\_Command. Do so by either exposing your own ItemRemoved event and handling it in the main page or by calling Parent.Controls.Remove(this) inside the RemoveCartItem\_Command. Or am I missing something?
Response.Redirect back to the page after you do the work to remove the cart item.
User Control Postback
[ "", "c#", "asp.net", "postback", "user-controls", "" ]
How do you store a password entered by the user in memory and erase it securely after it is no longer need? To elaborate, currently we have the following code: ``` username = raw_input('User name: ') password = getpass.getpass() mail = imaplib.IMAP4(MAIL_HOST) mail.login(username, password) ``` After calling the `login` method, what do we need to do to fill the area of memory that contains password with garbled characters so that someone cannot recover the password by doing a core dump? There is a similar question, however it is in Java and the solution uses character arrays: [How does one store password hashes securely in memory, when creating accounts?](https://stackoverflow.com/questions/646224/how-does-one-store-password-hashes-securely-in-memory-when-creating-accounts) Can this be done in Python?
Python doesn't have that low of a level of control over memory. Accept it, and move on. The **best** you can do is to `del password` after calling `mail.login` so that no references to the password string object remain. Any solution that purports to be able to do more than that is only giving you a false sense of security. Python string objects are immutable; there's no direct way to change the contents of a string after it is created. *Even if* you were able to somehow overwrite the contents of the string referred to by `password` (which is technically possible with stupid ctypes tricks), there would still be other copies of the password that have been created in various string operations: * by the getpass module when it strips the trailing newline off of the inputted password * by the imaplib module when it quotes the password and then creates the complete IMAP command before passing it off to the socket You would somehow have to get references to all of those strings and overwrite their memory as well.
There actually -is- a way to securely erase strings in Python; use the memset C function, as per [Mark data as sensitive in python](https://stackoverflow.com/questions/982682/mark-data-as-sensitive-in-python/983525#983525) Edited to add, long after the post was made: [here's a deeper dive into string interning](http://guilload.com/python-string-interning/). There are some circumstances (primarily involving non-constant strings) where interning does not happen, making cleanup of the string value slightly more explicit, based on CPython reference counting GC. (Though still not a "scrubbing" / "sanitizing" cleanup.)
Securely Erasing Password in Memory (Python)
[ "", "python", "security", "passwords", "" ]
I have a DataTable which has some rows and I am using the select to filter the rows to get a collection of DataRows which I then loop through using foreach and add it to another DataTable, but it is giving me the error "This Row already belongs to another table". Here is the code: ``` DataTable dt = (DataTable)Session["dtAllOrders"]; DataTable dtSpecificOrders = new DataTable(); DataRow[] orderRows = dt.Select("CustomerID = 2"); foreach (DataRow dr in orderRows) { dtSpecificOrders.Rows.Add(dr); //Error thrown here. } ```
You need to create a new `Row` with the values from `dr` first. A `DataRow` can only belong to a single `DataTable`. You can also use `Add` which takes an array of values: ``` myTable.Rows.Add(dr.ItemArray) ``` Or probably even better: ``` // This works because the row was added to the original table. myTable.ImportRow(dr); // The following won't work. No data will be added or exception thrown. var drFail = dt.NewRow() drFail["CustomerID"] = "[Your data here]"; // dt.Rows.Add(row); // Uncomment for import to succeed. myTable.ImportRow(drFail); ```
Try this: ``` DataTable dt = (DataTable)Session["dtAllOrders"]; DataTable dtSpecificOrders = dt.Clone(); DataRow[] orderRows = dt.Select("CustomerID = 2"); foreach (DataRow dr in orderRows) { dtSpecificOrders.ImportRow(dr); } ```
This Row already belongs to another table error when trying to add rows?
[ "", "c#", "" ]
I've noticed that certain command cause LINQtoSQL to connect to the database and download the records that are part of the query, for example, .ToArray(). Does the command .Cast() cause a query to execute (and how can I tell these things in the future?). For example... ``` IRevision<T> current = context.GetTable(typeof(T)) .Cast<IRevision<T>>() .SingleOrDefault(o => o.ID == recordId); ``` I know there is a command for .GetTable that allows you to specify a generic type, but for strange and unexplainable reasons, it cannot be used in this situation.
From [Enumerable.Cast()](http://msdn.microsoft.com/en-us/library/bb341406.aspx)'s remarks: > This method is implemented by using deferred execution. The immediate return value is an object that stores all the information that is required to perform the action. The query represented by this method is not executed until the object is enumerated either by calling its GetEnumerator method directly or by using foreach in Visual C# or For Each in Visual Basic. All of the LINQ operators will let you know if they are deferred execution or immediate query execution. Additionally, here are the standard LINQ operators which are NOT deferred: * Aggregate * All * Any * Average * Contains * Count * ElementAt * ElementAtOrDefault * First * FirstOrDefault * Last * LastOrDefault * LongCount * Max * Min * SequenceEqual * Single * SingleOrDefault * Sum * ToArray * ToDictionary * ToList * ToLookup
No, it does not. It simply will perform a cast when you iterate through the IEnumerable. There isn't any definitive way (in code) to know whether or not a method will use deferred execution or not. The documentation is going to be your best friend here as it will tell you if it defers execution or not. However, that doesn't mean that you can't make some assumptions if the documentation is unclear. If you have a method that returns another list/structure (like ToList, ToArray), then it will have to execute the query in order to populate the new data structure. If the method returns a scalar value, then it will have to execute the query to generate that scalar value. Other than that, if it simply returns `IEnumerable<T>`, then it more-than-likely is deferring execution. However, that doesn't mean that it's guaranteed, it just means it is more-than-likely.
LINQ - Does .Cast<T>() Select Records?
[ "", "c#", "linq", "linq-to-sql", "records", "" ]
I'm having a bit of a problem with a singleton class I'm exposing via remoting. In my server I have: ``` TcpChannel channel = new TcpChannel( Settings.Default.RemotingPort ); ChannelServices.RegisterChannel( channel, false ); RemotingConfiguration.RegisterWellKnownServiceType( typeof( RemotableObject ), "RemotableObject", WellKnownObjectMode.Singleton ); ``` RemotableObject is a singleton object that inherits MarshalByRefObject. My client connects to it via: ``` remoteObject = (RemotableObject)Activator.GetObject( typeof( RemotableObject ), string.Format( "tcp://{0}:{1}/RemotableObject", serverIP, serverPort ) ); ``` Everything works great as far as the remoting goes, but when I access the singleton object in my server code like this: ``` int someValue = RemotableObject.Instance.SomeDynamicValue; ``` It accesses a different instance than the clients do. I have also verified that the private constructor in RemotableObject gets hit twice while debugging. I can get the desired behavior if I get an instance to RemotableObject via remoting in my server code, but is there a way that I can access the same object as my clients from the server without the remoting overhead?
If I understand what you're after, (you want the object to live on the server, but you want all client calls to get the same instance of the object on the server, and you also want calls in the server code to get that same instance? ) then, If your server is "ServerName", and it is listening on port nnnn, with Uri as "MyMsgEndpointUri", you have defined the Uri as: ``` var MesgUri = "tcp://ServerName:nnnn/MyMsgEndpointUri"; ``` in your server, Initialize the endpoint by: ``` RemotingServices.Marshal([singletonInstance], MesgURI); ``` Instead of `RegisterWellKnownServiceType();` also, in the class representing the singleton, remember to override the InitializeLifetimeService property with a null operation... or the singleton object will get Garbage collected at some point... ``` public override object InitializeLifetimeService() { return (null); } ``` From the server, just call your singleton classes' static factory method to get access to that singleton instance... Do not use remoting calls at all...
I've never tried to call Activator.GetObject from the server-side, but that should return the same instance that the clients are using. But, you're still going to get a proxy.
Working with singletons in .Net Remoting
[ "", "c#", ".net", "singleton", "remoting", "" ]
How do I implement error handling elegantly? For example, my data access layer can potentially throw 2 types of errors: 1) not authorized access, in which case the page should hide everything and just show the error message 2) errors that inform the user that something like this already exists in the database (say name not unique - for example), and in this case I wouldn't want to hide everything. EDITED: As a result of some comments here I devised that I should create derived specialized exception types, such as NotAuthorizedException, DuplicateException, etc etc.... it's all fine and dandy, however I can see 2 problems potentially: 1) Every stored proc has a return field p\_error where it contains an error message. Upon getting the data from DB, I need to check this field to see what type of an error has been returned, so I can throw an appropriate exceptions. So, I still need to store my error types/error messages somewhere.....In other words, how do I should the exact message to the user (at certain times I need to) w/o checking the p\_error field first. WHich brings me back to error object. Anyone? 2) I can this potentially turning into a nightmare where the number of exceptions equals the number of error message types. Am I missing something here? Much thanks to everyone!
Create your own exception layer. DALExceptionManager DuplicateException DatabaseException BLLExceptionManager NotAuthorizedException InvalidDateException In your Presentation Layer, Add this references and create a common exception handler. In this way you know how to deal with the exception messages.
You should check out the exception handling block in [Enterprise Library](http://msdn.microsoft.com/en-us/library/dd203099.aspx). Lots of good tips and codeware surrounding wrapping exceptions and passing them between layers.
Error Handling in 3 layered architecture
[ "", "c#", "error-handling", "n-tier-architecture", "" ]
I have an object that I serialize to XML. If one of the properties in the object is null, then native serialization ignores to add this as the attribute. Is this normal behavior, if so, is there a way I can override it? ex: ``` public class Test { [XmlAttribute] public string value {set; get; } [XmlAttribute] public string key {set; get; } } ``` When value is null, i get ``` <Root> <Test key="blah"> </Root> ```
[XmlElement( IsNullable = true )](http://msdn.microsoft.com/en-us/library/system.xml.serialization.xmlelementattribute.isnullable(VS.85).aspx)
In case Sunny's answer just doesn't fits to you, you can customize the serialization process by implementing the IXmlSerializable interface
XML Serialization and null value - C#
[ "", "c#", "asp.net", "" ]
Variable scope in JS is confusing the hell out of me. In the following code, if I use the `setClient` public method to set a `clientID` I can then access the value from inside the track method using the `getClient` method. I cannot, however, access the value of the private member 'version' this way (or any other private member). I had assumed that var `_this = this` would create a closure of some sort allowing access to the scope of the Container function. And now I'm confused. I realise this is probably really simple though, so I thought I'd ask here. Where on earth have a grasped the wrong end of the stick? ``` function Container() { // private members var version = '0.1'; var CID = false; var _this = this; // public members this.getVersion = function() { return _this.version; } this.getClient = function() { return _this.CID; } this.setClient = function(CID) { _this.CID = CID; } // private methods this.getQS = function() { return _this.version; } // public methods this.track = function() { if (_this.CID) { var date = new Date(); data = { cid: _this.getClient(), sw: screen.width ? screen.width : false, sh: screen.height ? screen.height : false, d: date.getTime() } qs = ''; for (p in data) { qs += p+'~'+data[p]+'-'; } var elHd = document.getElementsByTagName("head")[0]; var elScr = document.createElement('script'); elScr.type = 'text/javascript'; elScr.src = 'http://example.org/'+qs+ 'version-'+_this.getVersion(); elHd.appendChild(elScr); } else { alert('no client ID'); } } } ```
Cleand up your Container constructor a bit. The version and CID variables are private and within the Container constructor scope, so you do not need the this scope reference, and it would not work at all. this. reference would be needed for public accessible properties and methods, and extremely useful when you define the prototype outside of the constructor function, as shown in the second code block. ``` function Container() { var version = "0.1", CID = false; this.getVersion = function() { return version }; this.getClient = function() { return CID }; this.setClient = function(value) { CID = value }; this.track = function() { if (CID) { var qs = "", data = { cid: this.getClient(), sw: screen.width ? screen.width: false, sh: screen.height ? screen.height: false, d: (new Date).getTime() }; for (var p in data) qs += p +"~"+ data[p] +"-"; var js = document.createElement("script"); js.type = "text/javascript"; js.src = "http://example.org/"+ qs +"version-"+ this.getVersion(); document.getElementsByTagName("head")[0].appendChild(js); } else { alert("No Client ID"); } }; }; ``` this. reference becomes crucial when you are adding/overriding the prototype after the constructor. ``` function Container2() { } Container2.prototype = { CID: null, version: "0.1", track: function() { alert(this.version); } } ```
I'm not sure I'm understanding where you are confused (or why you are doing things the way you are, so I may be meta-confused). What happens if you just do: ``` this.getVersion = function() { return version; } ```
JS Variable Scope
[ "", "javascript", "scope", "" ]
Considering the following two usage scenarios (exactly as you see them, that is, the end-user will only be interested in using `Vector2_t` and `Vector3_t`): [1]Inheritance: ``` template<typename T, size_t N> struct VectorBase { }; template<typename T> struct Vector2 : VectorBase<T, 2> { }; template<typename T> struct Vector3 : VectorBase<T, 3> { }; typedef Vector2<float> Vector2_t; typedef Vector3<float> Vector3_t; ``` [2]Specialization: ``` template<typename T, size_t N> struct Vector { }; template<typename T> struct Vector<T, 2> { }; template<typename T> struct Vector<T, 3> { }; typedef Vector<float, 2> Vector2_t; typedef Vector<float, 3> Vector3_t; ``` I can't make up my mind as to which is a nicer solution. The obvious advantage to inheritance is code reuse in the derived classes; a possible disadvantage being performance (bigger size, users may pass by value, etc). Specialization seems to avoid all that, but at the expense of me having to repeat myself multiple times. What other advantages/disadvantages did I miss, and in your opinion, which route should I take?
What you ultimately want, i think, is to have the user type ``` Vector<T, N> ``` And depending on `N`, the user will get slight different things. The first will not fulfill that, but the second will, on the price of code duplication. What you can do is to invert the inheritance: ``` template<typename T, size_t N> struct VectorBase { }; template<typename T> struct VectorBase<T, 2> { }; template<typename T> struct VectorBase<T, 3> { }; template<typename T, size_t N> struct Vector : VectorBase<T, N> { }; ``` And implement the few functions that depend only on N being some specific value in the appropriate base-class. You may add a protected destructor into them, to prevent users deleting instances of `Vector` through pointers to `VectorBase` (normally they should not even be able to name `VectorBase`: Put those bases in some implementation namespace, like `detail`). Another idea is to combine this solution with the one mentioned in another answer. Inherit privately (instead of publicly as above) and add wrapper functions into the derived class that call the implementations of the base-class. Yet another idea is to use just one class and then `enable_if` (using `boost::enable_if`) to enable or disable them for particular values of `N`, or use a int-to-type transformer like this which is much simplier ``` struct anyi { }; template<size_t N> struct i2t : anyi { }; template<typename T, size_t N> struct Vector { // forward to the "real" function void some_special_function() { some_special_function(i2t<N>()); } private: // case for N == 2 void some_special_function(i2t<2>) { ... } // case for N == 3 void some_special_function(i2t<3>) { ... } // general case void some_special_function(anyi) { ... } }; ``` That way, it is completely transparent to the user of `Vector`. It also won't add any space overhead for compilers doing the empty base class optimization (quite common).
Use inheritance and private inheritance. And don't use any virtual functions. Since with private inheritance, you don't have is-a, no one will be able to use a baseclas pointer to a derived subclass, and you won't get the slicing problem when passinfg by value. This gives you the best of both worlds (and indeed it's how most libraries implement many of the STL classes). From <http://www.hackcraft.net/cpp/templateInheritance/> (discussing std::vector, not your **V**ector class): > `vector<T*>` is declared to have a > private base of `vector<void*>`. > All functions which place a new element > into the vector, such as `push_back()`, call the > equivalent function on this private base, > so internally our `vector<T*>` is using a > `vector<void*>` for storage. All functions > which return an element from the vector, such as > `front()`, perform a `static_cast` on the > result of calling the equivalent function > on the private base. Since the only way to get a > pointer into the `vector<void*>` (apart from > deliberately dangerous tricks) is through the > interface offered by `vector<T*>` it is safe > to staticly cast the `void*` back to `T*` > (or the `void*&` back to `T*&`, and so on). In general, if the STL does it like this, it seems like a decent model to emulate.
Inheritance vs Specialization
[ "", "c++", "inheritance", "specialization", "" ]
I want to convert date format from 01/09 to January 2009 , 09/03 to September 2003 etc. Is this possible in SQL? Please let me know if there is a API for the same.
if you have a DateTime column in your table, it's possible ``` SELECT DATENAME(MM, YOUR_DATE_COLUMN) + ' ' + CAST(YEAR(YOUR_DATE_COLUMN) AS VARCHAR(4)) AS [Month YYYY] ``` <http://www.sql-server-helper.com/tips/date-formats.aspx>
You should look [here](http://msdn.microsoft.com/en-us/library/aa226054(SQL.80).aspx). It's rather simple.
Date Format conversion in SQL
[ "", "sql", "sql-server", "sql-server-2005", "" ]
I have very large images (jpg) and i want to write a csharp program to loop through the files and reduce the size of each image by 75%. I tried this: ``` Image thumbNail = image.GetThumbnailImage(800, 600, null, new IntPtr()); ``` but the file size is still very large. Is there anyway to create thumbnails and have the filesize be much smaller?
``` private void CompressAndSaveImage(Image img, string fileName, long quality) { EncoderParameters parameters = new EncoderParameters(1); parameters.Param[0] = new EncoderParameter(Encoder.Quality, quality); img.Save(fileName, GetCodecInfo("image/jpeg"), parameters); } private static ImageCodecInfo GetCodecInfo(string mimeType) { foreach (ImageCodecInfo encoder in ImageCodecInfo.GetImageEncoders()) if (encoder.MimeType == mimeType) return encoder; throw new ArgumentOutOfRangeException( string.Format("'{0}' not supported", mimeType)); } ``` Usage: ``` Image myImg = Image.FromFile(@"C:\Test.jpg"); CompressAndSaveImage(myImg, @"C:\Test2.jpg", 10); ``` That will compress Test.jpg with a quality of 10 and save it as Test2.jpg. **EDIT:** Might be better as an extension method: ``` private static void SaveCompressed(this Image img, string fileName, long quality) { EncoderParameters parameters = new EncoderParameters(1); parameters.Param[0] = new EncoderParameter(Encoder.Quality, quality); img.Save(fileName, GetCodecInfo("image/jpeg"), parameters); } ``` Usage: ``` Image myImg = Image.FromFile(@"C:\Test.jpg"); myImg.SaveCompressed(@"C:\Test2.jpg", 10); ```
[ImageMagick](http://www.imagemagick.org/script/index.php) is a command line tool which is hugely powerful for doing image manipulation. I've used it for resizing large images and thumbnail creation in circumstances where the aspect ratio of the source image is unknown or is unreliable. ImageMagick is able to resize images to a specific height or width while maintaining the original aspect ratio of your picture. It can also add space around an image if required. All in all very powerful and a nice abstraction from having to deal with .nets Image APIs. To use the imageMagick command line tool from within C# I recommend using the System.Diagnostics.ProcessStartInfo object like so: ``` ProcessStartInfo psi = new ProcessStartInfo(); psi.FileName = @"C:\Program Files\ImageMagick-6.5.0-Q16\convert.exe"; psi.UseShellExecute = false; psi.RedirectStandardOutput = true; psi.RedirectStandardError = true; psi.Arguments = string.Format("-size x{0} \"{1}\" -thumbnail 200x140 -background transparent -gravity center -extent 200x140 \"{2}\"", heightToResizeTo, originalTempFileLocation, resizedTempFileLocation); Process p = new Process(); p.StartInfo = psi; p.Start(); p.WaitForExit(); ``` Using the scale% paramater you can easily reduce the size of your image by 75%
Create thumbnail and reduce image size
[ "", "c#", "file", "image", "size", "image-scaling", "" ]
I am new to C++ style casts and I am **worried that using C++ style casts will ruin the performance of my application** because I have a [real-time-critical deadline](http://en.wikipedia.org/wiki/Real-time_computing) in my interrupt-service-routine. I heard that some casts will even throw exceptions! I would like to use the C++ style casts because it would make my code more "robust". However, **if there is any performance hit** then I will probably not use C++ style casts and will instead spend more time testing the code that uses C-style casts. --- Has anyone done any rigorous testing/profiling to compare the performance of C++ style casts to C style casts? What were your results? What conclusions did you draw?
If the C++ style cast can be conceptualy replaced by a C-style cast there will be no overhead. If it can't, as in the case of `dynamic_cast`, for which there is no C equivalent, you have to pay the cost one way or another. As an example, the following code: ``` int x; float f = 123.456; x = (int) f; x = static_cast<int>(f); ``` generates identical code for both casts with VC++ - code is: ``` 00401041 fld dword ptr [ebp-8] 00401044 call __ftol (0040110c) 00401049 mov dword ptr [ebp-4],eax ``` The only C++ cast that can throw is `dynamic_cast` when casting to a reference. To avoid this, cast to a pointer, which will return 0 if the cast fails.
The only one with any extra cost at runtime is `dynamic_cast`, which has capabilities that cannot be reproduced directly with a C style cast anyway. So you have no problem. The easiest way to reassure yourself of this is to instruct your compiler to generate assembler output, and examine the code it generates. For example, in any sanely implemented compiler, `reinterpret_cast` will disappear altogether, because it just means "go blindly ahead and pretend the data is of this type".
Performance hit from C++ style casts?
[ "", "c++", "performance", "casting", "" ]
I'm using yum on CentOS 5.1 - I hand-compiled PHP 5.2.8 from source, but have other packages installed using yum. I need to install a PHP extension via pecl, and it requires phpize to be installed as well. However, doing the following yields a dependency error: > sudo yum install php-devel Error: Missing Dependency: php = 5.1.6-20.el5\_2.1 is needed by package php-devel Since I actually have a newer version of PHP already installed, how can I force yum to ignore this? Do I need to hand-compile pecl/phpize from source? I admittedly never had a problem before, it only seems to be because of a combo of compiles and yum installs. Any thoughts? Thanks, Kyle
As a rule of thumb, it's better to have one package management in the system, so you'll be better off packaging everything in RPMS and managing it via yum. It will save you lots of time in the long run. If you absolutely want to have something (fe PHP) compiler from sources by hand, use stow/checkinstall/... or any other solution which would enable you to do rudimentary package management for source-compiled stuff. Regerding your question, you could try to override dependency checking by downloading RPM of the required package an doing "rpm -i --force file.rpm", since yum does not have any option for forced installations
In general: If you build it yourself, it goes into `/usr/local`, and is only accessible to other things in `/usr/local`. If you install from RPM/Yum, it goes into `/usr`, and is accessible to `/usr` and `/usr/local`. So, if you want to install PHP tools using home-compiled PHP, install them into `/usr/local` as well: typically, with GNU-type software, that'd be something like: ``` ./configure --prefix=/usr/local && make && sudo make install ``` or ``` make prefix=/usr/local all && sudo make prefix=/usr/local install ``` …although *most* software should default to `/usr/local` unless you override its prefix setting. If you want to “hand-build” packages that are based upon RPM's, you can use ``` yumdownloader --source WHATEVER-PACKAGE rpm -i WHATEVER-PACKAGE.rpm rpmbuild -bp ~/rpm/SPECS/WHATEVER-PACKAGE.spec ``` (your path equivalent to `~/rpm` may vary; `rpmbuild --showrc` will tell you where) This downloads the `.src.rpm` package, which contains the upstream (original author's) source (usually a tarball) as well as OS-specific patches; installs the sources into `~/rpm` (or your rpmbuild prefix); and then unpacks the sources and applies the patches into `~/rpm/BUILD/WHATEVER-PACKAGE/` From there, you can do the configure/make steps yourself, with the `/usr/local` prefix Of course, just installing from RPM's is far easier :-)
Overriding yum dependency checks when newer versions of the dependent software exist
[ "", "php", "dependencies", "centos", "yum", "" ]
[This question](https://stackoverflow.com/questions/652064/select-random-sampling-from-sqlserver-quickly) asks about getting a random(ish) sample of records on SQL Server and the answer was to use `TABLESAMPLE`. Is there an equivalent in Oracle 10? If there isn't, is there a standard way to get a random sample of results from a query set? For example how can one get 1,000 random rows from a query that will return millions normally?
``` SELECT * FROM ( SELECT * FROM mytable ORDER BY dbms_random.value ) WHERE rownum <= 1000 ```
The [SAMPLE clause](https://docs.oracle.com/cd/B28359_01/server.111/b28286/statements_10002.htm#i2065953) will give you a random sample percentage of all rows in a table. For example, here we obtain 25% of the rows: ``` SELECT * FROM emp SAMPLE(25) ``` The following SQL (using one of the analytical functions) will give you a random sample of a specific number of each occurrence of a particular value (similar to a GROUP BY) in a table. Here we sample 10 of each: ``` SELECT * FROM ( SELECT job, sal, ROW_NUMBER() OVER ( PARTITION BY job ORDER BY job ) SampleCount FROM emp ) WHERE SampleCount <= 10 ```
Select a random sample of results from a query result
[ "", "sql", "oracle", "random", "" ]
Does anyone know a reason why my programs could be causing my speakers to output some soft static? The programs themselves don't have a single element that outputs sound to anything, yet when I run a few of my programs I can hear a static coming from my speakers. It even gets louder when I run certain programs. Moving the speakers around doesn't help, so it must be coming from inside the computer. I'm not sure what other details to put down since this seems very odd. They are OpenGL programs written in C++ with MS Visual C++. Edit: It seems to be that swapping the framebuffers inside an infinite loop is making the noise, as when I stop swapping I get silence...
Since you say you don't touch sound in your programs, I doubt it's your code doing this. Does it occur if you run any other graphics-intensive programs? Also, what happens if you mute various channels in the mixer (sndvol32.exe on 32-bit windows)? Not knowing anything else I'd venture a guess that it could be related to the fan on your graphics card. If your programs cause the fan to turn on and it's either close to your sound card or the fan's power line crosses an audio cable, it could cause some static. Try moving any audio cables as far as possible from the fan and power cables and see what happens. It could also be picking up static from a number of other sources, and I wouldn't say it's necessarily unusual. If non-graphics-intensive programs cause this as well, it could be hard-disk access, or even certain frequencies of CPU/power usage being picked up on an audio line like an antenna. You can also try to reduce the number of loops in your audio wires and see if it helps, but no guarantees.
Computers consume a different amount of power when executing code. This fluctuation of current acts like a RF transmitter and can be picked up by audio equipment and it will be essentially "decoded" much like a AM modulated signal. As the execution usually does not produce a recognizable signal it sounds like white noise. A good example of audio equippment picking up a RF signal is if you hold your (GSM) cell phone close to an audio amplifier when receiving a call. You most likely will hear a characteristic pumping buzz from the cell phone's transmitter. Go here to learn more about [Electromagnetic compatibility](http://en.wikipedia.org/wiki/Electromagnetic_compatibility). There are multiple ways a signal can couple into your audio. As you mentioned a power cord to be the source it was most likely magnetic inductive coupling.
Programs causing static noise in speakers?
[ "", "c++", "opengl", "audio", "" ]
I have inherited a table with a structure something like this: ``` ID Name Timestamp Data ---------------------------- 1 A 40 ... 2 A 30 ... 3 A 20 ... 4 B 40 ... 5 B 20 ... 6 C 30 ... 7 C 20 ... 8 C 10 ... ``` `ID` is an identity field and the primary key and there are non-unique indexes on the `Name` and `Timestamp` fields. What is the most efficient way to get the most recent record for each item name, i.e. in the table above rows **1**,**4** and **6** should be returned as they are the most up-to-date entries for items **A**,**B** and **C** respectively.
SQL Server 2005 (onwards): ``` WITH MostRecentRows AS ( SELECT ID, Name, Data, ROW_NUMBER() OVER (PARTITION BY Name ORDER BY TimeStamp DESC) AS 'RowNumber' FROM MySchema.MyTable ) SELECT * FROM MostRecentRows WHERE RowNumber = 1 ```
Assuming there are no duplicate timestamps per name, something like this should work: ``` SELECT ID, Name, Timestamp, Data FROM test AS o WHERE o.Timestamp = (SELECT MAX(Timestamp) FROM test as i WHERE i.name = o.name) ```
Select Most Recent States From History Table
[ "", "sql", "t-sql", "" ]
Is it possible to delete the *first* record from a table in `SQL Server`, without using any `WHERE` condition and without using a cursor?
``` WITH q AS ( SELECT TOP 1 * FROM mytable /* You may want to add ORDER BY here */ ) DELETE FROM q ``` Note that ``` DELETE TOP (1) FROM mytable ``` will also work, but, as stated in the [**documentation**](http://msdn.microsoft.com/en-us/library/ms189835.aspx): > The rows referenced in the `TOP` expression used with `INSERT`, `UPDATE`, or `DELETE` are not arranged in any order. Therefore, it's better to use `WITH` and an `ORDER BY` clause, which will let you specify more exactly which row you consider to be the first.
depends on your [DBMS](http://en.wikipedia.org/wiki/Dbms) ``` -- MYSql: DELETE FROM table LIMIT 1; -- Postgres: DELETE FROM table LIMIT 1; -- MSSql: DELETE TOP(1) FROM table; -- Oracle: DELETE FROM table WHERE ROWNUM = 1; ```
Delete the 'first' record from a table in SQL Server, without a WHERE condition
[ "", "sql", "sql-server", "" ]
I wanted to make sure about something in Java: If I have a Character or an Integer or a Long and those sort of things, should I use equals or is == sufficient? I know that with strings there are no guarantees that there is only one instance of each unique string, but I'm not sure about other boxed types. My intuition is to use equals, but I want to make sure I'm not wasting performance.
EDIT: The spec makes *some* guarantees for boxing conversions. From [section 5.1.7](http://java.sun.com/docs/books/jls/third_edition/html/conversions.html#5.1.7): > If the value p being boxed is true, > false, a byte, a char in the range > \u0000 to \u007f, or an int or short > number between -128 and 127, then let > r1 and r2 be the results of any two > boxing conversions of p. It is always > the case that r1 == r2. The implementation *can* use a larger pool, mind you. I would *really* avoid writing code which relies on that though. Not because it might fail, but because it's not obvious - few people will know the spec that well. (I previously thought it was implementation-dependent.) You should use `equals` or compare the underlying values, i.e. ``` if (foo.equals(bar)) ``` or ``` if (foo.intValue() == bar.intValue()) ``` Note that even if the autoboxing were guaranteed to use fixed values, other callers can always create separate instances anyway.
If you want to compare any two objects for equality use `.equals()`. Even (and especially) if those objects are the primitive wrapper types `Byte`, `Character`, `Short`, `Integer`, `Long`, `Float`, `Double` and `Boolean`. For objects "`==`" only ever compares the object identity and that's very, very rarely what you want. And you de-facto never what you want with the primitive wrappers. Only use `==` in one of those two scenarios: 1. all values involved in the comparison are primitive types (and preferably not floating point numbers) 2. you really want to know if two references refer to the same object (this includes comparison of `enum`s, because there the value is bound to the object identity)
Comparing Character, Integer and similar types in Java: Use equals or ==?
[ "", "java", "equals", "primitive", "" ]
I have a master page which is nested 2 levels. It has a master page, and that master page has a master page. When I stick controls in a ContentPlaceHolder with the name "bcr" - I have to find the controls like so: ``` Label lblName =(Label)Master.Master.FindControl("bcr").FindControl("bcr").FindControl("Conditional1").FindControl("ctl03").FindControl("lblName"); ``` Am I totally lost? Or is this how it needs to be done? I am about to work with a MultiView, which is inside of a conditional content control. So if I want to change the view I have to get a reference to that control right? Getting that reference is going to be even nastier! Is there a better way? Thanks
Firstly, you should know that MasterPages actually sit inside Pages. So much so that a MasterPage's Load event is actually called after your ASPX's Load event. This means, the Page object is actually the highest control in the control hierarchy. So, knowing this, the best way to find any control in such a nested environment, is to write a recursive function that loops through every control and child controls until it finds the one you're looking for. in this case, your MasterPages are actually child controls of the main Page control. You get to the main Page object from inside any control like this: C#: this.Page; VB.NET Me.Page I find that usually, the Control's class FindControl() method is pretty useless, as the enviroment is always nested. Because if this, I've decided to use .NET's 3.5 new Extension features to extend the Control class. By using the code below (VB.NET), in say, your AppCode folder, all your controls will now peform a recursive find by calling FindByControlID() ``` Public Module ControlExtensions <System.Runtime.CompilerServices.Extension()> _ Public Function FindControlByID(ByRef SourceControl As Control, ByRef ControlID As String) As Control If Not String.IsNullOrEmpty(ControlID) Then Return FindControlHelper(Of Control)(SourceControl.Controls, ControlID) Else Return Nothing End If End Function Private Function FindControlHelper(Of GenericControlType)(ByVal ConCol As ControlCollection, ByRef ControlID As String) As Control Dim RetControl As Control For Each Con As Control In ConCol If ControlID IsNot Nothing Then If Con.ID = ControlID Then Return Con End If Else If TypeOf Con Is GenericControlType Then Return Con End If End If If Con.HasControls Then If ControlID IsNot Nothing Then RetControl = FindControlByID(Con, ControlID) Else RetControl = FindControlByType(Of GenericControlType)(Con) End If If RetControl IsNot Nothing Then Return RetControl End If End If Next Return Nothing End Function End Module ```
Finding controls is a pain, and I've been using this method which I got from the [CodingHorror blog](https://blog.codinghorror.com/recursive-pagefindcontrol/) quite a while ago, with a single modification that returns null if an empty id is passed in. ``` /// <summary> /// Recursive FindControl method, to search a control and all child /// controls for a control with the specified ID. /// </summary> /// <returns>Control if found or null</returns> public static Control FindControlRecursive(Control root, string id) { if (id == string.Empty) return null; if (root.ID == id) return root; foreach (Control c in root.Controls) { Control t = FindControlRecursive(c, id); if (t != null) { return t; } } return null; } ``` In your case, I think you'd need the following: ``` Label lblName = (Label) FindControlRecursive(Page, "lblName"); ``` Using this method is generally much more convenient, as you don't need to know exactly where the control resides to find it (assuming you know the ID, of course), though if you have nested controls with the same name, you'll probably get some strange behavior, so that might be something to watch out for.
Finding controls inside nested master pages
[ "", "c#", "asp.net", ".net-3.5", "master-pages", "" ]
Im working with PHP 4.3.11 and when I execute a [header](http://ar.php.net/header) always responds with an error like this **Warning:** Cannot modify header information - headers already sent by (output started at d:\folder\file.php:1) in **d:\folder\file.php** on line **2** **Warning:** Cannot modify header information - headers already sent by (output started at d:\folder\file.php:1) in **d:\folder\file.php** on line **3** Current PHP version: 4.3.11 the code I used to generate this error was ``` <?php header("Cache-Control: no-cache, must-revalidate"); // HTTP/1.1 header("Expires: Sat, 26 Jul 1997 05:00:00 GMT"); // Date in the past echo 'Current PHP version: ' . phpversion(); // prints e.g. '2.0' or nothing if the extension isn't enabled echo phpversion('tidy'); ?> ``` It has no spaces nor newlines before or after the php tags, and the same code in a 5.x version returns just the php version as expected. Any clue? Thanks in advance **Edit:** Solved!: I've opened the file with western european encoding and deleted the [BOM](http://en.wikipedia.org/wiki/Byte-order_mark) and it worked. Thanks all for your help!
Do you have a [UTF BOM](http://en.wikipedia.org/wiki/Byte-order_mark) at the start of the file?
Make sure that there are no empty lines and invisible characters (such as the [UTF BOM](http://en.wikipedia.org/wiki/Byte-order_mark)) before the PHP block so that `<?php` is really the first in the file.
php header function produces an error when it shouldnt
[ "", "php", "header", "" ]