Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
I'm looking for a .NET Add-in that reads in the contents of the Current Document window, lists the header declaration of all Regions, Subs, Functions, and Module Level Variables, and provides a simple Move Up/Move Down buttons to rearrange their order.
I find that the "File Structure Window" provided by the [Resharper](http://www.jetbrains.com/resharper/) add-in provides most of the features you are looking for. However, it is part of a comprehensive refactoring add-in and this may not suit you.
I haven't yet used it (as I usually just code in the regions myself, or wait until I'm doing other refactoring on an inherited project), but [Regionerate](http://www.rauchy.net/regionerate/) looks good.
Is there a .NET Tool/Add-in available which allows you to easily rearrange the order of Regions, Subs, Functions, and Member Variables in a Class?
[ "", "c#", "asp.net", "vb.net", "visual-studio", "add-in", "" ]
What's the difference between \n and \r (I know it has something to do with OS), and what's the best way to echo a line break that will work cross platform? **EDIT:** In response to Jarod, I'll be using ths to echo a line break in a .txt log file, though I'm sure I'll be using it in the future for things such as echoi...
* `\n` is a Linux/Unix line break. * `\r` is a classic Mac OS (non-OS X) line break. Mac OS X uses the above unix `\n`. * `\r\n` is a Windows line break. I usually just use `\n` on our Linux systems and most Windows apps deal with it ok anyway.
Use the `PHP_EOL` constant, which is automatically set to the correct line break for the operating system that the PHP script is running on. Note that this constant is declared since PHP 5.0.2. ``` <?php echo "Line 1" . PHP_EOL . "Line 2"; ?> ``` For backwards compatibility: ``` if (!defined('PHP_EOL')) { s...
PHP Echo Line Breaks
[ "", "php", "cross-platform", "newline", "eol", "line-breaks", "" ]
Suppose I have this Windows wchar\_t string: ``` L"\x4f60\x597d" ``` and ``` L"\x00e4\x00a0\x597d" ``` and would like to convert it (not necessarily programmatically; it will be a one-time thing) to GCC/Linux wchar\_t format, which is UTF-32 AFAIK. How do I do it? (a general explanation would be nice, but example b...
One of the most used libraries to do character conversion is the ICU library <http://icu-project.org/> It is e.g. used by some boost <http://www.boost.org/> libraries.
Would converting from UTF-16 (the Visual C++ `wchar_t` form) to UTF-8, then possibly from UTF-8 to UCS-4 (the GCC `wchar_t` form), be an acceptable answer? If so, then in Windows you could use the `WideCharToMultiByte` function (with `CP_UTF8` for the `CodePage` parameter), for the first part of the conversion. Then y...
How to convert (not necessarily programmatically) between Windows' wchar_t and GCC/Linux one?
[ "", "c++", "linux", "utf", "wchar-t", "" ]
I would like to construct a query that displays all the results in a table, but is offset by 5 from the start of the table. As far as I can tell, MySQL's `LIMIT` requires a limit as well as an offset. Is there any way to do this?
From the [MySQL Manual on LIMIT](http://dev.mysql.com/doc/refman/5.0/en/select.html#id4651990): > To retrieve all rows from a certain > offset up to the end of the result > set, you can use some large number for > the second parameter. This statement > retrieves all rows from the 96th row > to the last: ``` SELECT * ...
As you mentioned it LIMIT is required, so you need to use the biggest limit possible, which is 18446744073709551615 (maximum of unsigned BIGINT) ``` SELECT * FROM somewhere LIMIT 18446744073709551610 OFFSET 5 ```
MySQL offset infinite rows
[ "", "mysql", "sql", "sql-limit", "" ]
I got an HTML with the `<body onload="window.print()">`. The question I'm trying to ask is: * Is there any way to remove the strings that the web browsers add to the printed page? * Such as: + Web site from where the page was printed + Page count + Title of the web page + Date of printing
Google Docs is now [skirting around](http://docs.google.com/support/bin/answer.py?hl=en&answer=50089) this issue by generating a PDF version of your document. If you are using Chrome, it will automatically open the PDF in a new tab and pop up the print dialog. Other browsers will prompt you to download the resultant f...
These a usually browser specific print settings. In IE & FireFox for example you can go into page setup and change the header and footer details for printing. I don't think this can be controlled by the web page itself.
Remove the default browser header and footer when printing HTML
[ "", "javascript", "html", "printing-web-page", "" ]
I have a Java Applet that uses AWT. In some (rare) circumstances, the platform does not refresh the screen properly. I can move or minimize/maximize the window and see that my applet refreshed properly. I am looking for code that will give me the fullest possible applet screen repaint, simulating the behaviour of a min...
This happens all the time if you are not programming carefully in AWT/Swing. First of all, you should do ALL work on the event thread. This means you can't do any of it in your main statement (or anything it calls directly). I know every Java GUI app ever invented violates this rule, but that's the rule. For the most...
The method to use for this kind of problem is repaint, as you've mentioned. It's possible you are seeing an issue with the JVM you are using. I'd recommend using different versions of the Sun JVM and even the MS VM for IE to see if this is a VM related problem - it may actually be unrelated to your code. I haven't act...
Force a full Java applet refresh (AWT)
[ "", "java", "macos", "applet", "refresh", "awt", "" ]
I'm working on a simple javascript login for a site, and have come up with this: ``` <form id="loginwindow"> <strong>Login to view!</strong> <p><strong>User ID:</strong> <input type="text" name="text2"> </p> <p><strong>Password:</strong> <input type="password" name="text1"><br> <input type="button" value="Check In...
There are several topics being discussed at once here. Let's try to clarify. **1. Your Immediate Concern:** (*Why won't the input button work when ENTER is pressed?*) Use the **submit** button type. ``` <input type="submit".../> ``` ..instead of ``` <input type="button".../> ``` Your problem doesn't really have ...
Put the script directly in your html document. Change the onclick value with the function you want to use. The script in the html will tell the form to submit when the user hits enter or press the submit button. ``` <form id="Form-v2" action="#"> <input type="text" name="search_field" placeholder="Enter a movie" va...
Javascript login form doesn't submit when user hits Enter
[ "", "javascript", "forms", "button", "submit", "html-input", "" ]
I have a table that stores all the volunteers, and each volunteer will be assigned to an appropriate venue to work the event. There is a table that stores all the venues. It stores the volunteer's appropriate venue assignment into the column `venue_id`. ``` table: venues columns: id, venue_name table: volunteers_200...
General SQL LEFT Outer join syntax. SELECT volunteers.id, volunteers.lname, volunteers.fname, volunteers.venue\_id, venues.venue\_name FROM Volunteers\_2009 AS Volunteers LEFT OUTER JOIN Venues ON (Volunteers.venue\_id = Venues.id)
select field1, field2, field3 from venues, volunteers\_2009 where volunteers\_2009.venue\_id = venues.id
Join query and what do I do with it to display data correctly?
[ "", "php", "mysql", "" ]
I have a char in c#: ``` char foo = '2'; ``` Now I want to get the 2 into an int. I find that Convert.ToInt32 returns the actual decimal value of the char and not the number 2. The following will work: ``` int bar = Convert.ToInt32(new string(foo, 1)); ``` int.parse only works on strings as well. Is there no nativ...
Interesting answers but the docs say differently: > Use the `GetNumericValue` methods to > convert a `Char` object that represents > a number to a numeric value type. Use > `Parse` and `TryParse` to convert a > character in a string into a `Char` > object. Use `ToString` to convert a `Char` > object to a `String` obje...
This will convert it to an `int`: ``` char foo = '2'; int bar = foo - '0'; ``` This works because each character is internally represented by a number. The characters `'0'` to `'9'` are represented by consecutive numbers, so finding the difference between the characters `'0'` and `'2'` results in the number 2.
Convert char to int in C#
[ "", "c#", "char", "int", "" ]
I noticed some code of a colleague today that initialized class variables in the initialization. However it was causing a warning, he says because of the order they are in. My question is why is it better to do variable initialization where it currently is and not within the curly brackets? ``` DiagramScene::DiagramSc...
* It is more efficient (in general). All members of a class are initialised in the constructor, whether you explicitly initialise them or not. If you do not specify an initialiser, then the default constructor of the member is run. If you assign a value in the constructor body, then the assignment operator is called ag...
It's better to do the initialization of the members in the initialization list because the members are then only initialized once. This can be a huge difference in performance (and even behavior) if the members are classes themselves. If the members are all non-const, non-reference fundamental data types, then the diff...
C++ class initialisation containing class variable initialization
[ "", "c++", "class", "coding-style", "" ]
Using PHP, what's the fastest way to convert a string like this: `"123"` to an integer? Why is that particular method the fastest? What happens if it gets unexpected input, such as `"hello"` or an array?
I've just set up a quick benchmarking exercise: ``` Function time to run 1 million iterations -------------------------------------------- (int) "123": 0.55029 intval("123"): 1.0115 (183%) (int) "0": 0.42461 intval("0"): 0.95683 (225%) (int) in...
I personally feel casting is the prettiest. ``` $iSomeVar = (int) $sSomeOtherVar; ``` Should a string like 'Hello' be sent, it will be cast to integer 0. For a string such as '22 years old', it will be cast to integer 22. Anything it can't parse to a number becomes 0. If you really do NEED the speed, I guess the oth...
Fastest way to convert string to integer in PHP
[ "", "php", "optimization", "casting", "" ]
I am a complete JSP beginner. I am trying to use a `java.util.List` in a JSP page. What do I need to do to use classes other than ones in `java.lang`?
Use the following import statement to import `java.util.List`: ``` <%@ page import="java.util.List" %> ``` BTW, to import more than one class, use the following format: ``` <%@ page import="package1.myClass1,package2.myClass2,....,packageN.myClassN" %> ```
FYI - if you are importing a List into a JSP, chances are pretty good that you are violating MVC principles. Take a few hours *now* to read up on the [MVC approach](https://en.wikipedia.org/wiki/Model-view-controller) to web app development (including use of taglibs) - do some more googling on the subject, it's fascina...
How do you import classes in JSP?
[ "", "java", "jsp", "" ]
Using Python I want to be able to draw text at different angles using PIL. For example, imagine you were drawing the number around the face of a clock. The number **3** would appear as expected whereas **12** would we drawn rotated counter-clockwise 90 degrees. Therefore, I need to be able to draw many different stri...
Draw text into a temporary blank image, rotate that, then paste that onto the original image. You could wrap up the steps in a function. Good luck figuring out the exact coordinates to use - my cold-fogged brain isn't up to it right now. This demo writes yellow text on a slant over an image: ``` # Demo to add rotated...
It's also usefull to know our text's size in pixels before we create an Image object. I used such code when drawing graphs. Then I got no problems e.g. with alignment of data labels (the image is exactly as big as the text). ``` (...) img_main = Image.new("RGB", (200, 200)) font = ImageFont.load_default() # Text to b...
How do I draw text at an angle using python's PIL?
[ "", "python", "python-imaging-library", "imaging", "" ]
I'm pretty new to the idea of recursion and this is actually my first attempt at writing a recursive method. I tried to implement a recursive function Max that passes an array, along with a variable that holds the array's size in order to print the largest element. It works, but it just doesn't *feel* right! I have ...
Your use of static variables for holding state outside the function will be a source of difficulty. An example of a recursive implementation of a max() function in pseudocode might be: ``` function Max(data, size) { assert(size > 0) if (size == 1) { return data[0] } maxtail = Max(data[1..size]...
Making your function dependent on static variables is not a good idea. Here is possible implementation of recursive Max function: ``` int Max(int[] array, int currentPos, int maxValue) { // Ouch! if (currentPos < 0) { raise some error } // We reached the end of the array, return latest maxValue...
Refactor this recursive method?
[ "", "java", "recursion", "" ]
I'm looking for a way to get the name of the main HTML form so I can submit it from JavaScript. The reason I can just set the name of the form is because the JavaScript is on a User Control that could get added to many different sites with different form names. Thanks.
I'm not totally sure that this will address what you're asking for, so please comment on it: In your script, when the User Control renders, you could have this placed in there. So long as script doesn't have a "runat" attribute, you should be good. ``` <script type="text/javascript"> var formname = '<%=this.Page.For...
I'm not sure , try "YourUserControl.Page.Form" But why do you need the form name, are you going to have more than one form on your .aspx page , if not, you can get the whole post back JS code for the control that will do the post back (submit) using "Page.ClientScript.GetPostBackEventReference()" and use it to set the...
Get the ASP.NET form name
[ "", "asp.net", "javascript", "forms", "" ]
We have a file that has a 64 bit integer as a string in it. How do we scanf() or otherwise parse this numeric string into an unsigned 64 bit integer type in C++ ? We are aware of things like %lld etc., but a lot of ways to do this parse seem to break compiles under different compilers and stdlibs. The code should comp...
GCC has long long, as will compilers for C++0x. MSVC++ doesn't (yet), but does have its \_\_int64 you can use. ``` #if (__cplusplus > 199711L) || defined(__GNUG__) typedef unsigned long long uint_64_t; #elif defined(_MSC_VER) || defined(__BORLANDC__) typedef unsigned __int64 uint_64_t; #else #error "Please de...
Alnitak recommends `strtoull()`, but it seems it's not [available in Win32](http://social.msdn.microsoft.com/forums/en-US/vclanguage/thread/d69a6afe-6558-4913-afb0-616f00805229/) environments. The linked-to forum thread recommends either of `_strtoui64()`, `_wcstoui64()` and `_tcstoui64()` as replacements. Perhaps this...
Read 64 bit integer string from file
[ "", "c++", "parsing", "64-bit", "integer", "" ]
At work we do almost everything in Java and perl, but I wanted to build out a feature using PHP and sessions. Some peeps thought that it was a bad idea to try to do PHP sessions on our system, cause it's distributed to many servers. What would the specific problem be?
The answer to your specific question, what would the problem be, lies in the fact that by default PHP stores its sessions in files on the filesystem. For a single webserver serving requests, this is not a problem because your session data will always be available. But what if you had two load-balanced webservers servin...
You could also use a custom session save handler: <http://www.php.net/manual/en/function.session-set-save-handler.php> I haven't ever tried it, but with it you define your own save/read functions, so you can implement a database or a shared nfs backend without the need to install any extensions. Also Msession, which...
Are PHP sessions hard to scale across a distributed system?
[ "", "php", "session", "distributed-system", "" ]
Please forgive my long question. I have an idea for a design that I could use some comments on. Is it a good idea to do this? And what are the pit falls I should be aware of? Are there other similar implementations that are better? **My situation is as follows:** I am working on a rewrite of a windows forms applicat...
I have a similar situation here, though I use MySQL. Every database has a versions table that contains the version (simply an integer) and a short comment of what has changed in this version. I use a script to update the databases. Every database change can be in one function or sometimes one change is made by multiple...
Have you considered *partitioning* your large tables by 'construction'? This could alleviate some of the growing pains by splitting the storage for the tables across files/physical devices without needing to change your application. Adding spindles (more drives) and performing a few hours of DBA work can often be chea...
Dynamic patching of databases
[ "", "sql", "sql-server", "database", "" ]
All numbers that divide evenly into x. I put in 4 it returns: 4, 2, 1 edit: I know it sounds homeworky. I'm writing a little app to populate some product tables with semi random test data. Two of the properties are ItemMaximum and Item Multiplier. I need to make sure that the multiplier does not create an illogical s...
pseudocode: * Loop from 1 to the square root of the number, call the index "i". * if number mod i is 0, add i and number / i to the list of factors. realocode: ``` public List<int> Factor(int number) { var factors = new List<int>(); int max = (int)Math.Sqrt(number); // Round down for (int factor = 1; ...
The `%` (remainder) operator is the one to use here. If `x % y == 0` then `x` is divisible by `y`. (Assuming `0 < y <= x`) I'd personally implement this as a method returning an `IEnumerable<int>` using an iterator block.
Best way to find all factors of a given number
[ "", "c#", ".net", "math", "" ]
I have a class that contains a dynamically allocated array, say ``` class A { int* myArray; A() { myArray = 0; } A(int size) { myArray = new int[size]; } ~A() { // Note that as per MikeB's helpful style critique, no need to check against 0. delete [] ...
For building containers you obviously want to use one of the standard containers (such as a std::vector). But this is a perfect example of the things you need to consider when your object contains RAW pointers. If your object has a RAW pointer then you need to remember the rule of 3 (now the rule of 5 in C++11). * Co...
I'd recommend using std::vector: something like ``` typedef std::vector<int> A; typedef std::vector<A> AS; ``` There's nothing wrong with the slight overkill of STL, and you'll be able to spend more time implementing the specific features of your app instead of reinventing the bicycle.
Dynamically allocating an array of objects
[ "", "c++", "memory-management", "pointers", "destructor", "copy-constructor", "" ]
I am using a 3rd party API which is defined in 2 DLLs. I have included those DLLs in my project and set references to them. So far so good. However, these DLLs have at least one dependent DLL which cannot be found at runtime. I copied the missing DLL into the project and set the 'Copy to output' flag but without succe...
It sounds like you need to better understand the third-party library and how it uses its own dependencies. If the installation of the API solves the problem, but copying the files manually does not, then you're missing something. There's either a missing file, or some environment variable or registry entry that's requi...
How are you deploying? Just flat files? If so, it should work as long as the file ends up in the project output directory. Does it? If you are using another deployment, you will need to tell that engine to include it. This is different for each of msi/ClickOnce/etc.
C#: How to include dependent DLLs?
[ "", "c#", "visual-studio", "deployment", "dll", "" ]
I've got some experience with [Bash](http://en.wikipedia.org/wiki/Bash_%28Unix_shell%29), which I don't mind, but now that I'm doing a lot of Windows development I'm needing to do basic stuff/write basic scripts using the Windows command-line language. For some reason said language really irritates me, so I was conside...
Python is well suited for these tasks, and I would guess much easier to develop in and debug than Windows batch files. The question is, I think, how easy and painless it is to ensure that all the computers that you have to run these scripts on, have Python installed.
## Summary **Windows**: no need to think, use Python. **Unix**: quick or run-it-once scripts are for Bash, serious and/or long life time scripts are for Python. ## The big talk In a Windows environment, Python is definitely the best choice since [cmd](http://en.wikipedia.org/wiki/Command_Prompt) is crappy and PowerS...
Would Python make a good substitute for the Windows command-line/batch scripts?
[ "", "python", "command-line", "scripting", "" ]
Having a vector containing pointers to objects then using the clear function doesn't call the destructors for the objects in the vector. I made a function to do this manually but I don't know how to make this a generic function for any kind of objects that might be in the vector. ``` void buttonVectorCleanup(vector<Bu...
The best thing to do is use smart pointers, such as from [Boost](http://www.boost.org/doc/libs/1_36_0/libs/smart_ptr/smart_ptr.htm). Then the objects will be deleted automatically. Or you can make a template function ``` template <class T> void vectorCleanup(vector<T *>& dVector){ T* tmpClass; for(vector<T*>:...
You might want to use boost's [pointer containers](http://www.boost.org/doc/libs/1_36_0/libs/ptr_container/doc/ptr_container.html). They are highly efficient and safe.
How do I create a generic std::vector destructor?
[ "", "c++", "stl", "vector", "destructor", "" ]
I need to call a [VBScript](http://en.wikipedia.org/wiki/VBScript) file (.vbs file extension) in my C# Windows application. How can I do this? There is an add-in to access a VBScript file in Visual Studio. But I need to access the script in code behind. How to do this?
The following code will execute a VBScript script with no prompts or errors and no shell logo. ``` System.Diagnostics.Process.Start(@"cscript //B //Nologo c:\scripts\vbscript.vbs"); ``` A more complex technique would be to use: ``` Process scriptProc = new Process(); scriptProc.StartInfo.FileName = @"cscript"; scri...
Another approach is to create a VB.NET Class Library project, copy your VBScript code into a VB.NET Class file, and reference the VB.NET Class Library from your C# program. You will need to fix-up any differences between VBScript and VB.NET (should be few). The advantage here, is that you will run the code in-process...
How to call a VBScript file in a C# application?
[ "", "c#", ".net", "asp.net", ".net-2.0", "vbscript", "" ]
Today somebody told me that interface implementation in C# is just "Can-Do" relationship, not "Is-A" relationship. This conflicts with my long-time believing in LSP(Liskov Substitution Principle). I always think that all inheritance should means "Is-A" relationship. So, If interface implementation is just a "Can-Do" r...
In my experience it doesn't really help that much to think of "is-a" and "can-do" relationships. You rapidly get into problems. It's an impedance mismatch between the real world and OO, basically. However much people actually talk about modeling the real world, you fundamentally need to understand what the relationship...
I tend to think of interfaces as a contract of behaviour. Interfaces such as IComparable and IEnumerable are classic examples. In the example you gave, IHuman and IEngineer are not really behaviours.
C# Interface Implementation relationship is just "Can-Do" Relationship?
[ "", "c#", "inheritance", "interface", "liskov-substitution-principle", "" ]
How can I count operations in C++? I'd like to analyze code in a better way than just timing it since the time is often rounded to 0 millisec.
You can do precise measurements by reading the time-stamp-counter (**tsc**) of the CPU, which is incremented by one at each cpu-clock. Unfortunately the read is done inlining some assembler instructions in the code. Depending on the underlying architecture the cost of the read varies between ~11(AMD) and ~33(Intel) **...
If you are timing code, it's worth running it a lot of times in a loop to avoid the effect of the timer resolution. So you might run the thing you're timing 10,000 times and measure the amount of time it takes to run all the iterations. It will probably only take a few seconds to run and you'll get better timing data.
How can I count operations in C++?
[ "", "c++", "performance", "" ]
Up until now I have been using std::string in my C++ applications for embedded system (routers, switches, telco gear, etc.). For the next project, I am considering to switch from std::string to std::wstring for Unicode support. This would, for example, allow end-users to use Chinese characters in the command line inte...
Note that many communications protocols require 8-bit characters (or 7-bit characters, or other varieties), so you will often need to translate between your internal wchar\_t/wstring data and external encodings. UTF-8 encoding is useful when you need to have an 8-bit representation of Unicode characters. (See [How Do ...
You might get some headache because of the fact that [the C++ standard dictates that wide-streams are required to convert double-byte characters to single-byte when writing to a file, and how this conversion is done is implementation-dependent](http://www.codeproject.com/KB/stl/upgradingstlappstounicode.aspx).
Switching from std::string to std::wstring for embedded applications?
[ "", "c++", "unicode", "stl", "embedded", "" ]
Say I've got a class like this: ``` class Test { int x; SomeClass s; } ``` And I instantiate it like this: ``` Test* t = new Test; ``` Is x on the stack, or the heap? What about s?
Each time you "instantiate" an object/symbol using a new (we are speaking C++ here), a new memory zone will be allocated for this object. If not, it will be put on the "local" memory zone. The problem is that I have no standard definition for "local" memory zone. ## An example This means that, for example: ``` stru...
``` Test a; Test *t = new Test; ``` a, and all its members, are on the stack. The object pointed to by t, and all its members, are on the heap. The pointer t is on the stack.
Are data members allocated in the same memory space as their objects in C++?
[ "", "c++", "memory-management", "" ]
In my website, users have the possibility to store links. During typing the internet address into the designated field I would like to display a suggest/autocomplete box similar to Google Suggest or the Chrome Omnibar. Example: User is typing as URL: ``` http://www.sta ``` Suggestions which would be displayed: ``...
You could try with <http://google.com/complete/search?output=toolbar&q=keyword> and then parse the xml result.
I did this once before in a Django server. There's two parts - client-side and server-side. Client side you will have to send out XmlHttpRequests to the server as the user is typing, and then when the information comes back, display it. This part will require a decent amount of javascript, including some tricky parts ...
How to implement Google Suggest in your own web application (e.g. using Python)
[ "", "python", "autocomplete", "autosuggest", "" ]
For example for the following XML ``` <Order> <Phone>1254</Phone> <City>City1</City> <State>State</State> </Order> ``` I might want to find out whether the XElement contains "City" Node or not.
Just use the other overload for [Elements](http://msdn.microsoft.com/en-us/library/bb348975.aspx). ``` bool hasCity = OrderXml.Elements("City").Any(); ```
It's been a while since I did XLinq, but here goes my WAG: ``` from x in XDocument where x.Elements("City").Count > 0 select x ``` ;
How to determine if XElement.Elements() contains a node with a specific name?
[ "", "c#", "xml", "linq", ".net-3.5", "" ]
The only thing I can get python omnicomplete to work with are system modules. I get nothing for help with modules in my site-packages or modules that I'm currently working on.
I get completion for my own modules in my PYTHONPATH or site-packages. I'm not sure what version of the pythoncomplete.vim script you're using, but you may want to make sure it's the latest. EDIT: Here's some examples of what I'm seeing on my system... This file (mymodule.py), I puth in a directory in PYTHONPATH, and...
Once I generated ctags for one of my site-packages, it started working for that package -- so I'm guessing that the omnicomplete function depends on ctags for non-sys modules. EDIT: Not true at all. Here's the problem -- poor testing on my part -- omnicomplete WAS working for parts of my project, just not most of it....
Is there any way to get python omnicomplete to work with non-system modules in vim?
[ "", "python", "vim", "omnicomplete", "" ]
Today I happens to find that one C# class can inherit one interface both in implicit and explicit way. This surprises me. If C# works in this way, then one instance can behave differently when referenced in different way. ``` interface IFoo { void DoSomething(); } class Foo : IFoo { #region IFoo Members p...
Your example does **not** implement IFoo both implicitly and explicitly. You only implement IFoo.DoSometing() explicitly. You have a new method on your class called DoSomething(). It has nothing to do with IFoo.DoSomething, except that it has the same name and parameters.
Every class that implements an interface has a *mapping* between that class's members and the interface's members. If the class *explicitly* implements an interface member, then the explicit implementation will **always** be mapped to the interface. If there isn't an explicit implementation then an implicit implementat...
Why Can A C# Class Inherit From One Interface Both Implicitly and Explicitly?
[ "", "c#", "inheritance", "implicit", "explicit", "" ]
If you have a class member that is `static` and `public`. Would you write `static public` or `public static`? I know they are the same. But is there some recommendation / best practice for writing this?
see [this question](https://stackoverflow.com/questions/191929/is-there-a-convention-to-the-order-of-modifiers-in-c#191944) If you download the Microsoft [StyleCop](http://code.msdn.microsoft.com/sourceanalysis) Visual Studio addin, it can validate your source code against the rules Microsoft use. It likes the access ...
"public static" is far more common, so you might want to go with that just to increase readability for programmers who never stumbled upon "static public".
Which is recommended: "static public" or "public static"
[ "", "c#", "" ]
I have sets of 5, 6 and 7 digit numbers. I need them to be displayed in the 000/000/000 format. So for example: 12345 would be displayed as 000/012/345 and 9876543 would be displayed as 009/876/543 I know how to do this in a messy way, involving a series of if/else statements, and strlen functions, but there has to...
sprintf and modulo is one option ``` function formatMyNumber($num) { return sprintf('%03d/%03d/%03d', $num / 1000000, ($num / 1000) % 1000, $num % 1000); } ```
``` $padded = str_pad($number, 9, '0', STR_PAD_LEFT); $split = str_split($padded, 3); $formatted = implode('/', $split); ```
Whats the cleanest way to convert a 5-7 digit number into xxx/xxx/xxx format in php?
[ "", "php", "regex", "" ]
I'm consuming a third-party resource (a .dll) in a web service, and my problem is, that invoking this resource (calling a method) is done asynchronous - I need to subscribe to an event, to get the answer for my request. How do I do that in a c# web service? **Update:** With regard to [Sunny's answer](https://stackove...
If the 3rd party component does not support the standard asynchronous programming model (i.e it does not use IAsyncResult), you can still achieve synchronization using AutoResetEvent or ManualResetEvent. To do this, declare a field of type AutoResetEvent in your web service class: ``` AutoResetEvent processingComplete...
Assuming your 3rd party component is using the asynchronous programming model pattern used throughout the .NET Framework you could do something like this ``` HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create("http://www.stackoverflow.com"); IAsyncResult asyncResult = httpWebRequest.BeginGetResp...
Invoking asynchronous call in a C# web service
[ "", "c#", "web-services", "asynchronous", "function-calls", "" ]
I'm having trouble getting the right number of elements in the ArrayList `alt` in the JSP page below. When I view the JSP it shows the size is 1 (`<%=alt.size()%>`) when it should be 3; I think I'm adding that method to the array in the generator class, so I don't understand why it's showing 1. This is my jsp page: `...
To get 3 Alerts you can redesign as follows. Notice that there is only one property of the alert class. You can create a new instance of the Alert for each alert. ``` package com.cg.mock; public class Alert { String alert1; public Alert(String alert1) { super(); this.alert1 = alert1; } public S...
The problem is you have only one Alert instance in your ArrayList, but that single Alert has 3 properties: alert1, alert2, and alert3. Take a look at the line: ``` alt.add(new Alert("alert1","alert2","alert3")); ``` You only have one add line, and it is not in a loop. A possible solution: ``` public class Alert { ...
Not getting the proper size of an ArrayList in JSP
[ "", "java", "jsp", "arraylist", "" ]
I'm writing an intranet application for a client and I want to give them the ability to configure through an admin interface, which users and user groups can access certain areas. What I'd like to know is the best way of storing the reference to the user or group that is assigned to an area of the intranet. Should I b...
I would use domain\group in case the group gets moved or deleted/recreated. Using CN is brittle in the face of changes to the OU structure. SIDs are not human readable and will break if the object is deleted/recreated.
Personally, I believe that the "Domain\Username" format is sufficiently readable. Also, if you were editing the SQL table directly, you could pretty easily insert a record for a user for testing or debugging purposes.
What is the best way to store a reference to an AD group?
[ "", "c#", "asp.net", "active-directory", "" ]
I have quickly read over the [Microsoft Lambda Expression](http://msdn.microsoft.com/en-us/library/bb397687.aspx) documentation. This kind of example has helped me to understand better, though: ``` delegate int del(int i); del myDelegate = x => x * x; int j = myDelegate(5); //j = 25 ``` Still, I don't understand why...
[Lambda expressions](http://weblogs.asp.net/scottgu/archive/2007/04/08/new-orcas-language-feature-lambda-expressions.aspx) are a simpler syntax for anonymous delegates and can be used everywhere an anonymous delegate can be used. However, the opposite is not true; lambda expressions can be converted to expression trees...
Anonymous functions and expressions are useful for one-off methods that don't benefit from the extra work required to create a full method. Consider this example: ``` List<string> people = new List<string> { "name1", "name2", "joe", "another name", "etc" }; string person = people.Find(person => person.Contains("Joe...
C# Lambda expressions: Why should I use them?
[ "", "c#", "c#-3.0", "lambda", "" ]
Are there any libraries out there (preferably a self contained Text Edit Control) for .NET that have Spell Check capabilities. I would like to add the typical red underline to miss-spelled words in the edit area of my application. Edit: To clarify, this is for WinForms
Not a redlining control, but: [Aspell.Net](http://aspell-net.sourceforge.net/) is a Free and Open Source .Net spell checking component. Based on the GNU Aspell project, Aspell.Net is one of the most powerful multi-lingual spelling engines available. The API is written in C# and communicates through a C++ wrapper around...
Aspell.Net looks nice, but does not seem to be maintained anymore. I could not get it to work on my machine. After searching around SourceForge, I found [NHunspell](http://nhunspell.sourceforge.net/), which is a .Net port of the spell checker from OpenOffice.org. It provides methods to spell check, find synonyms, and ...
.NET Spell Check control?
[ "", "c#", "winforms", "spell-checking", "" ]
A lot of my C# code follows this pattern: ``` void foo(string param1, string param2, string param3) { try { // do something... } catch(Exception ex) { LogError(String.Format("Error in foo(param1={0}, param2={1}, param3={2}), exception={3}", param1, param2, param3, ex.Message)); ...
You could use Reflection and the convention that you must pass the parameters to the LogError with the right order: ``` private static void MyMethod(string s, int x, int y) { try { throw new NotImplementedException(); } catch (Exception ex) { LogError(MethodBase.GetCurrentMethod(), ...
You could use aspect oriented programming with PostSharp (have a look at <http://www.postsharp.org>, and the tutorial at <http://www.codeproject.com/KB/cs/ps-custom-attributes-1.aspx>). Basically you could do something like this: ``` public class LogExceptionAttribute : OnExceptionAspect { public override void OnExce...
Generic logging of function parameters in exception handling
[ "", "c#", ".net", "" ]
I want to examine the contents of a `std::vector` in GDB, how do I do it? Let's say it's a `std::vector<int>` for the sake of simplicity.
To view vector std::vector myVector contents, just type in GDB: ``` (gdb) print myVector ``` This will produce an output similar to: ``` $1 = std::vector of length 3, capacity 4 = {10, 20, 30} ``` To achieve above, you need to have gdb 7 (I tested it on gdb 7.01) and some python pretty-printer. Installation process...
With GCC 4.1.2, to print the whole of a std::vector<int> called myVector, do the following: ``` print *(myVector._M_impl._M_start)@myVector.size() ``` To print only the first N elements, do: ``` print *(myVector._M_impl._M_start)@N ``` **Explanation** This is probably heavily dependent on your compiler version, bu...
How do I print the elements of a C++ vector in GDB?
[ "", "c++", "debugging", "stl", "vector", "gdb", "" ]
I'm a complete Ada newbie, though I've used Pascal for 2-3 years during HS. IIRC, it is possible to call Pascal compiled functions from C/C++. Is it possible to call procedures & functions written in Ada from C++?
According to this [old tutorial](http://www.ghs.com/download/whitepapers/ada_c++.pdf), it should be possible. However, as illustrated by [this thread](http://archives.devshed.com/forums/programming-132/problem-passing-in-out-parameter-from-c-to-ada-1023388.html), you must be careful with the c++ extern "C" definitions...
Here's an example using g++/gnatmake 5.3.0: *NOTE: Be careful when passing data between C++ and Ada* **ada\_pkg.ads** ``` package Ada_Pkg is procedure DoSomething (Number : in Integer); pragma Export (C, DoSomething, "doSomething"); end Ada_Pkg; ``` **ada\_pkg.adb** ``` with Ada.Text_Io...
Can you call Ada functions from C++?
[ "", "c++", "c", "ada", "cross-language", "" ]
I have a web service that is protected by requiring the consuming third party application to pass a client certificate. I have installed the certificate on the providing web service in production and on the client as well. This process is currently working fine for other clients with a similar setup. The current versio...
I had this kind of problem a couple of weeks ago. The solution in my case was to use impersonation in order to gain appropriate access to the certificate store. By default, the IIS worker thread was running as a system user, and as such had no access to the appropriate store. Adding the certificate to a specific user s...
There's a distinct reason it did not work on my machine. When running within Visual Studio, it runs with my credentials, which were used to install the certificate. Thus automatically has permission to access the private key store on the machine. *However* when running outside of cassini (in the IDE), the IIS process d...
Passing a client certificate only works on my machine
[ "", "c#", "web-services", "security", "client-certificates", "" ]
I need to setup an application that watches for files being created in a directory, both locally or on a network drive. Would the `FileSystemWatcher` or polling on a timer would be the best option. I have used both methods in the past, but not extensively. What issues (performance, reliability etc.) are there with ei...
I have seen the file system watcher fail in production and test environments. I now consider it a convenience, but I do not consider it reliable. My pattern has been to watch for changes with the files system watcher, but poll occasionally to catch missing file changes. Edit: If you have a UI, you can also give your u...
The biggest problem I have had is missing files when the buffer gets full. Easy as pie to fix--just increase the buffer. Remember that it contains the file names and events, so increase it to the expected amount of files (trial and error). It does use memory that cannot be paged out, so it could force other processes t...
FileSystemWatcher vs polling to watch for file changes
[ "", "c#", "file-io", "filesystemwatcher", "distributed-filesystem", "" ]
I'm sorry for this very newbish question, I'm not much given into web development. I've got this cool JavaScript in a .js file that we want to use on a small web site. (It's a script to run Cooliris on it). How do use the .js file or attach it to my HTML code?
Just include this line anywhere in your HTML page: ``` <script type="text/javascript" src="yourfile.js"></script> ``` Don't forget the closing tag as IE won't recongize it without a separate closing tag.
``` <script type="text/javascript" src="myfile.js"></script> ``` Usually inserted in the <head> tag. After that, it depends wether or not your script need additional initialization or customisation to work.
How to use a .js file?
[ "", "javascript", "" ]
I have a [Bluehost](http://en.wikipedia.org/wiki/Bluehost) account where I can run Python scripts as CGI. I guess it's the simplest CGI, because to run I have to define the following in `.htaccess`: ``` Options +ExecCGI AddType text/html py AddHandler cgi-script .py ``` Now, whenever I look up web programming with Py...
**How WSGI, CGI, and the frameworks are all connected?** Apache listens on port 80. It gets an HTTP request. It parses the request to find a way to respond. Apache has a LOT of choices for responding. One way to respond is to use CGI to run a script. Another way to respond is to simply serve a file. In the case of CG...
I think [Florian's answer](https://stackoverflow.com/questions/219110/how-python-web-frameworks-wsgi-and-cgi-fit-together/219124#219124) answers the part of your question about "what is WSGI", especially if you read [the PEP](http://www.python.org/dev/peps/pep-0333). As for the questions you pose towards the end: WSG...
How Python web frameworks, WSGI and CGI fit together
[ "", "python", "apache", "cgi", "wsgi", "" ]
Having a bit of trouble with the syntax where we want to call a delegate anonymously within a Control.Invoke. We have tried a number of different approaches, all to no avail. For example: ``` myControl.Invoke(delegate() { MyMethod(this, new MyEventArgs(someParameter)); }); ``` where someParameter is local to this m...
Because `Invoke`/`BeginInvoke` accepts `Delegate` (rather than a typed delegate), you need to tell the compiler what type of delegate to create ; `MethodInvoker` (2.0) or `Action` (3.5) are common choices (note they have the same signature); like so: ``` control.Invoke((MethodInvoker) delegate {this.Text = "Hi";}); ``...
Actually you do not need to use delegate keyword. Just pass lambda as parameter: ``` control.Invoke((MethodInvoker)(() => {this.Text = "Hi"; })); ```
Anonymous method in Invoke call
[ "", "c#", ".net", "compiler-errors", "anonymous-methods", "" ]
I have created a class for a dashboard item which will hold information such as placement on the dashboard, description, etc. I am currently using a pair of Collections to hold those dashboard items contained in the "library" and those items showing on the dashboard itself. I have been asked to make this dashboard mult...
``` List< List<Placement>> ListofListOfPlacements = new List< List<Placement>> (); List<Placement> dashboard1 = new List<Placement>(); List<Placement> dashboard2 = new List<Placement>(); List<Placement> dashboard3 = new List<Placement>(); List<Placement> dashboard4 = new List<Placement>(); ListofListOfPlacements.Add(...
Since you are talking about tabs, it sounds to me like you want something closer to a dictionary keyed on the tab name, with a set of items per tab. .NET 3.5 added the `ILookup<,>` interface: ``` ILookup<string, Foo> items = null; //TODO foreach (Foo foo in items["SomeTab"]) { Conso...
Is a Collection of Collections possible and/or the best way? C# .Net 3.5
[ "", "c#", ".net", "collections", "" ]
Is there a way to resize a `std::vector` to lower capacity when I no longer need previously reserved space?
Effective STL, by Scott Meyers, Item 17: Use the `swap` trick to trim excess capacity. ``` vector<Person>(persons).swap(persons); ``` After that, `persons` is "shrunk to fit". This relies on the fact that `vector`'s copy constructor allocates only as much as memory as needed for the elements being copied.
If you're using C++11, you can use `vec.shrink_to_fit()`. In VS2010 at least, that does the swap trick for you.
How to downsize std::vector?
[ "", "c++", "stl", "vector", "" ]
I am trying to setup tracd for the project I am currently working on. After creating a password file with the python script given in the [site](http://trac.edgewall.org/wiki/TracStandalone) I am trying to start the server with authentication on. But it throws up warning saying No users found in the realm. What actually...
Replacing the above said command line with the one bellow helps. tracd --port 8000 --auth=Trac,D:\My\_Test\_Project\Documents\Trac\digest.txt,Trac D:\My\_Test\_Project\Documents\Trac The string after --auth= should be the environment name and not the project name.
Check your password digest file. Looking at mine it appears that the output is stored as a line with three fields in this format: `username:realm:passwordhash`. If your getting that warning then it could be a mismatch between the realm field in the digest file and the realm that you're passing in when launching tracd. ...
Tracd Realm
[ "", "python", "project-management", "wiki", "trac", "" ]
I'm addicted to Vim, it's now my de facto way of editing text files. Being that it's mainly a text editor and not an IDE, has anyone got tricks for me to make it easier when developing Java apps? Some questions I have: * How do I invoke a maven task without leaving vi? * Can I get code completion? * How's the syntax...
Some tips: * Make sure you use vim (vi improved). Linux and some versions of UNIX symlink vi to vim. * You can get code completion with [eclim](http://eclim.sourceforge.net/) * Or you can get vi functionality within Eclipse with [viPlugin](http://viplugin.com/) * Syntax highlighting is great with vim * Vim has good su...
I've been a Vim user for years. I'm starting to find myself starting up Eclipse occasionally (using the vi plugin, which, I have to say, has a variety of issues). The main reason is that Java builds take quite a while...and they are just getting slower and slower with the addition of highly componentized build-framewor...
Tips for using Vim as a Java IDE?
[ "", "java", "vim", "ide", "" ]
I'm developing my first Word 2007 addin, and I've added an OfficeRibbon to my project. In a button-click handler, I'd like a reference to either the current `Word.Document` or `Word.Application`. I'm trying to get a reference via the `OfficeRibbon.Context` property, which the documentation says should refer to the cur...
I also encountered this problem while creating an Excel 2007 AddIn using VS2008 SP1. The workaround I used was to store the Application in an `internal static` property in the main AddIn class and then reference it in the event handler in my ribbon: ``` public partial class ThisAddIn { internal static Application ...
Try referencing the document with: ``` Globals.ThisDocument.[some item] ``` [MSDN Reference](http://msdn.microsoft.com/en-us/library/bhczd18c.aspx)
VSTO: Why is OfficeRibbon.Context null?
[ "", "c#", "ms-word", "ms-office", "vsto", "ribbon", "" ]
This might be a little hard to explain, but I will try. I want to display a list of categories (stored in 1 table), and number of domains associated with each category (stored in another table). The monkey wrench in this case is that each domain has a set of records associated with it (which are stored in a 3rd table...
``` SELECT Categories.Name,count(DISTINCT categories.name) FROM Categories JOIN Domains ON Categories.ID=Domains.CID JOIN Records ON Records.DID=Domains.ID GROUP BY Categories.Name ``` Tested with following setup: ``` CREATE TABLE Categories (Name nvarchar(50), ID int NOT NULL IDENTITY(1,1)) CREATE TABLE Domains (Na...
``` select c.name, count(distinct d.did) from domains d left join categories c on c.cid = d.cid left join records r on r.did = d.did group by c.name ``` tested with 2 categories, 2 domains per categories, random number of records per domain. result set: ``` name count ---- ----- test 2 test2 ...
How would I write this 3 level deep mysql query?
[ "", "sql", "mysql", "" ]
How can I setup a default value to a property defined as follow: ``` public int MyProperty { get; set; } ``` That is using "prop" [tab][tab] in VS2008 (code snippet). Is it possible without falling back in the "old way"?: ``` private int myProperty = 0; // default value public int MyProperty { get { return myPr...
Just set the "default" value within your constructor. ``` public class Person { public Person() { this.FirstName = string.Empty; } public string FirstName { get; set; } } ``` Also, they're called Automatic Properties.
My preference would be to do things "the old way", rather than init in the constructor. If you later add another constructor you'll have to be sure to call the first one from it, or your properties will be uninitialized.
How to set a default value using "short style" properties in VS2008 (Automatic Properties)?
[ "", "c#", ".net", "visual-studio-2008", "properties", "" ]
I'm new to the VxWorks environment, I'm wondering what C and C++ compilers are available for use with VxWorks?
As far as i know Tornado VxWorks IDE using gcc toolchain. Any way i suggest to use the compiler provided by WindRiver (which i believe their version of gcc) to avoid compatibility problems. It's probably worth to menation the VxWorks version you having in mind. I guess gcc version will be depend on VxWorks version a...
There are two: gcc and diab. They will be provided with your WindRiver platform (such as "General Purpose Platform 3.6"). The gcc is modified by WindRiver (and/or CodeSourcery) to work with VxWorks. Now with VxWorks 6.9 there is a third option: Intel C++ compiler (for Intel target architectures only, 32 and 64 bit) --...
What C/C++ compilers are available for VxWorks?
[ "", "c++", "c", "vxworks", "" ]
Does a tool exist for dynamically altering running javascript in a browser? For example, to change the values of javascript variables during runtime.
Firebug , or Venkman Javascript Debugger .
So, Firebug really is one of the best options - or, if you are a developer that owns Visual Studio and want to debug using IE, you can do that. Let's assume you will do this with Firebug using Firefox. First, determine where you want to alter the code and place the following line *just before* the line you want to sta...
Does a tool exist for dynamically altering running javascript in a browser?
[ "", "javascript", "dynamic-data", "" ]
I need to generate an XML file in C#. I want to write the code that generates this in a file that is mostly XML with code inside of it as I can in an ASP.NET MVC page. So I want a code file that looks like: ``` <lots of angle brackets...> <% foreach(data in myData) { %> < <%= data.somefield %> <% } ...
First off, its MUCH easier to generate XML using XElements. There are many examples floating around. Just search for "Linq to XML." Alternatively, if you absolutely need to do templating, I'd suggest using a template engine such as [NVelocity](http://sourceforge.net/projects/nvelocity/) rather than trying to kludge AS...
Further to the above - use the new XML classes delivered with Linq - they make generation of XML in a logical fashion much much easier though you won't get down to something akin to a template in C#. If you really need something template like then - and I know that this won't necessarily go down well - you should look...
How do I create an XML file using templating similar to ASP.NET
[ "", "c#", "asp.net", "xml", "" ]
I have now 1gb ram at work(i hope that will change soon) and jboss takes almost half of it and that is too much, i turned off logging to file, what more can i do to reduce memory usage ?
You can limit the maximum memory used using the -Xmx parameter, as in any java process. Edit the $JBOSS\_HOME/bin/run.conf and set this parameter to the desired maximum memory you want to allocate to JBoss. Also, you can remove from the deploy directory of the server configuration you are using, the services you are n...
Which configuration are you using? JBoss comes with 3 [standard server configurations](http://www.jboss.org/file-access/default/members/jbossas/freezone/docs/Server_Configuration_Guide/beta500/html/ch03s02.html) * The ***minimal*** configuration starts the core server container without any of the enterprise services. ...
jboss with less memory
[ "", "java", "memory", "jakarta-ee", "jboss", "" ]
I have a PHP script that can encode a PNG image to a Base64 string. I'd like to do the same thing using JavaScript. I know how to open files, but I'm not sure how to do the encoding. I'm not used to working with binary data.
You can use [`btoa()`](https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/btoa) and [`atob()`](https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/atob) to convert to and from base64 encoding. There appears to be some confusion in the comments regarding what these functio...
[From here](http://www.webtoolkit.info/javascript-base64.html): ``` /** * * Base64 encode / decode * http://www.webtoolkit.info/ * **/ var Base64 = { // private property _keyStr : "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=", // public method for encoding encode : function (i...
How can you encode a string to Base64 in JavaScript?
[ "", "javascript", "base64", "binaryfiles", "" ]
How do I iterate over the words of a string composed of words separated by whitespace? Note that I'm not interested in C string functions or that kind of character manipulation/access. I prefer elegance over efficiency. My current solution: ``` #include <iostream> #include <sstream> #include <string> using namespace...
For what it's worth, here's another way to extract tokens from an input string, relying only on standard library facilities. It's an example of the power and elegance behind the design of the STL. ``` #include <iostream> #include <string> #include <sstream> #include <algorithm> #include <iterator> int main() { us...
I use this to split string by a delimiter. The first puts the results in a pre-constructed vector, the second returns a new vector. ``` #include <string> #include <sstream> #include <vector> #include <iterator> template <typename Out> void split(const std::string &s, char delim, Out result) { std::istringstream i...
How do I iterate over the words of a string?
[ "", "c++", "string", "split", "" ]
How are assertions done in c++? Example code is appreciated.
Asserts are a way of explicitly checking the assumptions that your code makes, which helps you track down lots of bugs by narrowing down what the possible problems could be. They are typically only evaluated in a special "debug" build of your application, so they won't slow down the final release version. Let's say yo...
Assertion are boolean expressions which should typically always be true. They are used to ensure what you expected is also what happens. ``` void some_function(int age) { assert(age > 0); } ``` You wrote the function to deal with ages, you also 'know' for sure you're always passing sensible arguments, then you ...
What are assertions? and why would you use them?
[ "", "c++", "assert", "" ]
We have a ASP.Net 2.0 web application up and running with the server in the Midwest (Eastern Standard Time). At this moment all of our customers are in the same time zone as the server. We are bringing another server online in Arizona (Mountain Standard Time). We are storing all our times in a SQL 2005 database via C#...
I had the same issue. We sold our application to a user that was in a different time zone than the web server. We did not store any time information in UTC, but it was actually working correctly. Time displayed in the server's time zone was displaying exactly 3 hours behind. All we had to do was add a time zone drop do...
To local time will always on the server side convert to the physical location. You have a few options. 1. Store the offset value from UTC to the Users, keep times in UTC 2. Do the conversion client side via JS (Not elegant, nor appropriate, In my opinion) 3. Look at some [MSDN recommendations](http://msdn.microsoft.co...
Web Application Time Zone Issue
[ "", "c#", "asp.net", "timezone", "" ]
I'm using an HTML sanitizing whitelist code found here: <http://refactormycode.com/codes/333-sanitize-html> I needed to add the "font" tag as an additional tag to match, so I tried adding this condition after the `<img` tag check ``` if (tagname.StartsWith("<font")) { // detailed <font> tag checking // Non-...
Your IsMatch Method is using the option `RegexOptions.IgnorePatternWhitespace`, that allows you to put comments inside the regular expressions, so you have to scape the # chatacter, otherwise it will be interpreted as a comment. ``` if (!IsMatch(tagname,@"<font(\s*size=""\d{1}"")? (\s*color=""((\#[0-9a-f]{6})|(\#[...
I don't see anything obviously wrong with the regex. I would try isolating the problem by removing pieces of the regex until the problem goes away and then focus on the part that causes the issue.
Why is a left parenthesis being escaped in this Regex?
[ "", "c#", ".net", "regex", "" ]
I'm using MSTEST inside Visual Studio 2008. How can I have each unit test method in a certain test class act as if it were the first test to run so that all global state is reset before running each test? I do not want to explicitly clean up the world using TestInitialize, ClassInitialize, AssemblyInitialize, etc. For ...
In the end, I wrote a helper that used [AppDomain.CreateDomain](http://msdn.microsoft.com/en-us/library/system.appdomain.createdomain.aspx) and then used reflection to call the unit test under a different AppDomain. It provides the isolation I needed. [This post](http://social.msdn.microsoft.com/Forums/en-US/vststest/...
Add a helper in your tests that uses reflection to delete the singleton instance (you can add a reset method to the singleton as well, but I would be concerned about its use). Something like: ``` public static class SingletonHelper { public static void CleanDALFactory() { t...
How to force a MSTEST TestMethod to reset all singletons/statics before running?
[ "", "c#", "unit-testing", "visual-studio-2008", "mstest", "appdomain", "" ]
I've been writing a lot recently about Parallel computing and programming and I do notice that there are a lot of patterns that come up when it comes to parallel computing. Noting that Microsoft already has released a library along with the Microsoft Visual C++ 2010 Community Technical Preview (named Parallel Patterns ...
Patterns: * Produce/Consumer + One Thread produces data + One Thread consumes the data * Loop parallelism + If you can show that each loop is independent each iteration can be done in a sperate thread * Re-Draw Thread + Other threads do work and update data structures but one thread re-draws screen. *...
First you have to chose between shared-memory computing, and shared-nothing computing. Shared memory is easier, but doesn't scale that well - you will use shared-nothing if you either a) have a cluster, rather than a multiprocessor system, or b) if you have many CPUs (say, > 60), and a high degree of non-uniform memo...
Parallel Programming and C++
[ "", "c++", "design-patterns", "parallel-processing", "idioms", "" ]
Will their be a new release of the compact framework with VS2010 and .net 4.0 and if so what new features will it include? WPF? linq to SQL? etc
Visual Studio 2010 only supports developing for windows phone 7. This is a silver light based framework, it does not support win forms or native code. VS2010 can not be used to develop for Windows Mobile 6.5 or lower. You can however install VS2008 along side VS2010.
From what I heard from guys in redmond, there will be a mobile silverlight platform for both windows mobile and nokia (symbian, I think). The "silverlight mobile" platform should be built on top of the compact framework, so it will NOT be a port of the desktop version. There seems to be an information embargo on Windo...
.net Compact Framework 4.0
[ "", "c#", ".net", "compact-framework", "" ]
I was loading a Bitmap Image from a File. When I tried to save the Image to another file I got the following error "A generic error occurred in GDI+". I believe this is because the file is locked by the image object. Ok so tried calling the Image.Clone function. This still locks the file. hmm. Next I try loading a Bi...
I have since found an alternative method to clone the image without locking the file. [Bob Powell has it all plus more GDI resources](https://web.archive.org/web/20120419185819/http://www.bobpowell.net/imagefileconvert.htm). ``` //open the file Image i = Image.FromFile(path); //create temporary ...
Well if you're looking for other ways to do what you're asking, I reckon it should work to create a MemoryStream, and read out the FileStream to it, and load the Image from that stream... ``` var stream = new FileStream("original-image", FileMode.Open); var bufr = new byte[stream.Length]; stream.Read(bufr, 0, (int)str...
Saving a modified image to the original file using GDI+
[ "", "c#", "gdi+", "image-manipulation", "" ]
It appears that Directory.GetFiles() in C# modifies the Last access date of a file. I've googled for hours and can't seem to find a work around for this issue. Is there anyway to keep all the MAC (Modified, Accessed, Created) attributes of a file? I'm using Directory.GetDirectories(), Directory.GetFiles(), and FileInfo...
I know this is far from ideal, but u can use fsutil (provided with Windows) to disable last access time writing: ``` fsutil behavior set disablelastaccess 1 ``` Presumably you'd set it back to 0 once done. You can invoke this using Process.Start from C#, but there must be a better programmatic way (calling into Windo...
Access times are different from last write times. If you use fi.LastWriteTime I think you will find that the times are the same displayed in explorer or cmd window. Of course the last access and last write could be the same, but they are not necessarily the same.
Directory.GetFiles keeping the last access time
[ "", "c#", "lastaccesstime", "" ]
Suppose we have a vector/array in C++ and we wish to count which of these N elements has maximum repetitive occurrences and output the highest count. Which algorithm is best suited for this job. example: ``` int a = { 2, 456, 34, 3456, 2, 435, 2, 456, 2} ``` the output is 4 because 2 occurs 4 times. That is the maxi...
Sort the array and then do a quick pass to count each number. The algorithm has O(N\*logN) complexity. Alternatively, create a hash table, using the number as the key. Store in the hashtable a counter for each element you've keyed. You'll be able to count all elements in one pass; however, the complexity of the algori...
**Optimized for space:** Quicksort (for example) then iterate over the items, keeping track of largest count only. At best O(N log N). **Optimized for speed:** Iterate over all elements, keeping track of the separate counts. This algorithm will always be O(n).
Finding Frequency of numbers in a given group of numbers
[ "", "c++", "c", "algorithm", "puzzle", "frequency", "" ]
The following have been proposed for an upcoming C++ project. * C++ Coding Standards, by Sutter and Alexandrescu * JSF Air Vehicle C++ coding standards * The Elements of C++ Style * Effective C++ 3rd Edition, by Scott Meyers Are there other choices? Or is the list above what be should used on a C++ project? Some rel...
I really think it does not matter which one you adopt, as long as everyone goes along with it. Sometimes that can be hard as it seems that some styles don't agree with peoples tases. I.e. it comes down to arguing about whether prefixing all member variable with `m_` is *pretty* or not. I have been using and modifying ...
[C++ Coding Standards: 101 Rules, Guidelines, and Best Practices](https://rads.stackoverflow.com/amzn/click/com/0321113586) (C++ In-Depth Series) by Herb Sutter and, Andrei Alexandrescu.
Existing Standard Style and Coding standard documents
[ "", "c++", "coding-style", "documentation", "standards", "" ]
As just stated in a recent [question](https://stackoverflow.com/questions/135759/why-cant-i-inherit-iodirectory) and [answer](https://stackoverflow.com/questions/135759/why-cant-i-inherit-iodirectory#135772), you can't inherit from a static class. How does one enforce the rules that go along with static classes inside ...
Module == static class If you just want a class that you can't inherit, use a `NotInheritable` class; but it won't be static/Shared. You could mark all the methods, properties, and members as `Shared`, but that's not strictly the same thing as a static class in C# since it's not enforced by the compiler. If you reall...
Almost there. You've got to prevent instantiation, too. ``` NotInheritable Class MyStaticClass ''' <summary> ''' Prevent instantiation. ''' </summary> Private Sub New() End Sub Public Shared Function MyMethod() As String End Function End Class ``` * Shared is like method of static cla...
Marking A Class Static in VB.NET
[ "", "c#", "vb.net", "" ]
During execution, how can a java program tell how much memory it is using? I don't care how efficient it is!
VonC's answer is an interactive solution - if you want to know programatically, you can use [Runtime.totalMemory()](http://java.sun.com/javase/6/docs/api/java/lang/Runtime.html#totalMemory()) to find out the total amount used by the JVM, and [Runtime.freeMemory()](http://java.sun.com/javase/6/docs/api/java/lang/Runtime...
If you are have a java1.6 somewhere and your program is running in java 1.4.2, 1.5 or 1.6, you can launch a [visualVM session](https://visualvm.dev.java.net/), connect to your application, and follow the memory (and much more) ![image of monitoring application with Visual VM](https://visualvm.dev.java.net/images/docs/...
During execution, how can a java program tell how much memory it is using?
[ "", "java", "memory", "runtime", "" ]
What is the best jQuery status message plugin? I like [jGrowl](http://plugins.jquery.com/project/jgrowl) and [Purr](http://plugins.jquery.com/project/purr), but jGrowl doesn't have the feature to remain sticky (not close automatially) and Purr doesn't seem to work right in IE 6. I would like to show messages like... ...
jGrowl does look to have sticky - see sample 2 in the demo page: <https://github.com/stanlemon/jGrowl> ...ah - or did you mean after the page has reloaded? I would then handle this on the server side - i.e. include a sitedown.js that triggers the growl notice each time any page is visited.
A few options... * [Humanized Messages](http://code.google.com/p/humanmsg/) ([demo](http://binarybonsai.com/misc/humanmsg/), 3 KB) looks very cool, and has a nice history rollout * [Pines Notify](http://sciactive.github.io/pnotify/) (13 KB) is extremely customizable and supports jQuery UI themes * [jGrowl](https://git...
Best jQuery Status Message Plugin?
[ "", "javascript", "jquery", "plugins", "jquery-plugins", "user-interface", "" ]
On large tables in MSSQL; selecting specific columns results in greater speed of the query. Does the same apply to Linq to SQL? Would this: ``` var person = from p in [DataContextObject].Persons where p.PersonsID == 1 select new { p.PersonsID, p.PersonsAdress, p.PersonsZipcode }; ``` be fas...
I highly recommend [LinqPad](http://linqpad.net/). It is free and lets you run LINQ queries dynamically. When you can also look at the SQL that is generated. What you will see is that the LINQ query will translate the first query into selecting only those columns. So it is faster.
If you are limiting the size of the result set by only selecting a few specific columns, then YES it will have an affect. **EDIT** ading clarification from comment How is this better, it will reduce the size of the resultant data returned from SQL AND it will reduce the size of the objects used to store the results i...
Linq to SQL: select optimization
[ "", "sql", "performance", "linq-to-sql", "" ]
I recently introduced HTML into some RSS feeds that I publish (which up to now only had plain text, no markup), and I was wondering which method is better: use character encoding (such as htmlspecialchars) or just encapsulate everything in CDATA? It seems to me that CDATA might be easier, but I'm unclear as to whether...
CDATA is for any data that should not be parsed by the XML parser. Any tags not in a CDATA block **will** be parsed by the XML parser and may take on a different meaning. CDATA can also incur an overhead for the parsers if there is no need for it. Try to avoid CDATA blocks any time you know HTML (or otherwise) won't b...
Personally CDATA is easier, as it allows the display of the actual HTML by the subscriber without their reader needing to do anything funny. If you use HTML Encoding, the subscribers reader, or website iteself, must decode the source to display the HTML
Which is better for encoding HTML for RSS?
[ "", "php", "rss", "cdata", "" ]
Is there any method? My computer is AMD64. ``` ::std::string str; BOOL loadU(const wchar_t* lpszPathName, int flag = 0); ``` When I used: ``` loadU(&str); ``` the VS2005 compiler says: ``` Error 7 error C2664:: cannot convert parameter 1 from 'std::string *__w64 ' to 'const wchar_t *' ``` How can I do it?
If you have a std::wstring object, you can call `c_str()` on it to get a `wchar_t*`: ``` std::wstring name( L"Steve Nash" ); const wchar_t* szName = name.c_str(); ``` Since you are operating on a narrow string, however, you would first need to widen it. There are various options here; one is to use Windows' built-in ...
First convert it to std::wstring: ``` std::wstring widestr = std::wstring(str.begin(), str.end()); ``` Then get the C string: ``` const wchar_t* widecstr = widestr.c_str(); ``` This only works for ASCII strings, but it will not work if the underlying string is UTF-8 encoded. Using a conversion routine like MultiByt...
I want to convert std::string into a const wchar_t *
[ "", "c++", "stl", "wchar-t", "stdstring", "" ]
I am all about using ASP.NET MVC, but one of the areas that I hope gets improved on is Client-Side Validation. I know the most recent version (Preview 5) has a lot of new features for Validation, but they all seem to be after the page has been posted. I have seen an interesting article by [Steve Sanderson](http://blo...
*"Obviously you'll still need to validate your input on the server side for the small percentage of users who disable javascript."* Just an update to this comment. Server-side validation has nothing to do with users that run with JavaScript disabled. Instead, it is needed for security reasons, and to do complex valida...
I agree with other posters, client side validation is strictly for improving user experience. Check out the [JQuery Validation](http://bassistance.de/jquery-plugins/jquery-plugin-validation/) plugin. It's super easy to get started with basic validation -- literally one line of JS plus adding class names to the input c...
ASP.NET MVC Client Side Validation
[ "", "javascript", "asp.net-mvc", "validation", "client-side", "" ]
Ok, this probably has a really simple answer, but I've never tried to do it before: How do you launch a web page from within an app? You know, "click here to go to our FAQ", and when they do it launches their default web browser and goes to your page. I'm working in C/C++ in Windows, but if there's a broader, more port...
``` #include <windows.h> void main() { ShellExecute(NULL, "open", "http://yourwebpage.com", NULL, NULL, SW_SHOWNORMAL); } ```
I believe you want to use the ShellExecute() function which should respect the users choice of default browser.
Launch web page from my application
[ "", "c++", "c", "windows", "browser", "" ]
I've worked on several PHP projects and always I have problems with organizing my work. Where do you develop your application - on localhost, remote server or maybe production one(!) ? When I work on my localhost after making some major path I send new files by ftp - but sometimes it happens to forget about one file an...
This is how we manage our commercial site: 1. Develop in a local sand box 2. Check-in to SVN 3. Automated build/test from SVN onto internal dev server 4. Scripted deploy using rsync to staging server for QA/UAT 5. Scripted deploy onto production servers. Staging and production servers are both hosted by the ...
[Google App Engine](http://code.google.com/appengine/) has an apposite tool that automatically uploads to the production environment files that are modified; don't know if there's something similar for PHP. So, doing a dev2prod script (a script that does this automatically) should be a good solution. To do local sourc...
How do you manage PHP Project Development Lifecycle?
[ "", "php", "lifecycle", "" ]
One of classes in my program uses some third-party library. Library object is a private member of my class: ``` // My.h #include <3pheader.h> class My { ... private: 3pObject m_object; } ``` The problem with this - any other unit in my program that uses My class should be configured t...
Use the "pimpl" idiom: ``` // header class My { class impl; std::auto_ptr<impl> _impl; }; // cpp #include <3pheader.h> class My::impl { 3pObject _object; }; ```
The Private Implementation (PIMPL) pattern: <http://www.codeproject.com/KB/tips/PIMPL.aspx> Basically, you define that your class holds a pointer to a struct that you forward declare. Then you define the struct inside the cpp file and use the constructor and destructor in your class to create/delete the PIMPL. :)
C++ headers - separation between interface and implementation details
[ "", "c++", "coding-style", "" ]
I'm new to mock objects, but I understand that I need to have my classes implement interfaces in order to mock them. The problem I'm having is that in my data access layer, I want to have static methods, but I can't put a static method in an interface. What's the best way around this? Should I just use instance metho...
I would use a method object pattern. Have a static instance of this, and call it in the static method. It should be possible to subclass for testing, depending on your mocking framework. i.e. in your class with the static method have: ``` private static final MethodObject methodObject = new MethodObject(); public st...
Yes, you use instance methods. Static methods basically say, "There is one way to accomplish this functionality - it's not polymorphic." Mocking relies on polymorphism. Now, if your static methods logically don't care about what implementation you're using, they might be able to take the interfaces as parameters, or p...
How to mock with static methods?
[ "", "c#", ".net", "mocking", "interface", "static-methods", "" ]
I'm currently writing an edit-in-place script for MooTools and I'm a little stumped as to how I can make it degrade gracefully without JavaScript while still having some functionality. I would like to use progressive enhancement in some way. I'm not looking for code, but more a concept as to how one would approach the ...
It sounds like you might be approaching this from the wrong direction. Rather than creating the edit-in-place and getting it degrade nicely (the Graceful Degradation angle), you should really be creating a non-Javascript version for editing and then adding the edit-in-place using Javascript after page load, reffered to...
You can't do edit-in-place at all without JavaScript, so graceful degradation for it consists of making sure that the user can still edit the item in question when JavaScript isn't available. As such, I'd just have a link to edit the entire item in question and then create the edit-in-place controls in JavaScript on p...
Any ideas on how to make edit-in-place degradable?
[ "", "javascript", "mootools", "graceful-degradation", "progressive-enhancement", "edit-in-place", "" ]
Given the following java enum: ``` public enum AgeRange { A18TO23 { public String toString() { return "18 - 23"; } }, A24TO29 { public String toString() { return "24 - 29"; } }, A30TO35 { public String toString() { ...
The best and simplest way to do it is like this: ``` public enum AgeRange { A18TO23 ("18-23"), A24TO29 ("24-29"), A30TO35("30-35"); private String value; AgeRange(String value){ this.value = value; } public String toString(){ return value; } public static AgeRang...
You could always create a map from string to value - do so statically so you only need to map it once, assuming that the returned string remains the same over time. There's nothing built-in as far as I'm aware.
How to convert string result of enum with overridden toString() back to enum?
[ "", "java", "enums", "enumeration", "converters", "" ]
I have a form a user can enter their name, then it will add it to $message to be sent in an email. Is it better to use `$_POST` or `$_REQUEST`? Here is a snippet of using `$_REQUEST` ``` $message.= "Name: ".$_REQUEST["fname"]." ".$_REQUEST["mname"]." ".$_REQUEST["lname"]."\n"; ```
The answer is: It depends on how you want it to be used. If you're using `$_POST`, that means it can only come in via POST. If you're using `$_REQUEST`, that means you accept POST, GET (and COOKIE, but it's mainly the first two we're interested in). For something like this, `$_POST` would probably be neater, but if y...
My approach used to be to use **$\_REQUEST** for everything which I think is a big mistake. Lately, I've been trying to be more diligent about using GET only for read-requests & POST only for write-requests. To that end, I think using **$\_GET** for GET requests & **$\_POST** for POST requests makes my intent much mor...
When posting info from a form, is it better to use $_REQUEST or $_POST?
[ "", "php", "" ]
In DB2, you can name a column ORDER and write SQL like ``` SELECT ORDER FROM tblWHATEVER ORDER BY ORDER ``` without even needing to put any special characters around the column name. This is causing me pain that I won't get into, but my question is: why do databases allow the use of SQL keywords for object names? Sur...
I largely agree with the sentiment that keywords shouldn't be allowed as identifiers. Most modern computing languages have 20 or maybe 30 keywords, in which case imposing a moratorium on their use as identifiers is entirely reasonable. Unfortunately, SQL comes from the old COBOL school of languages ("computing language...
Many SQL parsers (expecially DB2/z, which I use) are smarter than some of the regular parsers which sometimes separate lexical and semantic analysis totally (this separation is mostly a good thing). The SQL parsers can figure out based on context whether a keyword is valid or should be treated as an identifier. Hence...
Why can you have a column named ORDER in DB2?
[ "", "sql", "database", "db2", "" ]
How do I query an Oracle database to display the names of all tables in it?
``` SELECT owner, table_name FROM dba_tables ``` This is assuming that you have access to the `DBA_TABLES` data dictionary view. If you do not have those privileges but need them, you can request that the DBA explicitly grants you privileges on that table, or, that the DBA grants you the `SELECT ANY DICTIONARY` priv...
Querying `user_tables` and `dba_tables` didn't work. This one did: ``` select table_name from all_tables ```
Get list of all tables in Oracle?
[ "", "sql", "oracle", "" ]
In Visual Studio 2008 in a C# WinForms project, there is a button on a form. In the properties view, the property "Font" is set to "Arial Unicode MS". What do I need to put into the property "Text", so I get the unicode character \u0D15 displayed on the button? When I put \u0D15 into the "Text" property, the button d...
You don't have to escape your unicode characters in strings as C# is inherently unicode. Just put your unicode characters as they are into the string. For example: ``` button1.Text = "日本"; ```
One possible way is to run "charmap" and copypaste from there or copypaste it from elsewhere.
How to put unicode characters on a System.Windows.Forms.Button in C#?
[ "", "c#", "visual-studio", "unicode", "character", "" ]
I am trying to adapt an existing code to a 64 bit machine. The main problem is that in one function, the previous coder uses a void\* argument that is converted into suitable type in the function itself. A short example: ``` void function(MESSAGE_ID id, void* param) { if(id == FOO) { int real_param = (int)...
Use `intptr_t` and `uintptr_t`. To ensure it is defined in a portable way, you can use code like this: ``` #if defined(__BORLANDC__) typedef unsigned char uint8_t; typedef __int64 int64_t; typedef unsigned long uintptr_t; #elif defined(_MSC_VER) typedef unsigned char uint8_t; typedef __int64 int64...
I'd say this is the modern C++ way: ``` #include <cstdint> void *p; auto i = reinterpret_cast<std::uintptr_t>(p); ``` **EDIT**: ## The correct type to the the Integer So the right way to store a pointer as an integer is to use the `uintptr_t` or `intptr_t` types. (See also in cppreference [integer types for C99](ht...
Converting a pointer into an integer
[ "", "c++", "gcc", "casting", "64-bit", "32-bit", "" ]
I am having dependency troubles. I have two classes: `Graphic` and `Image`. Each one has its own .cpp and .h files. I am declaring them as the following: `Graphic.h`: ``` #include "Image.h" class Image; class Graphic { ... }; ``` `Image.h`: ``` #include "Graphic.h" class Graphic; ...
This worked for me: Image.h: ``` #ifndef IMAGE_H #define IMAGE_H #include "Graphic.h" class Image : public Graphic { }; #endif ``` Graphic.h: ``` #ifndef GRAPHIC_H #define GRAPHIC_H #include "Image.h" class Graphic { }; #endif ``` The following code compiles with no error: ``` #include "Graphic.h" int main...
You don't need to include Image.h or forward declare Image in Graphic.h - that's a circular dependency. If Graphic.h depends on anything in Image.h you need to split that out into a third header. (If Graphic has an Image member, that just isn't going to work.)
How do you inherit from a class in a different header file?
[ "", "c++", "inheritance", "organization", "" ]
Do you have any sugestions of tools to ease the task of understanding C/C++ code? We just inherited a large piece of software written by others and we need to quickly get up to speed on it. Any advice on tools that might simplify this task?
[SourceInsight](http://sourceinsight.com) and [Understand for C++](http://www.scitools.com) are the best tools you can get for c/c++ code analysis including flow charts.
Profiling software gives you an idea of which functions have been called. If you can use Linux, try [KCachegrind](https://kcachegrind.github.io/html/Home.html)
Tool to visualise code flow (C/C++)
[ "", "c++", "c", "code-analysis", "" ]
The interop library is slow and needs MS Office installed. Many times you don't want to install MS Office on servers. I'd like to use [Apache POI](http://en.wikipedia.org/wiki/Apache_POI), but I'm on .NET. I need only to extract the text portion of the files, not creating nor "storing information" in Office files. I...
For all MS Office versions: * You could use the third-party components like [TX Text Controls](http://www.textcontrol.com/) for Word and [TMS Flexcel Studio](http://www.tmssoftware.com/site/flexcelnet.asp) for Excel For the new Office (2007): * You could do some basic stuff using .net functionality from `system.io.p...
Check out the [Aspose components](http://www.aspose.com/categories/default.aspx). They are designed to mimic the Interop functionality without requiring a full Office install on a server.
How can I read MS Office files in a server without installing MS Office and without using the Interop Library?
[ "", "java", ".net", "apache", "ms-office", "office-interop", "" ]
I am new to PHP and trying to get the following code to work: ``` <?php include 'config.php'; include 'opendb.php'; $query = "SELECT name, subject, message FROM contact"; $result = mysql_query($query); while($row = mysql_fetch_array($result, MYSQL_ASSOC)) { echo "Name :{$row['name']} <br>" . "Subject : ...
**Edit** You say that you're still getting an error. Did you remember to add a **.** when you removed that extra semi-colon? --- You have a semi-colon in the middle of your string, two lines after the echo. ![](https://farm4.static.flickr.com/3049/2989189590_754c627f5d.jpg?v=0) Also, the end of the string is missi...
For the second part of your question, you could do this if field names are all logical: ``` while($row = mysql_fetch_array($result, MYSQL_ASSOC)) { foreach($row as $key => $value) { echo "$key: $value\n"; } } ```
Troubleshooting "unexpected $end" error
[ "", "php", "" ]
Im getting frustrated because of OpenDNS and other services (ie: roadrunner) that now always returns a ping even if you type any invalid url ie: lkjsdaflkjdsjf.com --- I had created software for my own use that would ping a url to verify if the site was up or not. This no longer works. Does anyone have any ideas about ...
You could create a simple web page with an address bar for the website and some javascript that uses AJAX to hit a site. If you get any HTTP response other than 200 on the async callback, the site isn't working. ``` <html> <head> <script language="javascript" type="text/javascript"> <!-- var ajax =...
[Wget](http://www.gnu.org/software/wget/) is a nice alternative. It will check not only whether the machine is active, but also whether the HTTP server is accepting connections.
Ping always succeeds, cant easily check uptime using ping on a url
[ "", "c#", ".net", "ping", "system.net", "" ]
Is there any built-in functionality for classical set operations on the java.util.Collection class? My specific implementation would be for ArrayList, but this sounds like something that should apply for all subclasses of Collection. I'm looking for something like: ``` ArrayList<Integer> setA ... ArrayList<Integer> se...
Intersection is done with `Collection.retainAll`; subtraction with `Collection.removeAll`; union with `Collection.addAll`. In each case, as `Set` will act like a set and a `List` will act like a list. As mutable objects, they operate in place. You'll need to explicitly copy if you want to retain the original mutable o...
I would recommend [Google Guava](https://code.google.com/p/guava-libraries/). The [Sets](https://google.github.io/guava/releases/snapshot-jre/api/docs/com/google/common/collect/Sets.html) class seems to have exactly what you are looking for. It has a [intersection](https://google.github.io/guava/releases/snapshot-jre/a...
Classical set operations for java.util.Collection
[ "", "java", "collections", "set", "" ]
I am writing a C library that reads a file into memory. It skips the first 54 bytes of the file (header) and then reads the remainder as data. I use fseek to determine the length of the file, and then use fread to read in the file. The loop runs once and then ends because the EOF is reached (no errors). At the end, by...
perhaps it's a binary mode issue. Try opening the file with `"r+b"` as the mode. **EDIT**: as noted in a comment `"rb"` is likely a better match to your original intent since `"r+b"` will open it for read/write and `"rb"` is read-only.
Also worth noting that simply including binmode.obj into your link command will do this for you for all file opens.
Why is fread reaching the EOF early?
[ "", "c++", "c", "file-io", "stdio", "feof", "" ]
I am working on an iGoogle-like application. Content from other applications (on other domains) is shown using iframes. How do I resize the iframes to fit the height of the iframes' content? I've tried to decipher the javascript Google uses but it's obfuscated, and searching the web has been fruitless so far. **Upda...
We had this type of problem, but slightly in reverse to your situation - we were providing the iframed content to sites on other domains, so the [same origin policy](http://en.wikipedia.org/wiki/Same_origin_policy) was also an issue. After many hours spent trawling google, we eventually found a (somewhat..) workable so...
If you do not need to handle iframe content from a different domain, try this code, it will solve the problem completely and it's simple: ``` <script language="JavaScript"> <!-- function autoResize(id){ var newheight; var newwidth; if(document.getElementById){ newheight=document.getElementById(id)...
Resizing an iframe based on content
[ "", "javascript", "iframe", "widget", "" ]
Let's say I have a class ``` public class ItemController:Controller { public ActionResult Login(int id) { return View("Hi", id); } } ``` On a page that is not located at the Item folder, where `ItemController` resides, I want to create a link to the `Login` method. So which `Html.ActionLink` metho...
I think what you want is this: ## ASP.NET MVC1 ``` Html.ActionLink(article.Title, "Login", // <-- Controller Name. "Item", // <-- ActionMethod new { id = article.ArticleID }, // <-- Route arguments. null // <-- htmlArguments .. which are none. You n...
I wanted to add to [Joseph Kingry's answer](https://stackoverflow.com/a/201341/3834). He provided the solution but at first I couldn't get it to work either and got a result just like Adhip Gupta. And then I realized that the route has to exist in the first place and the parameters need to match the route exactly. So I...
HTML.ActionLink method
[ "", "c#", ".net", "asp.net-mvc", "html-helper", "actionlink", "" ]
Is there a way to find all the class dependencies of a java main class? I have been manually sifting through the imports of the main class and it's imports but then realized that, because one does not have to import classes that are in the same package, I was putting together an incomplete list. I need something that...
It can be eaily done with just javac. Delete your class files and then compile the main class. javac will recursively compile any classes it needs (providing you don't hide package private classes/interfaces in strangely named files). Of course, this doesn't cover any recursive hacks.
You may want to take a look at the `jdeps` command line tool: <https://docs.oracle.com/javase/8/docs/technotes/tools/unix/jdeps.html> ``` jdeps -cp <your cp> -v <path to your .class file> ``` The command will return a list of the dependencies for that java class file. There are many other options that you can use in...
How do I get a list of Java class dependencies for a main class?
[ "", "java", "dependencies", "dependency-management", "" ]
I have Slackware 12.1 and wish to try out Eclipse for PHP/HTML/JavaScript development. However, it seems I'm facing myriad of possible options and I'd hate to miss the best thing and give up on Eclipse (I'm currently using [Geany](http://www.geany.org), but I'm missing some stuff like , for example, auto-complete for J...
If you want auto-complete for JavaScript, in that case you should to use some plug-in for Eclipse such as Aptana Studio, but Aptana is more than auto-compete tool for javascript, it has included a lot of unnecessary things that you don't need for regular development. I have the same problem to find the right solution f...
I second Aptana wholeheartedly. Since it is based very closely off of Eclipse, if you ever decide to do coding that Aptana will not cover, you are still used to the general interface of Eclipse. I don't want to say it is cut down, because it is not. It just has what you need for the languages and technologies you will...
Which Eclipse version to install on Linux for PHP development
[ "", "php", "linux", "eclipse", "slackware", "" ]
Cruisecontrol and Hudson are two popular continuous integration systems. Although both systems are able to do the automated continuous builds nicely, it just seems a lot easier to create a batch or bash build script, then use Windows scheduler or cron to schedule builds. Are there better continuous integration systems...
We have been using [CruiseControl](http://cruisecontrol.sourceforge.net/) for CI on a C++ project. While it is the only thing we use ant for, the ant build script for CruiseControl just starts our normal build script, so it is very simple and we haven't really needed to update it in a long while. Therefore the fact tha...
We use [Hudson](http://hudson-ci.org/) for CI and [SonarQube](http://www.sonarqube.org/) for code metrics. They're integrated, and Hudson has a handful of plugins that no cronjob can beat. One great plugin is CI Game, which keeps a score about who breaks the builds and who commits without breaking it. Hudson has plugi...
What continuous integration tool is best for a C++ project?
[ "", "c++", "continuous-integration", "" ]