Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
Using Firebird, I want to combine the results of two queries using UNION ALL, then sort the resulting output on a given column. ``` (select C1, C2, C3 from T1) union all (select C1, C2, C3 from T2) order by C3 ``` The parentheses came from valid syntax for other databases, and are needed to make sure the arguments t...
``` SELECT C1, C2, C3 FROM ( select C1, C2, C3 from T1 union all select C1, C2, C3 from T2 ) order by C3 ```
Field names are not required to be equal. That's why you can't use the field name in the order by. You may use the field index instead. As in: ``` (select C1, C2, C3 from T1) union all (select C7, C8, C9 from T2) order by 3 ```
Combining UNION ALL and ORDER BY in Firebird
[ "", "sql", "database", "database-design", "firebird", "" ]
I need to include a copyright statement at the top of every Python source file I produce: ``` # Copyright: © 2008 etc. ``` However, when I then run such a file I get this message: SyntaxError: Non-ASCII character '\xa9' in file MyFile.py on line 3, but no encoding declared; see <http://www.python.org/peps/pep-0263...
The copyright symbol in ASCII is spelled `(c)` or "`Copyright`". See circular 61, [Copyright Registration for Computer Programs](http://www.copyright.gov/circs/circ61.pdf). While it's true that the legal formalism (see Circular 1, [Copyright Basics](http://www.copyright.gov/circs/circ01.pdf)) is > The symbol © (the ...
Contrary to the accepted answer, AFAIK, (c) is not an officially recognized alternative to the copyright symbol, although I'm not sure it's been tested in court. However, © is just an abreviation of the word Copyright. Saying "Copyright 2008 Robert Munro" is identical to saying "© 2008 Robert Munro" Your "Copyright: ...
Putting Copyright Symbol into a Python File
[ "", "python", "encoding", "" ]
Is it okay to run Hibernate applications configured with `hbm2ddl.auto=update` to update the database schema in a production environment?
No, it's unsafe. Despite the best efforts of the Hibernate team, you simply cannot rely on automatic updates **in production**. Write your own patches, review them with DBA, test them, then apply them manually. Theoretically, if **hbm2ddl update** worked in development, it should work in production too. But in realit...
We do it in production albeit with an application that's not mission critical and with no highly paid DBAs on staff. It's just one less manual process that's subject to human error - the application can detect the difference and do the right thing, plus you've presumably tested it in various development and test enviro...
Hibernate: hbm2ddl.auto=update in production?
[ "", "java", "hibernate", "hbm2ddl", "" ]
Here is the situation: I have been called upon to work with InstallAnywhere 8, a Java-based installer IDE, of sorts, that allows starting and stopping of windows services, but has no built-in method to query their states. Fortunately, it allows you to create custom actions in Java which can be called at any time durin...
here's what I had to do. It's ugly, but it works beautifully. ``` String STATE_PREFIX = "STATE : "; String s = runProcess("sc query \""+serviceName+"\""); // check that the temp string contains the status prefix int ix = s.indexOf(STATE_PREFIX); if (ix >= 0) { // compare status number to one of the sta...
You can create a small VBS on-th-fly, launch it and capture its return code. ``` import java.io.File; import java.io.FileWriter; public class VBSUtils { private VBSUtils() { } public static boolean isServiceRunning(String serviceName) { try { File file = File.createTempFile("realhowto",".vbs"); ...
Need a way to check status of Windows service programmatically
[ "", "java", "command-line", "windows-services", "" ]
So regular expressions seem to match on the longest possible match. For instance: ``` public static void main(String[] args) { String s = "ClarkRalphKentGuyGreenGardnerClarkSupermanKent"; Pattern p = Pattern.compile("Clark.*Kent", Pattern.CASE_INSENSITIVE); Matcher myMatcher = p.matcher(s); int i = 1; ...
greedy vs reluctant is your friend here. try: `Clark.+?Kent`
You want a "reluctant" rather than a "greedy" quantifier. Simply putting a ? after your \* should do the trick.
Negating literal strings in a Java regular expression
[ "", "java", "regex", "" ]
What exactly are the Python scoping rules? If I have some code: ``` code1 class Foo: code2 def spam..... code3 for code4..: code5 x() ``` Where is `x` found? Some possible choices include the list below: 1. In the enclosing source file 2. In the class namespace 3. In the function def...
Actually, a concise rule for Python Scope resolution, from [Learning Python, 3rd. Ed.](https://rads.stackoverflow.com/amzn/click/com/0596513984). (These rules are specific to variable names, not attributes. If you reference it without a period, these rules apply.) **LEGB Rule** * **L**ocal — Names assigned in any way...
Essentially, the only thing in Python that introduces a new scope is a function definition. Classes are a bit of a special case in that anything defined directly in the body is placed in the class's namespace, but they are not directly accessible from within the methods (or nested classes) they contain. In your exampl...
Short description of the scoping rules
[ "", "python", "scope", "" ]
I would like to trim long sequences of the same value from a binary file in python. A simple way of doing it is simply reading in the file and using re.sub to replace the unwanted sequence. This will of course not work on large binary files. Can it be done in something like numpy?
If you don't have the memory to do `open("big.file").read()`, then numpy wont really help.. It uses the same memory as python variables do (if you have 1GB of RAM, you can only load 1GB of data into numpy) The solution is simple - read the file in chunks.. `f = open("big.file", "rb")`, then do a series of `f.read(500)...
If two copies fit in memory, then you can easily make a copy. The second copy is the compressed version. Sure, you can use numpy, but you can also use the [array](http://www.python.org/doc/2.5.2/lib/module-array.html) package. Additionally, you can treat your big binary object as a string of bytes and manipulate it dir...
Removing a sequence of characters from a large binary file using python
[ "", "python", "numpy", "binaryfiles", "" ]
Here is what I have: JAVA\_HOME=C:\Software\Java\jdk1.5.0\_12 (points to JDK 5.0) In Eclipse "Installed Runtimes" I have: jre 1.5.0\_12 (points to JRE 5.0) jre 1.6.0\_3 (points to JRE 6.0) (this one is default) I do not have "javac" on my PATH (i.e. I cannot run javac -version from command line if I am not in JDK/bi...
Eclipse has the [JDT](http://www.eclipse.org/jdt/overview.php) which includes the incremental compiler so it does not need an external one unless that is your wish :)
Eclipse has a list of installed JRE's under **window->preferences->java->Installed JRE's**. The one selected as the default will be the one included with Eclipse, but you can easily add any other JRE's from this same preference pane, and select any default you wish. This will be the system wide default, which can be o...
Where does Eclipse find javac to compile a project?
[ "", "java", "eclipse", "" ]
I'm using Spring's dependency injection but I'm running into difficulty loading a resource in my Spring config file. The resource is an XML file and is in a JAR file on my classpath. I try to access it as follows: ``` <import resource="classpath:com/config/resources.xml" /> ``` however I keep getting encountering th...
If it needs to be in the classpath of your webapp, then you should stick the JAR containing the config file into your WEB-INF/lib directory. If you're using a webapp, then the common convention is use a ContextLoaderListener to ensure a WebApplicationContext is inserted into a standard place in the ServletContext: ``...
I ran into a similar issue with a red5 plugin. I resolved it like so: ``` try { subContext = new FileSystemXmlApplicationContext(new String[] { "classpath*:/myconfig.xml" }, true, context); } catch (Exception fnfe) { subContext = new FileSystemXmlApplicationContext(new String[] { "plugins/myconfig.xml" }, true, co...
spring beans configuration
[ "", "java", "spring", "" ]
I have a web-app that I would like to extend to support multiple languages with new URLs. For example, www.example.com/home.do stays English, but www.example.com/es/home.do is Spanish. My first thought was to create a Filter which rewrites incoming urls like /es/home.do to /home.do (and sets the Locale in the Request);...
I'm not sure that overriding `getContextPath()` is enough to solve your problem. What if Struts is calling `ServletContext.getContextPath()` under the covers, or uses `getRequestURI()`, etc?
As far as I know, the conventional way to do this is with the accept-language HTTP header. The presentation language is a presentation detail, which shouldn't be represented by the set of URLs to navigate through the application.
Override getContextPath in an HttpServletRequest (for URL rewriting)
[ "", "java", "jakarta-ee", "url-rewriting", "servlet-filters", "" ]
I'm writing a simple C++ class in which I would like cache picture thumbnails versions of images downloaded from the web. As such, I would like to use a hash function which takes in URL strings and outputs a unique string suitable as a filename. Is there a simple way to do this without re-writing the function myself? ...
A simpler approach is to replace everything which is not a character or a number with an underscore. EDIT: Here's a naive implementation in C: ``` #include <cctype> char *safe_url(const char *str) { char *safe = strdup(str); for (int i = 0; i < strlen(str); i++) { if (isalpha(str[i])) saf...
In a similar situation I encoded the key's bytes in hex (where, in your case, the key is the hash of the URL). This doubles the size but is simple, avoids any possible problems with your filesystem mangling the characters, and sorts in the same order as the original key. (Originally I tried a slightly fancier, more ef...
Encode URLs into safe filename string
[ "", "c++", "url", "caching", "hash", "filenames", "" ]
I'm trying to start `iexplore.exe` let it run for 5 seconds and then close it again. `iexplore` opens just fine however it doesn't close when I call the PostThreadMessage. Can anyone see what I'm doing wrong? Here is my code: ``` CString IEPath = "C:\\Program Files\\Internet Explorer\\IEXPLORE.EXE";//GetIEPath(); //I...
if you can enumerate the windows on the desktop and send a WM\_CLOSE to the IE window , it might work .. you can use the spy programme to get the window class of the IE window
What is the return value from the PostThreadMessage call? That might give a clue.
How do I use PostThreadMessage to close internet explorer from C++
[ "", "c++", "windows", "multithreading", "messaging", "" ]
How to convert Unicode string into a utf-8 or utf-16 string? My VS2005 project is using Unicode char set, while sqlite in cpp provide ``` int sqlite3_open( const char *filename, /* Database filename (UTF-8) */ sqlite3 **ppDb /* OUT: SQLite db handle */ ); int sqlite3_open16( const void *filename, /*...
Short answer: No conversion required if you use Unicode strings such as CString or wstring. Use sqlite3\_open16(). You will have to make sure you pass a WCHAR pointer (casted to `void *`. Seems lame! Even if this lib is cross platform, I guess they could have defined a wide char type that depends on the platform and i...
Use the [WideCharToMultiByte](http://msdn.microsoft.com/en-us/library/ms776420(VS.85).aspx) function. Specify `CP_UTF8` for the `CodePage` parameter. ``` CHAR buf[256]; // or whatever WideCharToMultiByte( CP_UTF8, 0, StringToConvert, // the string you have -1, // length of the string - set -1 to indicate it ...
How to convert Unicode string into a utf-8 or utf-16 string?
[ "", "c++", "unicode", "utf-8", "character-encoding", "utf-16", "" ]
I am developing a .NET CF 3.5 network game. My issue is the app loads all the resources at first instance. However upon subsequent launches, the app gives me memory out of exception while loading resources especially sounds or big images. Please guide me
I assume you're not attempting to lauch multiple instances of the game at a time. This sounds like memory is not being returned to the OS after your game shuts down. One simple way to determine if you have a leak is: 1. Restart the device 2. Check the memory usage 3. Start your game, play it for a few minutes 4. Close...
How much memory is your application taking after loading all the resources ? On default settings I have been getting this error coming over cca 1.3 GB of private bytes (checking the task manager and the processes memory allocation).
.NET CF Application and Out of Memory Exception
[ "", "c#", ".net", "memory-management", "" ]
I'd like to make an (MS)SQL query that returns something like this: ``` Col1 Col2 Col3 ---- --------------------- ------ AAA 18.92 18.92 BBB 20.00 40.00 AAA 30.84 30.84 BBB 06.00 12.00 AAA 30.84 30.84 AAA 46.79 ...
You didn't mention what kind of database you're using. Here's something that will work in SQL Server: ``` SELECT Col1, Col2, CASE WHEN Col1='AAA' THEN Col2 WHEN Col1='BBB' THEN Col2*2 ELSE NULL END AS Col3 FROM ... ```
You can also use the `ISNULL` or `COALESCE` functions like thus, should the values be null: ``` SELECT ISNULL(Col1, 'AAA') AS Col1, ISNULL(Col2, 0) AS Col2, CASE WHEN ISNULL(Col1, 'AAA') = 'BBB' THEN ISNULL(Col2, 0) * 2 ELSE ISNULL(Col2) END AS Col3 FROM Tablename ```
SQL inline if statement type question
[ "", "sql", "sql-server", "" ]
I am trying to have a tooltip on multiple lines. how do i do this?
Put a newline (use `Environment.NewLine`) into the actual tooltip text.
You can enter a newline in the designer also *(for static-text only, obviously)* by clicking the dropdown arrow near the tooltip property-box, and hitting enter where you want the newline.
Multiline tooltipText
[ "", "c#", "winforms", "" ]
Consider the following code: ``` template <int dim> struct vec { vec normalize(); }; template <> struct vec<3> { vec cross_product(const vec& second); vec normalize(); }; template <int dim> vec<dim> vec<dim>::normalize() { // code to normalize vector here return *this; } int main() { vec<3>...
You can't :) What you want is to specialize the member functions instead: ``` template <int dim> struct vec { // leave the function undefined for everything except dim==3 vec cross_product(const vec& second); vec normalize(); }; template<> vec<3> vec<3>::cross_product(const vec& second) { // ... } te...
You haven't supplied a definition of vec<3>::normalize, so the linker obviously can't link to it. The entire point in a template specialization is that you can supply specialized versions of each method. Except you don't actually do that in this case.
How can I get a specialized template to use the unspecialized version of a member function?
[ "", "c++", "templates", "specialization", "" ]
I have a Windows Mobile application using the compact framework (NETCF) that I would like to respond to someone pressing the send key and have the phone dial the number selected in my application. Is there a way using the compact framework to trap the send key? I have looked at several articles on capturing keys, but I...
I can confirm that using SHCMBM\_OVERRIDEKEY works on both PPC and SP devices. I have tested it on WM5 PPC, WM5 SP, WM6 PPC, WM6 SP. I have not tried WM6.1 or WM6.5 yet but I kind-of assume that they work since WM6 works. Also you may need to support DTMF during the call as well? Since I was writing a LAP dll I follo...
You can catch all keys in teh worlds (apart from CTRL+ALT+DEL on desktop) via a keyhook: [static extern IntPtr SetWindowsHookEx(HookType hook, HookProc callback, IntPtr hMod, uint dwThreadId);](http://www.pinvoke.net/default.aspx/user32/SetWindowsHookEx.html) You can use this (or one of the other overrides) in CE via...
Is there a way to capture the send key on Windows Mobile and have it dial a specific number?
[ "", "c#", "windows-mobile", "compact-framework", "key", "" ]
\*\* Dup: [What's the difference between X = X++; vs X++;?](https://stackoverflow.com/questions/226002/whats-the-difference-between-x-x-vs-x) \*\* So, even though I know you would never actually do this in code, I'm still curious: ``` public static void main(String[] args) { int index = 0; System.out.println(...
this is a duplicate question. **EDIT:** I can't seem to find the original :P oh well a = a++ uses the postincrement, which your compiler interprets as: ``` a = function() { var old_value = a; a++; return old_value; } ``` **EDIT 2:** [What's the difference between X = X++; vs X++;?](https://stackoverflow.co...
`value++;` is post increment. ``` int firtValue = 9; int secondValue = firstValue++; ``` firstValue is now 10, but secondValue is 9, the value of firstValue before it was incremented. Now with pre-increment: ``` int firtValue = 9; int secondValue = ++firstValue; ``` firstValue and secondValue are now 10, fistValue...
Why doesn't `index = index++` increment `index`?
[ "", "java", "" ]
I have a MySQL table LOGIN\_LOG with fields ID, PLAYER, TIMESTAMP and ACTION. ACTION can be either 'login' or 'logout'. Only around 20% of the logins have an accompanying logout row. For those that do, I want to calculate the average duration. I'm thinking of something like ``` select avg(LL2.TIMESTAMP - LL1.TIMESTAM...
Given the data you have, there probably isn't anything much faster you can do because you have to look at a LOGIN and a LOGOUT record, and ensure there is no other LOGIN (or LOGOUT?) record for the same user between the two. Alternatively, find a way to ensure that a disconnect records a logout, so that the data is co...
Do you have a SessionManager type object that can timeout sessions? Because a timeout could be logged there, and you could get the last activity time from that and the timeout period. Or you log all activity on the website/service, and thus you can query website/service visit duration directly, and see what activities...
SQL query to calculate visit duration from log table
[ "", "sql", "mysql", "duration", "" ]
I'm wondering where I find the source to show how the operator \*\* is implemented in Python. Can someone point me in the right direction?
The python grammar definition (from which the parser is generated using [pgen](http://www.python.org/dev/peps/pep-0269/)), look for 'power': [Gramar/Gramar](http://svn.python.org/view/python/trunk/Grammar/Grammar?rev=65872&view=markup) The python ast, look for 'ast\_for\_power': [Python/ast.c](http://svn.python.org/vi...
There are two different implementations one for int (long in 3.0) objects and another one for float objects. The float pow is the float\_pow(PyObject \*v, PyObject \*w, PyObject \*z) function defined in Objects/floatobject.c file of the Python source code. This functions calls pow() from C stdlib's math.h The int pow...
How is ** implemented in Python?
[ "", "python", "" ]
There is a simple C++ method to use pattern matching on strings? The code should sound like this: ``` if (regexpcmp("l?nole*[0-9]", "linoleum1")) { //we have a match! } else { //no match } ```
Not in the core language. Use Boost.Regex or an external library like `pcre`. In a unix environment you almost certainly have access to the BSD regular expression tools (`regcomp`, `regerror`, `regexec`, `regfree`) which are c-like rather than c++-like but do work.
Did you already look at [Boost.Regex](http://www.boost.org/doc/libs/release/libs/regex/)? ``` const boost::regex e("l?nole*[0-9]"); if (regex_match("linoleum1", e)) { //we have a match! } else { //no match } ```
There is a function to use pattern matching (using regular expressions) in C++?
[ "", "c++", "regex", "string", "" ]
I am working on a background program that will be running for a long time, and I have a external logging program ([SmartInspect](http://www.gurock.com/products/smartinspect/)) that I want to feed with some values periodically, to monitor it in realtime when debugging. I know I can simply fire up multiple programs, lik...
You can also use [System.Diagnostics.**Process.TotalProcessorTime**](http://msdn.microsoft.com/en-us/library/system.diagnostics.process.totalprocessortime.aspx) and [System.Diagnostics.**ProcessThread.TotalProcessorTime**](http://msdn.microsoft.com/en-us/library/system.diagnostics.processthread.totalprocessortime.aspx)...
Have a look at `System.Diagnostics.PerformanceCounter`. If you run up `perfmon.exe`, you'll see the range of performance counters available to you (set the 'performance object' to 'Process'), one of which is '% Processor Time'.
Can a C# program measure its own CPU usage somehow?
[ "", "c#", "monitoring", "cpu", "performancecounter", "" ]
When designing a lookup table (enum) in SqlServer 2005, if you know the number of entries will never get very high, should you use tinyint instead of int? I'm most concerned about performance, particularly efficiency of indexes. Let's say you have these representative tables: ``` Person ------ PersonId int (PK) Pers...
The narrower a table (or index node entry) is, the more records (or index nodes) can fit on a single IO page, and the fewer physical (and logical) reads IO operations are required for any query. Also, the more index nodes there are on a single page, the fewer levels there may be in the index, from root to leaf level, a...
Memory 101: Smaller stuff means holding more in RAM at once and thus fewer hard disk reads. If the DB is big enough and you're running certain kinds of queries, this could be a very serious factor. But it probably won't make big difference.
Is it worth the trouble to use tinyint instead of int for SqlServer lookup tables?
[ "", "sql", "sql-server", "database-design", "" ]
Before I write my own I will ask all y'all. I'm looking for a C++ class that is almost exactly like a STL vector but stores data into an array on the stack. Some kind of STL allocator class would work also, but I am trying to avoid any kind of heap, even static allocated per-thread heaps (although one of those is my s...
You don't have to write a completely new container class. You can stick with your STL containers, but change the second parameter of for example `std::vector` to give it your custom allocator which allocates from a stack-buffer. The chromium authors wrote an allocator just for this: <https://chromium.googlesource.com/...
It seems that [boost::static\_vector](http://www.boost.org/doc/libs/1_55_0/doc/html/container/non_standard_containers.html#container.non_standard_containers.static_vector) is what you are searching. From the documentation: > static\_vector is an hybrid between vector and array: like vector, it's a sequence container w...
Looking for C++ STL-like vector class but using stack storage
[ "", "c++", "data-structures", "stl", "vector", "" ]
I'm implementing unit tests for a family of functions that all share a number of invariants. For example, calling the function with two matrices produce a matrix of known shape. I would like to write unit tests to test the entire family of functions for this property, without having to write an individual test case fo...
You could use a metaclass to dynamically insert the tests. This works fine for me: ``` import unittest class UnderTest(object): def f1(self, i): return i + 1 def f2(self, i): return i + 2 class TestMeta(type): def __new__(cls, name, bases, attrs): funcs = [t for t in dir(UnderT...
Here's my favorite approach to the "family of related tests". I like explicit subclasses of a TestCase that expresses the common features. ``` class MyTestF1( unittest.TestCase ): theFunction= staticmethod( f1 ) def setUp(self): self.matrix1 = numpy.ones((5,10)) self.matrix2 = numpy.identity(5)...
How do I concisely implement multiple similar unit tests in the Python unittest framework?
[ "", "python", "unit-testing", "" ]
I want to use JavaScript to control an embedded Windows Media Player, as well as access any properties that the player exposes. I've found a few hacky examples online, but nothing concrete. I really need access to play, pause, stop, seek, fullscreen, etc. I'd also like to have access to any events the player happens t...
There is an API in Microsoft's developer center, but it will only work if you embed windows media player using active-x. To "learn" more about the API, check out MSDN: <http://msdn.microsoft.com/en-us/library/dd564034(VS.85).aspx>
The API requires ActiveX connectivity native to Internet Explorer, or can use a [plugin for Firefox](http://port25.technet.com/pages/windows-media-player-firefox-plugin-download.aspx). Here's a sample page that might get you started. ``` <html> <head> <title>so-wmp</title> <script> onload=function() { ...
Is there a documented JavaScript API for Windows Media Player?
[ "", "javascript", "windows-media-player", "" ]
What's the best way to load HTML markup for a custom jQuery UI widget? So far, I've seen elements simply created using strings (i.e. `$(...).wrap('<div></div>')`) which is fine for something simple. However, this makes it extremely difficult to modify later for more complex elements. This seems like a fairly common p...
Something which is quite neat to do is this: ``` var newDiv = $("<div></div>"); //Create a new element and save a reference newDiv.attr("id","someid").appendTo("body"); ``` That way, you are creating an element, and storing its reference in a variable, for later use.
If you have a large amount of complex HTML, and don't want to deal with hardcoded strings in your JavaScript code, you can put it in a separate HTML file and use the [Ajax load function](http://docs.jquery.com/Ajax/load). It's chainable, so you can load the HTML file (the whole thing, or a selected fragment), inject i...
jQuery UI: Best way to load HTML markup?
[ "", "javascript", "jquery", "jquery-ui", "jquery-ui-plugins", "" ]
We have a number of MS SQL Server 2005 installations (both Standard and Enterprise editions) on our webservers. From time to time I need to administrate them from home. Right now I'm using Remote Desktop to connect to my work machine, but I'd prefer to install SQL Server Management Studio on my home machine so that I c...
See this question: [What's the difference between SQL Server Management Studio and the Express edition?](https://stackoverflow.com/questions/117347/whats-the-difference-between-sql-server-management-studio-and-the-express-versi) Also, if you have any trouble doing anything from Managment Studio Express, there are th...
If you do a client tools only install of the standard edition (ie. just SSMS) and don't install the database, agent, etc. then I'm pretty sure you don't need another license and won't be violating the EULA. If you want a full install the SQL Server developer edition is only $49 and comes with everything. <http://www.m...
Can SQL Server Express be used to effectively administrate a SQL Server Standard/Enterprise installation?
[ "", "sql", "sql-server", "administration", "" ]
How can I match (PCRE) everything inbetween two tags? I tried something like this: > <!--\s\*LoginStart\s\*-->(.\*)<!--\s\*LoginEnd\s\*--> But it didn't work out too well for me.. I'm kind of new to regular expressions, so I was hoping if someone would be kind enough to explain to me how I would accomplish this, if...
``` $string = '<!-- LoginStart --><div id="stuff">text</div><!-- LoginEnds -->'; $regex = '#<!--\s*LoginStart\s*-->(.*?)<!--\s*LoginEnds\s*-->#s'; preg_match($regex, $string, $matches); print_r($matches); // $matches[1] = <div id="stuff">text</div> ``` explanations: ``` (.*?) = non greedy match (match the first <!-...
PHP and regex? Here's some suggestions: ``` '/<!--\s*LoginStart\s*-->(.*)<!--\s*LoginEnd\s*-->/Us' ``` Might be better - the `U` capitalized makes the regex non-greedy, which means it'll stop at the first `<!--` that may work. But the important one is the `s`, which tells the regex to match a newline with the `.` cha...
Match everything inbetween two tags with Regular Expressions?
[ "", "php", "html", "regex", "tags", "" ]
What's the best way, using C# or other .NET language, to determine if a file path string is on the local machine or a remote server? It's possible to determine if a path string is UNC using the following: ``` new Uri(path).IsUnc ``` That works great for paths that start with C:\ or other drive letter, but what about...
Don't know if there's a more efficient way of doing this, but it seems to work for me: ``` IPAddress[] host; IPAddress[] local; bool isLocal = false; host = Dns.GetHostAddresses(uri.Host); local = Dns.GetHostAddresses(Dns.GetHostName()); foreach (IPAddress hostAddress in host) { i...
This is how I did it. ``` public static bool IsLocal(DirectoryInfo dir) { foreach (DriveInfo d in DriveInfo.GetDrives()) { if (string.Compare(dir.Root.FullName, d.Name, StringComparison.OrdinalIgnoreCase) == 0) //[drweb86] Fix for different case. { return...
Method to determine if path string is local or remote machine
[ "", "c#", ".net", "uri", "unc", "" ]
I have an XML file and an XML schema in another file and I'd like to validate that my XML file adheres to the schema. How do I do this in Python? I'd prefer something using the standard library, but I can install a third-party package if necessary.
I am assuming you mean using XSD files. Surprisingly there aren't many python XML libraries that support this. lxml does however. Check [Validation with lxml](http://lxml.de/validation.html). The page also lists how to use lxml to validate with other schema types.
## An example of a simple validator in Python3 using the popular library [lxml](http://lxml.de/) **Installation lxml** ``` pip install lxml ``` If you get an error like *"Could not find function xmlCheckVersion in library libxml2. Is libxml2 installed?"*, try to do this first: ``` # Debian/Ubuntu apt-get install py...
Validating with an XML schema in Python
[ "", "python", "xml", "validation", "xsd", "" ]
To implement data access code in our application we need some framework to wrap around jdbc (ORM is not our choice, because of scalability). The coolest framework I used to work with is [Spring-Jdbc](http://static.springframework.org/spring/docs/2.5.x/reference/jdbc.html). However, the policy of my company is to avoid...
We wrote our own wrapper. This topic is worthy of a paper but I doubt I'll ever have time to write it, so here are some key points: * we embraced sql and made no attempt to hide it. the only tweak was to add support for named parameters. parameters are important because we do not encourage the use of on-the-fly sql (f...
Spring-JDBC is fantastic. Consider that for an open source project like Spring the down side of external dependency is minimized. You can adopt the most stable version of Spring that satisfies your JDBC abstraction requirements and you know that you'll always be able to modify the source code yourselves if you ever run...
simple jdbc wrapper
[ "", "java", "jdbc", "data-access", "spring-jdbc", "" ]
1. Why is operator '&' defined for bool?, and operator '&&' is not? 2. How exactly does this 1) bool? & bool? and 2) bool? and bool work? Any other "interesting" operator semantics on Nullable? Any overloaded operators for generic T?
Operators on `Nullable<T>` are "lifted" operators. What this means is: if T has the operator, T? will have the "lifted" counterpart. && and || aren't really operators in the same sense as & and | - for example, they can't be overloaded - from the ECMA spec 14.2.2 Operator overloading: > The overloadable binary operat...
There are no short-circuiting operators (&& ||) defined for `bool?` Only are the logical AND, inclusive OR, operators and they behave like this: ``` x y x & y x | y true true true true true false false true true null null true false true false true false false fals...
Nullable<T>: and overloaded operators, bool? & bool
[ "", "c#", "nullable", "" ]
How would you append an integer to a `char*` in c++?
First convert the int to a `char*` using `sprintf()`: ``` char integer_string[32]; int integer = 1234; sprintf(integer_string, "%d", integer); ``` Then to append it to your other char\*, use `strcat()`: ``` char other_string[64] = "Integer: "; // make sure you allocate enough space to append the other string strca...
You could also use stringstreams. ``` char *theString = "Some string"; int theInt = 5; stringstream ss; ss << theString << theInt; ``` The string can then be accessed using `ss.str();`
Append an int to char*
[ "", "c++", "integer", "char", "append", "" ]
List comprehensions can be useful in certain situations, but they can also be rather horrible to read.. As a slightly exaggerated example, how would you indent the following? ``` allUuids = [x.id for x in self.db.query(schema.allPostsUuid).execute(timeout = 20) if x.type == "post" and x.deleted is not False] ```
It depends on how long they are. I tend to structure them like so: ``` [x.id for x in self.db.query(schema.allPostsUuid).execute(timeout=20) if x.type == 'post' and x.deleted is not False and ... and ...] ``` That way every expression has its own line. If any line becomes too big I like to extract it ...
Where I work, our coding guidelines would have us do something like this: ``` all_posts_uuid_query = self.db.query(schema.allPostsUuid) all_posts_uuid_list = all_posts_uuid_query.execute(timeout=20) all_uuid_list = [ x.id for x in all_posts_uuid_list if ( x.type == "post" and no...
How to indent Python list-comprehensions?
[ "", "python", "coding-style", "" ]
Do you put unit tests in the same project for convenience or do you put them in a separate assembly? If you put them in a separate assembly like we do, we end up with a number of extra projects in the solution. It's great for unit testing while coding but how do you release the application without all of these extra a...
In my opinion, unit tests should be placed in a separate assembly from production code. Here are just a few cons of placing unit tests in the same assembly or assemblies as production code are: 1. Unit tests get shipped with production code. The only thing shipped with product code is production code. 2. Assemblies wi...
Separate project, but in the same solution. (I've worked on products with separate solutions for test and production code - it's horrible. You're always switching between the two.) The reasons for separate projects are as stated by others. Note that if you're using data-driven tests, you might end up with quite a sign...
Do you put unit tests in same project or another project?
[ "", "c#", "unit-testing", "" ]
In C#, I'm creating an XML file from a DataTable using dataTable.WriteXml(filePath), and get the following: ``` <?xml version="1.0" encoding="utf-8" ?> <ExperienceProfiles> <ExperienceProfile> <Col1>blah</Col1> <Col2>4ed397bf-a4d5-4ace-9d44-8c1a5cdb0f34</Col2> </ExperienceProfile> </ExperienceProfiles> ```...
What you want is some way to tell the DataSet the expected format of your data. You're in luck, the DataSet supports just this feature. You will need to create an XML schema for your data and load it into the DataSet before you write out the XML. In the schema define Col1 and Col2 as attributes of the ExperienceProfil...
you can use the ColumnMapping feature of the datatable column. . ``` column.ColumnMapping = MappingType.Attribute ```
How to specify format of XML output when writing from a DataTable?
[ "", "c#", "ado.net", "xsd", "" ]
I'm opening a new browser window from my site for some of the members. However, some may later close it, or it might have initially failed to open. Is there a snippet of fairly plain Javascript that can be run on each page to confirm if another browser window is open, and if not, to provide a link to re-open it? **[c...
This [excellent, comprehensive article](http://www.irt.org/articles/js205/index.htm) *("Almost complete control of pop-up windows")* should answer all your questions about javascript popup windows. *"JavaScript 1.1 also introduced the window **closed** property. Using this property, it is possible to detect if a windo...
``` var myWin = window.open(...); if (myWin.closed) { myWin = window.open(...); } ```
How do I confirm a browser window is open, with Javascript?
[ "", "javascript", "popup", "" ]
I am getting an 'access is denied' error when I attempt to delete a folder that is not empty. I used the following command in my attempt: `os.remove("/folder_name")`. What is the most effective way of removing/deleting a folder/directory that is not empty?
``` import shutil shutil.rmtree('/folder_name') ``` [Standard Library Reference: shutil.rmtree](http://docs.python.org/library/shutil.html#shutil.rmtree). By design, `rmtree` fails on folder trees containing read-only files. If you want the folder to be deleted regardless of whether it contains read-only files, then...
From [the python docs](http://docs.python.org/library/os.html#os.walk) on `os.walk()`: ``` # Delete everything reachable from the directory named in 'top', # assuming there are no symbolic links. # CAUTION: This is dangerous! For example, if top == '/', it # could delete all your disk files. import os for root, dirs...
How do I remove/delete a folder that is not empty?
[ "", "python", "file", "" ]
**Update** - for those of a facetious frame of mind, you can assume that Aggregate still produces the normal result whatever function is passed to it, including in the case being optimized. I wrote this program to build a long string of integers from 0 to 19999 separate by commas. ``` using System; using System.Linq;...
You are 'overriding' System.Linq.Aggregate with your own extension method in namespace MakeAggregateGoFaster. Perhaps specialised on `IEnumerable<string>` and making use of a StringBuilder? Maybe taking an `Expression<Func<string, string, string>>` instead of a `Func<string, string, string>` so it can analyse the exp...
Why not use one of the other forms of Aggregate? ``` Enumerable.Range(0, size ).Aggregate(new StringBuilder(), (a, b) => a.Append(", " + b.ToString()), (a) => a.Remove(0,2).ToString()); ``` You can specify any type for your seed, perform whatever formatting or custom calls are needed in the first lamb...
Optimizing Aggregate for String Concatenation
[ "", "c#", "optimization", "linq-to-objects", "" ]
With JSR 311 and its implementations we have a powerful standard for exposing Java objects via REST. However on the client side there seems to be something missing that is comparable to Apache Axis for SOAP - something that hides the web service and marshals the data transparently back to Java objects. How do you crea...
This is an old question (2008) so there are many more options now than there were then: * **Apache CXF** has three different [REST Client options](http://cxf.apache.org/docs/jax-rs-client-api.html) * **[Jersey](https://jersey.java.net/)** (mentioned above). * **[Spring RestTemplate](http://blog.springsource.com/2009/0...
As I mentioned in [this thread](https://stackoverflow.com/questions/165720/how-to-debug-restful-services#166269) I tend to use [Jersey](http://jersey.java.net/) which implements JAX-RS and comes with a nice REST client. The nice thing is if you implement your RESTful resources using JAX-RS then the Jersey client can re...
How do you create a REST client for Java?
[ "", "java", "rest", "client", "" ]
I got dtd in file and I cant remove it. When i try to parse it in Java I get "Caused by: java.net.SocketException: Network is unreachable: connect", because its remote dtd. can I disable somehow dtd checking?
You should be able to specify your own EntityResolver, or use specific features of your parser? See [here](https://stackoverflow.com/questions/155101/make-documentbuilderparse-ignore-dtd-references) for some approaches. A more complete example: ``` <?xml version="1.0"?> <!DOCTYPE foo PUBLIC "//FOO//" "foo.dtd"> <foo>...
This worked for me: ``` SAXParserFactory saxfac = SAXParserFactory.newInstance(); saxfac.setValidating(false); try { saxfac.setFeature("http://xml.org/sax/features/validation", false); saxfac.setFeature("http://apache.org/xml/features/nonvalidating/load-dtd-grammar", false); saxfac.setFeature("http://...
how to disable dtd at runtime in java's xpath?
[ "", "java", "xpath", "dtd", "doctype", "" ]
Java requires that you catch all possible exceptions or declare them as thrown in the method signature. This isn't the case with C# but I still feel that it is a good practice to catch all exceptions. Does anybody know of a tool which can process a C# project and point out places where an exception is thrown but not ca...
Check out the ExceptionFinder plug-in by Jason Bock for the .NET Reflector. It does just what you are looking for. Here's a screeny: Check it out on [CodePlex](http://www.codeplex.com/ExFinderReflector)
There is a R# plug-in that analyses thrown exceptions. <http://exceptionalplugin.codeplex.com/>
Checked exception catching in C#
[ "", "c#", "exception", "" ]
I have some code which ignores a specific exception. ``` try { foreach (FileInfo fi in di.GetFiles()) { collection.Add(fi.Name); } foreach (DirectoryInfo d in di.GetDirectories()) { populateItems(collection, d); } } catch (UnauthorizedAccessException ex) { //ignore and move o...
Just rewrite it as ``` catch (UnauthorizedAccessException) {} ```
As Dave M. and tvanfosson said, you want to rewrite it as ``` catch (UnauthorizedAccessException) {} ``` The bigger question that should be asked, however, is why you are catching an exception on ignoring it (commonly called swallowing the exception)? This is generally a bad idea as it can (and usually does) hide pro...
Ignoring exceptions
[ "", "c#", "exception", "" ]
In Java, you can qualify local variables and method parameters with the final keyword. ``` public static void foo(final int x) { final String qwerty = "bar"; } ``` Doing so results in not being able to reassign x and qwerty in the body of the method. This practice nudges your code in the direction of immutability...
You should try to do this, whenever it is appropriate. Besides serving to warn you when you "accidentally" try to modify a value, it provides information to the compiler that can lead to better optimization of the class file. This is one of the points in the book, "Hardcore Java" by Robert Simmons, Jr. In fact, the boo...
My personal opinion is that it is a waste of time. I believe that the visual clutter and added verbosity is not worth it. I have never been in a situation where I have reassigned (remember, this does not make objects immutable, all it means is that you can't reassign another reference to a variable) a variable in erro...
Why would one mark local variables and method parameters as "final" in Java?
[ "", "java", "final", "" ]
What is the most direct and/or efficient way to convert a `char[]` into a `CharSequence`?
Without the copy: ``` CharSequence seq = java.nio.CharBuffer.wrap(array); ``` However, the `new String(array)` approach is likely to be easier to write, easier to read and faster.
A `String` is a `CharSequence`. So you can just create a new `String` given your `char[]`. ``` CharSequence seq = new String(arr); ```
Java: convert a char[] to a CharSequence
[ "", "java", "string", "" ]
I want to send an array constructed in javascript with the selected values of a multiple select. Is there a way to send this array to a php script using ajax?
You can post back to your server with XML or JSON. Your javascript will have to construct the post, which in the case of XML would require you to create it in javascript. JSON is not only lighterweight but easier to make in javascript. Check out [JSON-PHP](http://mike.teczno.com/json.html) for parsing JSON. You might ...
You might do that with $.post method of jQuery (for example) : ``` var myJavascriptArray = new Array('jj', 'kk', 'oo'); $.post('urltocallinajax', {'myphpvariable[]': myJavascriptArray }, function(data){ // do something with received data! }); ``` Php will receive an array which will be name **myphpvariable** and ...
How can I send an array to php through ajax?
[ "", "php", "ajax", "multiple-select", "" ]
I'd like to write a plugin that does something with the currently edited file in Eclipse. But I'm not sure how to properly get the file's full path. This is what I do now: ``` IFile file = (IFile) window.getActivePage().getActiveEditor.getEditorInput(). getAdapter(IFile.class); ``` Now I have an IFile object, an...
Looks like you want [`IResource.getRawLocation()`](http://help.eclipse.org/helios/index.jsp?topic=%2Forg.eclipse.platform.doc.isv%2Freference%2Fapi%2Forg%2Feclipse%2Fcore%2Fresources%2FIResource.html). That returns an `IPath`, which also has a `makeAbsolute()` method if you want to be doubly sure you've got an absolute...
I think a more Java friendly solution would be to do use the following: ``` IResource.getLocation().toFile() ``` This takes advantage of the IPath API (the getLocation() part) and will return a java.io.File instance. Of course the other answers will probably get you to where you want to be too. On a tangential note,...
Get the absolute path of the currently edited file in Eclipse
[ "", "java", "eclipse", "eclipse-plugin", "eclipse-api", "" ]
I had been steering away from C# for a while, because it was "just a Windows thing", and it fell out of my current needs. However It's been gaining popularity and now with Mono catching up, it's becoming more attractive but I was wondering what IDE are people using to Code C#(with Mono) on \*nix platforms.
I think [MonoDevelop](http://monodevelop.com/Main_Page) is the most popular.
I use [Vim](http://www.vim.org) for all my \*nix stuff. There's even a Vim plugin for VS ([ViEmu](http://www.viemu.com)) so you can use your Vim tricks from within the IDE as well.
What is a decent Mono Editor?
[ "", "c#", "editor", "mono", "" ]
What's the best way to pass data from one Windows Forms app (an office plugin) to another (exe written in C#) in C#?
I'll take a wild stab at this and say you probably want the office app to *phone home* to your exe? In this context, the "exe" is the server and the office app is the client. If you're using .NET 3.0, WCF is likely your best bet. I would structure the solution into three parts: 1. "Shared Contracts". These are interf...
Yup. WCF is the way to go. I recommend checking out iDesign.net to use the InProcFactory class. You can shim up your office class into a service and call into your other application which is hosting a service. The other service can then call back into the office based service. You can use an IPC endpoint which will ma...
How to do intra-application communication in .NET
[ "", "c#", ".net", "windows", "" ]
The default seems to be upper case, but is there really any reason to use upper case for keywords? I started using upper case, because I was just trying to match what [SQL Server](https://en.wikipedia.org/wiki/Microsoft_SQL_Server) gives me whenever I tried to create something, like a new [stored procedure](https://en...
It's just a matter of style, probably originating in the days when editors didn't do code colouring. I used to prefer all upper case, but I'm now leaning towards all lower. Either way, be consistent.
PERSONALLY, I DON'T LIKE MY SQL YELLING AT ME. IT REMINDS ME OF BASIC OR COBOL. So I prefer my T-SQL lowercase with database object names MixedCase. It is much easier to read, and literals and comments stand out.
Is there a good reason to use upper case for SQL keywords?
[ "", "sql", "coding-style", "capitalization", "" ]
I'm trying to get the name of the executable of a window that is outside my C# 2.0 application. My app currently gets a window handle (hWnd) using the GetForegroundWindow() call from "user32.dll". From the digging that I've been able to do, I think I want to use the GetModuleFileNameEx() function (from PSAPI) to obtai...
You can call [GetWindowThreadProcessId](http://msdn.microsoft.com/en-us/library/ms633522(VS.85).aspx) and that will return you the process associated with the window. From that, you can call [OpenProcess](http://msdn.microsoft.com/en-us/library/ms684320.aspx) to open the process and get the handle to the process.
Been struggling with the same problem for an hour now, also got the first letter replaced by a **?** by using GetModuleFileNameEx. Finaly came up with this solution using the **System.Diagnostics.Process** class. ``` [DllImport("user32.dll")] public static extern IntPtr GetWindowThreadProcessId(IntPtr hWnd, IntPtr Pro...
How do I GetModuleFileName() if I only have a window handle (hWnd)?
[ "", "c#", "winapi", "hwnd", "getmodulefilename", "" ]
With multiple developers working on the same Tomcat application, I'd like to tell the application to install to a different path, based on the current user and revision control client/view. So, if Bob is building, the app should be installed in Bob's test environment, maybe /bob1 or something like that. Bob might have...
I typically use a variation on the default properties answer already given: ``` <property file="local.properties" /> <property file="default.properties" /> ``` I read the local properties file first and the default one second. Users don't edit the default one (then accidentally check it in), they just define the prop...
You can override ant properties from the command line. ``` ant -Dinstall.location=/bob1 install ``` See [Running Ant](http://ant.apache.org/manual/running.html) for more information.
Building with ant : dynamic build options?
[ "", "java", "ant", "build-process", "" ]
I've never actually used greasemonkey, but I was considering using it. Considering that GreaseMonkey allows you to let random people on the Internet change the behavior of your favorite websites, how safe can it be? Can they steal my passwords? Look at my private data? Do things I didn't want to do? How safe is Greasem...
*Considering that GreaseMonkey allows you to let random people on the Internet change the behavior of your favorite websites, how safe can it be?* It's as safe as you allow it to be - but you aren't very clear, so let's look at it from a few perspectives: ## Web Developer Greasemonkey can't do anything to your websi...
> Considering that GreaseMonkey allows you to let random people on the Internet change the behavior of your favorite websites Random people whose UserScript you have installed. No one can force you to install a UserScript. > Can they steal my passwords? Yes, a UserScript could modify a login page so it sent your pas...
How safe is Greasemonkey?
[ "", "javascript", "security", "greasemonkey", "" ]
I'm looking into tightening up our ad code by moving it to an external jQuery script, but I obviously still need some HTML to target the ad to. So I was wondering if I can target a noscript element (or within a noscript element) since I'm going to have to leave that on the page anyway, or if I need to have some other e...
`<noscript>` content is not only not displayed when JS is active, it apparently is also not in the DOM. I tried accessing content inside a `<noscript>` area (hoping you could `clone()` it with jQuery and insert it somewhere else) but got back nothing.
You can target noscript elemements. ``` <noscript>asdfasFSD</noscript> <script> alert(document.getElementsByTagName("noscript")[0].innerHTML); </script> ``` This works in FF3, IE6 and Google Chrome. It will alert asdfasFSD for me.
Does noscript get acknowledged by javascript enabled browsers?
[ "", "javascript", "jquery", "html", "" ]
I have a file upload form that is being posted back to a servlet (using multipart/form-data encoding). In the servlet, I am trying to use Apache Commons to handle the upload. However, I also have some other fields in the form that are just plain fields. How can I read those parameters from the request? For example, in...
You could try something like this: ``` while (items.hasNext()) { FileItem thisItem = (FileItem) items.next(); if (thisItem.isFormField()) { if (thisItem.getFieldName().equals("somefieldname") { String value = thisItem.getString(); // Do something with the val...
Took me a few days of figuring this out but here it is and it works, you can read multi-part data, files and params, here is the code: ``` try { ServletFileUpload upload = new ServletFileUpload(); FileItemIterator iterator = upload.getItemIterator(req); while(iterator.hasNext()){ ...
How can I read other parameters in a multipart form with Apache Commons
[ "", "java", "apache-commons", "multipartform-data", "" ]
If I have a Django form such as: ``` class ContactForm(forms.Form): subject = forms.CharField(max_length=100) message = forms.CharField() sender = forms.EmailField() ``` And I call the as\_table() method of an instance of this form, Django will render the fields as the same order as specified above. My q...
I went ahead and answered my own question. Here's the answer for future reference: In Django `form.py` does some dark magic using the `__new__` method to load your class variables ultimately into `self.fields` in the order defined in the class. `self.fields` is a Django `SortedDict` instance (defined in `datastructure...
New to Django 1.9 is **[Form.field\_order](https://docs.djangoproject.com/en/stable/ref/forms/api/#django.forms.Form.field_order)** and **[Form.order\_fields()](https://docs.djangoproject.com/en/stable/ref/forms/api/#django.forms.Form.order_fields)**. ``` # forms.Form example class SignupForm(forms.Form): passwor...
How does Django Know the Order to Render Form Fields?
[ "", "python", "django", "django-forms", "" ]
I need some help regarding algorithm for randomness. So Problem is. There are 50 events going to happen in 8 hours duration. Events can happen at random times. Now it means in each second there is a chance of event happening is 50/(8\*60\*60)= .001736. How can I do this with random generation algorithm? I can get ran...
* Create a list of 50 numbers. * Fill them with a random number between 1 and 8 \* 60 \* 60. * Sort them And you have the 50 seconds. Note that you can have duplicates.
Both `r` and `RAND_MAX` are integers, so the expression ``` double chance = r / RAND_MAX; ``` is computed with integer arithmetic. Try: ``` double chance = 1.0 * r / RAND_MAX; ``` which will cause the division to be a floating point division. However, a better solution would be to use a random function that return...
randomness algorithm
[ "", "c++", "random", "events", "" ]
Suppose I have a table with a numeric column (lets call it "score"). I'd like to generate a table of counts, that shows how many times scores appeared in each range. For example: ``` score range | number of occurrences ------------------------------------- 0-9 | 11 10-19 | 14 20-29 ...
Neither of the highest voted answers are correct on SQL Server 2000. Perhaps they were using a different version. Here are the correct versions of both of them on SQL Server 2000. ``` select t.range as [score range], count(*) as [number of occurences] from ( select case when score between 0 and 9 then ' 0- 9'...
An alternative approach would involve storing the ranges in a table, instead of embedding them in the query. You would end up with a table, call it Ranges, that looks like this: ``` LowerLimit UpperLimit Range 0 9 '0-9' 10 19 '10-19' 20 29 '20-29' 30 ...
In SQL, how can you "group by" in ranges?
[ "", "sql", "sql-server", "t-sql", "" ]
What is the best way to close a browser window of an AJAX ASP.NET application after the server-side has been executed. I found this [solution](https://stackoverflow.com/questions/250450/aspnet-ajax-close-window-after-ajax-call), but it seems a little complex for what I want to accomplish. Or is this the best way to ac...
No, there is no way to close a browser window without the user's consent. You can log them out of their application, but you can't forcibly close the browser window.
Actually you can do this by placing the following code in your button click event. ``` protected void btnMyButton_Click(object sender, ImageClickEventArgs e) { // Update database bool success = Presenter.DoDatabaseStuff(); if (success) { // Close window after success const string javaS...
Close a browser window of an ASP.NET and AJAX application
[ "", "asp.net", "javascript", "asp.net-ajax", "" ]
I have a two-dimensional array (of Strings) which make up my data table (of rows and columns). I want to sort this array by any column. I tried to find an algorithm for doing this in C#, but have not been successful. Any help is appreciated.
Load your two-dimensional string array into an actual DataTable (System.Data.DataTable), and then use the DataTable object's Select() method to generate a sorted array of DataRow objects (or use a DataView for a similar effect). ``` // assumes stringdata[row, col] is your 2D string array DataTable dt = new DataTable()...
Can I check - do you mean a rectangular array (`[,]`)or a jagged array (`[][]`)? It is quite easy to sort a jagged array; I have a discussion on that [here](http://groups.google.co.uk/group/microsoft.public.dotnet.languages.csharp/browse_thread/thread/1e1a4bd58144bf73/364f22121b566a3c#23b3e4487e91cd02). Obviously in t...
How do I sort a two-dimensional (rectangular) array in C#?
[ "", "c#", "arrays", "sorting", "" ]
I like generics a lot and use them whereever I can. Every now and then I need to use one of my classes in another project which has to run on an old JVM (before 5.0), needs to run on JavaME (where generics are not allowed neither) or in Microsoft J# (which has VERY poor Support for generics). At the moment, I remove a...
You need to use something like [Retroweaver](http://retroweaver.sourceforge.net/) in order to achieve this sort of thing. The other answers on this question are slightly misleading. Generics are sort-of bytecode compatible with previous versions, but not entirely (see `java.lang.reflect.Type` if you don't believe me). ...
In Netbeans (I'm not sure about what IDE you are using) you can set the source-code compatibility to a set java version - just set it to one that supports generics. As already posted, generics are bytecode compatable with old JVM / JRE versions and so it should hopefully work out of the box.
How to use generics in a world of mixed Java versions?
[ "", "java", "generics", "jvm", "portability", "" ]
I'm working in a windows environment (my laptop!) and I need a couple of scripts that run other programs, pretty much like a windows batch file. how can I run a command from python such that the program when run, will replace the script? The program is interactive (for instance, unison) and keeps printing lines and as...
I found out that os.system does what I want, Thanks for all that tried to help. ``` os.system("dir") ``` runs the command just as if it was run from a batch file
You should create a new processess using the [subprocess module](http://www.python.org/doc/2.5.2/lib/module-subprocess.html). I'm not fluent in windows processes but its Popen function is cross-platform, and should be preffered to OS specific solutions. EDIT: I maintain that you should prefer the Subprocess module to...
python as a "batch" script (i.e. run commands from python)
[ "", "python", "scripting", "batch-file", "" ]
I'm trying to complete a practice question from a book on generics but the question doesn't make sense to me. Here it goes. Create two classes with identical functionality. Use generics for the first class, and cast the second class to Object types. Create a for loop that uses class and the Object based class to deter...
I think that the question is asking you to create a collection class, and insert instances of your class into that. E.g., Generics version: ``` List<Human> myList = new List<Human>(); Human h = new Human(); myList.Add(h); ``` Object version: ``` ArrayList myObjectList = new ArrayList(); Human h = new Human(); myOb...
I think the question is for looping over a collection of your classes. **Generic** ``` List<Person> pList = new List<Person>(); for(int i = 0; i<1000; ++i) pList.Add(new Person(30)); StopWatch sw = new StopWatch(); sw.start(); int sum = 0; foreach(Person p in pList) sum += p.Value; sw.Stop(); ``` **Object**...
C# generics question
[ "", "c#", "generics", "" ]
I'm writing a service that has five different methods that can take between 5 seconds and 5 minutes to run. The service will schedule these different methods to run at different intervals. I don't want any of the methods to run concurrently, so how do I have the methods check to see if another method is running and q...
If you want *simple*, and all the methods are in the same class, ou can just use `[MethodImpl]`: ``` [MethodImpl(MethodImplOptions.Synchronized)] public void Foo() {...} [MethodImpl(MethodImplOptions.Synchronized)] public void Bar() {...} ``` For instance methods, this locks on `this`; for static methods, this locks...
There's the [MethodImplOptions.Synchronized attribute](http://msdn.microsoft.com/en-us/library/system.runtime.compilerservices.methodimploptions.aspx), as noted in the article [Synchronized method access in C#](http://bartdesmet.net/blogs/bart/archive/2006/10/02/4490.aspx), but that can lead to deadlocks as noted at MS...
Forcing threads in a service to wait for another thread to finish
[ "", "c#", ".net", "multithreading", "" ]
I have a two way foreign relation similar to the following ``` class Parent(models.Model): name = models.CharField(max_length=255) favoritechild = models.ForeignKey("Child", blank=True, null=True) class Child(models.Model): name = models.CharField(max_length=255) myparent = models.ForeignKey(Parent) ``` How ...
I just came across [ForeignKey.limit\_choices\_to](http://docs.djangoproject.com/en/dev/ref/models/fields/#django.db.models.ForeignKey.limit_choices_to) in the Django docs. Not sure yet how it works, but it might be the right thing here. **Update:** `ForeignKey.limit_choices_to` allows one to specify either a constant...
The 'right' way to do it is to use a custom form. From there, you can access self.instance, which is the current object. Example -- ``` from django import forms from django.contrib import admin from models import * class SupplierAdminForm(forms.ModelForm): class Meta: model = Supplier fields = "_...
How do I restrict foreign keys choices to related objects only in django
[ "", "python", "django", "django-models", "" ]
I wonder if there is a way to set the value of #define in run time. I assume that there is a query for Oracle specific and Sql Server specific at the code below. ``` #define oracle // ... #if oracle // some code #else // some different code. #endif ```
Absolutely not, #defines are compiled out by the preprocessor before the compiler even sees it - so the token 'oracle' isn't even in your code, just '1' or '0'. Change the #define to a global variable or (better) a function that returns the correct value.
`#if` is compile-time. You could specify this in your build process (via switches to msbuild/csc), but not really at runtime. The excluded code *doesn't exist*. You might be better advised to (1 of): * Have separate DAL stacks for each back-end, using Dependency Injection / IoC * Use an ORM tool that supports either *...
Is there a way to set the value of #define on runtime?
[ "", "c#", "c-preprocessor", "" ]
In LinqToSql, it is lovely easy to load a row, change a column, and submit the changes to the database: ``` using (MyDataContext wdc = new MyDataContext()) { Article article = wdc.Article.First(p => p.ID == id); article.ItemsInStock = itemsinstock; wdc.SubmitChanges(); } ``` The only drawback: Article i...
ligget78 gave me another idea how to make an update of a single column: Create a new DataContext just for this kind of update, and only include the needed columns into this DataContext. This way the unneeded columns will not even be loaded, and of course not sent back to the database.
You need to set UpdateCheck on all properties of the Article class except the primary key (click on the class property in LINQ2SQL designer and switch to Properties Tool Window) to Never (not sure about WhenChanged, maybe that works too - go ahead and experiment with it!). This will force LINQ2SQL to use ``` UPDATE ....
How to update a single column in LINQ without loading the entire row?
[ "", "c#", "linq", "performance", "linq-to-sql", "" ]
I'm wanting to write a method that I can use to initialise a Map. First cut: ``` Map map(Object ... o) {for (int i = 0; i < o.length; i+=2){result.put(o[i], o[i+1])}} ``` Simple, but not type-safe. Using generics, maybe something like: ``` <TKey, TValue> HashMap<TKey, TValue> map(TKey ... keys, TValue ... values) ``...
To make life easier for yourself, never use a return type that contains wildcards. Wildcard types, in general, are for method parameters only. So, try this: ``` public static <TKey, TValue, TMap extends Map<TKey, TValue>> TMap map(TMap map, Pair<? extends TKey, ? extends TValue>... pairs) { for (Pair<? extends TK...
Why not this? Did I misunderstand something? ``` import java.util.HashMap; import java.util.Map; public class ToHash { public static <K, V> Map<K, V> toHash(Object... objects) { Map<K, V> map = new HashMap<K, V>(objects.length / 2); if (objects.length % 2 != 0) { throw new IllegalArgum...
Type-safe varargs method that initialises a Map
[ "", "java", "generics", "variadic-functions", "" ]
I am wondering how you would approach this problem I have two Taxrates that can apply to my products. I specifically want to avoid persisting the Taxrates into the database while still being able to change them in a central place (like Taxrate from 20% to 19% etc). so I decided it would be great to have them just com...
EDIT: Note that the code here could easily be abbreviated by having a private constructor taking the tax rate and the name. I'm assuming that in real life there might be actual behavioral differences between the tax rates. It sounds like you want something like Java's enums. C# makes that fairly tricky, but you can d...
I'd do it like this: ``` public class TaxRate { public readonly string Name; public readonly decimal Rate; private TaxRate(string name, decimal rate) { this.Name = name; this.Rate = rate; } public static readonly TaxRate NormalRate = new TaxRate("Normal rate", 20); public...
Enum struct? A Value object that behaves like a Enum
[ "", "c#", "enums", "" ]
I am reading in numbers from a file and then trying to add them to an array. My problem is how do you increase the size of the array? For example I thought might be able to just do: ``` #include <iostream> using namespace std; int main() { double *x; x = new double[1]; x[0]=5; x = new double[1]; x...
You don't want to work with arrays directly. Consider using a `vector`, instead. Then, you can call the `push_back` function to add things to the end, and it will automatically resize the vector for you. ``` #include <iostream> #include <vector> int main() { double value; std::vector<double> values; // R...
You should use a collection class to do this for you rather than managing it yourself. Have a look at the "vector" class. It's essentially a dynamic array that resizes automatically as required. In your situation you would use "vector" with the "double" type. You may also need to read up on templates in C++. <http://...
Dynamic Arrays - How to increase the size of an array?
[ "", "c++", "arrays", "" ]
Is there an equivalent to the Java File method **isDirectory()** in MFC? I tried using this : ``` static bool isDirectory(CString &path) { return GetFileAttributes(path) & FILE_ATTRIBUTE_DIRECTORY; } ``` but it doesn't seem to work.
Sorry for possibly "inconsistency" of answer to question but may be you'll see it useful because anytime I need something like this in Windows I am NOT using MFC but regular Windows API: ``` //not completely tested but after some debug I'm sure it'll work bool IsDirectory(LPCTSTR sDirName) { //First define special...
# CFileFind::IsDirectory() <http://msdn.microsoft.com/en-us/library/scx99850(VS.80).aspx> EDIT: ``` #include <afxwin.h> #include <iostream> using namespace std; CFileFind finder; fileName += _T("c:\\aDirName"); if (finder.FindFile(fileName)) { if (finder.FindNextFIle()) { ...
MFC Equivalent to Java File#isDirectory()
[ "", "c++", "mfc", "path", "directory", "" ]
Is it possible to using "paging" functionality in Linq queries? Let's say I have some XML like this: ``` <Root> <BetaSection> <Choices> <SetA> <Choice id="choice1">Choice One</Choice> <Choice id="choice2">Choice Two</Choice> <Choice id="choice3">...
``` var q = from X in Choices.Skip((page-1)*pageSize).Take(pageSize) select X; ``` Now, if you need a where clause in it, it gets a bit trickier: ``` var q = (from X in Choices where x.SomeField == SomeValue select X).Skip((page-1)*pageSize).Take(pageSize); ```
Absolutely - `Skip()` and `Take()` achieve paging, and are supported by pretty-much all LINQ providers. In this case it looks like you are using LINQ-to-Xml, so feel free to ignore the following bit - but for general info: note that if the data is coming from a database via a stored procedure, it is hard to page at th...
Newbie LINQ Question: Is Paging in LINQ Queries Possible?
[ "", "c#", "linq-to-xml", "" ]
I'm hoping that it isn't to pass each as a parameter to the controller post method.. Have a grid of 52 text boxes representing weeks in a year, each will be containing a decimal value, need ALL of these passed back to the controller for mass updating of the database.. edit: Adding more details. So my action Index();...
I would suggestion using a Model Binder: <http://www.singingeels.com/Articles/Model_Binders_in_ASPNET_MVC.aspx> <http://www.singingeels.com/Articles/Model_Binders_in_ASPNET_MVC__Part_2.aspx>
Check out this question. It should provide you with a better answer than using the FormCollection. [Complex model binding to a list](https://stackoverflow.com/questions/231878/complex-model-binding-to-a-list)
MVC ASP.NET Best way to get 52 textbox key/values from View to Controller
[ "", "c#", "asp.net-mvc", "" ]
Unit testing with C/C++: What do you teach people who either did not do unit testing before or come from Java/Junit? What is the single most important lesson / thing to remember/ practice from your point of view that saves a lot of time or stress (especially regarding C/C++)?
1. Unit tests have to run automatically on every checkin (or, unit tests that are written then forgotten are not unit tests). 2. Before fixing a bug, write a unit test to expose it (it should fail). Then fix the bug and rejoice as the test turns green. 3. It's OK to sacrifice a bit of "beauty" of a class for easier tes...
Read this... you will anyway.. ![alt text](https://i.stack.imgur.com/iaN6v.jpg)
Unit testing with C/C++: Lessons, what to remember?
[ "", "c++", "unit-testing", "tdd", "" ]
I'm working with a database schema that is running into scalability issues. One of the tables in the schema has grown to around 10 million rows, and I am exploring sharding and partitioning options to allow this schema to scale to much larger datasets (say, 1 billion to 100 billion rows). Our application must also be d...
I agree with the other answers that you should look at your schema and indexes before resorting to sharding. 10 million rows is well within the capabilities of any of the major database engines. However if you want some resources for learning about the subject of sharding then try these: * [Scalability Best Practices...
I agree with Mike Woodhouse's observation that the current size should not be an issue - and the questioner agrees. Most of the commercial DBMS provide support for fragmented tables in some for or another, under one name or several others. One of the key questions is whether there is a sensible way of splitting the da...
Resources for Database Sharding and Partitioning
[ "", "sql", "database", "scalability", "sharding", "database-cluster", "" ]
I am trying to process files one at a time that are stored over a network. Reading the files is fast due to buffering is not the issue. The problem I have is just listing the directories in a folder. I have at least 10k files per folder over many folders. Performance is super slow since File.list() returns an array in...
Although it's not pretty, I solved this kind of problem once by piping the output of dir/ls to a file before starting my app, and passing in the filename. If you needed to do it within the app, you could just use system.exec(), but it would create some nastiness. You asked. The first form is going to be blazingly fas...
How about using File.list(FilenameFilter filter) method and implementing FilenameFilter.accept(File dir, String name) to process each file and return false. I ran this on Linux vm for directory with 10K+ files and it took <10 seconds. ``` import java.io.File; import java.io.FilenameFilter; public class Temp { ...
Is there a workaround for Java's poor performance on walking huge directories?
[ "", "java", "performance", "directory-walk", "" ]
I'm creating some videos from a collection of images, I subsequently wish to play this video back with java. I found JMF but I haven't been able to find an encoding which is actually playable by it. Does anybody have an ffmpeg or mencoder formulation which produces JMF playable output? I would also take alternatives to...
According to the [JMF 2.1.1 - Supported Formats](http://java.sun.com/javase/technologies/desktop/media/jmf/2.1.1/formats.html) page, Quicktime and various codecs are supported for decoding directly.
Two things, you will need to use the formats listed here: <http://java.sun.com/javase/technologies/desktop/media/jmf/2.1.1/formats.html> Secondly, JMF still seems to have problems under certain resolutions, framerates and bitrates. I've found that it successfully can decode when the video to read, is not only in the ac...
Encoding for JMF
[ "", "java", "ffmpeg", "jmf", "" ]
How do you detect which form input has focus using JavaScript or jQuery? From within a function I want to be able to determine which form input has focus. I'd like to be able to do this in straight JavaScript and/or jQuery.
I am not sure if this is the most efficient way, but you could try: ``` var selectedInput = null; $(function() { $('input, textarea, select').focus(function() { selectedInput = this; }).blur(function(){ selectedInput = null; }); }); ```
[`document.activeElement`](https://developer.mozilla.org/en-US/docs/Web/API/Document/activeElement), it's been supported in IE for a long time and the latest versions of FF and chrome support it also. If nothing has focus, it returns the `document.body` object.
Detect which form input has focus using JavaScript or jQuery
[ "", "javascript", "jquery", "focus", "forms", "" ]
**Problem:** a table of coordinate lat/lngs. Two rows can potentially have the same coordinate. We want a query that returns a set of rows with unique coordinates (within the returned set). Note that `distinct` is not usable because I need to return the id column which is, by definition, distinct. This sort of works (`...
You might be able to use a CTE for this with the ROW\_NUMBER function across lat and long and then use rand() against that. Something like: ``` WITH cte AS ( SELECT intID, ROW_NUMBER() OVER ( PARTITION BY geoLat, geoLng ORDER BY NEWID() ) AS r...
this doesn't work for you? ``` select top (@maxcount) * from ( select max(intid) as id from Documents d group by d.geoLng, d.geoLat ) t order by newid() ```
SQL Server rand() aggregate
[ "", "sql", "sql-server", "geo", "" ]
I use Eclipse (3.4) and my class compiles without warning or errors. My project uses an external jar file. Where do I need to put this external jar file in order not to get a `java.lang.NoClassDefFoundError` when using this class from another project (not in Eclipse)? I could just extract the jar into the project fol...
If you're wanting to include a JAR file to your Eclipse project, you would generally create a 'lib' folder inside the project folder, and put the file in there. You then need to tell eclipse to include it in your class path so your code will compile and run inside eclipse. To do that: - Go into the properties o...
put it in your `jre/lib/ext` folder everything said about the classpath is true, but this is a consistent and sensible place for it to live. you can find out your jre folder by looking at the JAVA\_HOME environment variable on Windows.
Where to put the external jars?
[ "", "java", "eclipse", "jar", "eclipse-3.4", "ganymede", "" ]
I would like to convert an array if IDs, into a string of comma separated values, to use in a MySQL UPDATE query. How would I do this?
Remember to escape values: ``` '"' . implode('","', array_map('mysql_real_escape_string', $data)) . '"' ```
``` implode(',', $array); ```
How do you output contents of an array as a comma separated string?
[ "", "php", "arrays", "" ]
How can i make my Java Swing GUI Components [Right To Left] for Arabic language from NetBeans Desktop Application?
Don't you just have to use: ``` Component.setComponentOrientation( ComponentOrientation.RIGHT_TO_LEFT ) ``` I believe that the swing components all already have support for RTL, don't they? Not sure how/where you'd do that in regards to netbeans, though.
The call of ``` Component.setComponentOrientation( ComponentOrientation.RIGHT_TO_LEFT ) ``` should do the trick. But be sure to use the SwingConstants LEADING and TRAILING instead of LEFT and RIGHT in your layouts. The same goes for GridBagConstraints.LINE\_START or LINE\_END instead of WEST or EAST, and probably so...
JAVA Swing GUI Components howto RTL view?
[ "", "java", "swing", "right-to-left", "" ]
I would like to learn the best practices to employ when creating a database driven web-application. I prefer to learn from examples. What is a good sample application that I can download and run to learn this: I am looking for: 1. Should be written in C# (preferably) 2. Should contain a complex database design (paren...
If you don't want to worry about writing your [DAL](http://en.wikipedia.org/wiki/Data_access_layer) (Data Access Layer), then I suggest looking at [Nhibernate](http://www.nhibernate.org). There are samples with it and ASP.NET [here](http://www.beansoftware.com/asp.net-tutorials/nhibernate-log4net.aspx), [here](http://w...
There are lots of examples in [ASP.NET Starter](http://www.asp.net/community/projects/) Kits. I really like the [BlogEngine.NET](http://www.asp.net/downloads/starter-kits/blog-engine/) application. For higher-end basics (hmmm..."higher-end basics"...oxymoron?) the [BeerHouse E-Commerce application](http://www.asp.net/d...
Where can I find a Good Sample ASP.NET Database Driven Web Application?
[ "", "c#", "asp.net", "database", "" ]
I'm writing a simple program to browse the local network and pass on filenames to mplayer using "system". However, sometimes filenames contain spaces or quotes. Obviously I could write my own function to escape those, but I'm not sure exactly what characters do or do not need escaping. Is there a function available in...
There isn't a single solution that works everywhere because different shells have different ideas of what special characters are and how they are interpreted. For bash, you could probably get away with surrounding the entire filename in single quotes after replacing every single quote in the file name with `'"'"'` (the...
Other answers include this fork and exec solution, but I claim that this is the only right way to do it. Escaping shell arguments is prone to bugs and a waste of time, just as trying to escape SQL parameters is a silly idea when safer and more efficient parameter binding APIs exist. Here is a sample function: ``` vo...
How to safely escape a string from C++
[ "", "c++", "c", "linux", "shell", "" ]
If a packed Javascript saves 20kb off the download size, but takes a perfomance hit to unpack, then are there any benefits, besides obfuscating the code? I've made this a community wiki because it may be open to some discussion.
Packed javascript code generally does not take longer to execute vs regular code. Most code packers will shorten variables, function names and use a host of tricks to make the source smaller. The resulting source is fully executable! You can verify this by taking a look at it during runtime with firebug. You'll see the...
Short answer yes, because the client machine's unpacking time is faster than transmission, also the internet is overloaded as is, so any contribution to making things better is appreciated by anonymous, also remember that most clients will be caching this stuff, and the larger the file the more chances it will get itse...
Packing Javascripts - Is it worth it?
[ "", "javascript", "" ]
I have seen a lot of `ob_get_clean()` the last while. Typically I have done `$test .= 'test'` I'm wondering if one is faster and/or better than the other. Here is the code using `ob_get_clean()`: ``` ob_start(); foreach($items as $item) { echo '<div>' . $item . '</div>'; } $test = ob_get_clean(); ``` Here is ...
Output buffers have all the pitfalls of global variables. You have to be aware of all execution paths from the `ob_start()` to the `ob_get_clean()`. Are you sure it will get there, and that any buffers opened in between will have been closed? Keep in mind that code can throw exceptions. That can be a really fun bug for...
The results are the same, and I'd imagine the performance differences are negligible if any. Basically, a matter of personal style preference. I would go with concatenation myself - I use output buffering only when concatenation is not an option. Also, instead of running both `ob_get_contents()` and `ob_clean()` simpl...
Is it better to use ob_get_contents() or $text .= 'test';
[ "", "php", "optimization", "concatenation", "" ]
Why one would use one of the following packages instead of the other? * Java Logging * Commons Logging * Log4j * SLF4j * Logback
In chronological order of api apperance (as far as I know): * Log4j because most everybody uses it (in my experience) * Commons Logging because open source projects use it (so they can integrate with whatever logging framework is used in the integrated solution); especially valid if you're an API/Framework/OSS and you...
I find logging in Java to be confusing, inconsistent, poorly documented, and especially haphazard. Moreover, there is a huge amount of similarity between these logging frameworks resulting in duplication of effort, and confusion as to what logging environment you are actually in. In particular, if you are working in a ...
What's Up with Logging in Java?
[ "", "java", "logging", "log4j", "logback", "slf4j", "" ]
Here is a little test program: ``` #include <iostream> class Test { public: static void DoCrash(){ std::cout<< "TEST IT!"<< std::endl; } }; int main() { Test k; k.DoCrash(); // calling a static method like a member method... std::system("pause"); return 0; } ``` On VS2008 + SP1 (vc9) it compil...
The standard states that it is not necessary to call the method through an instance, that does not mean that you cannot do it. There is even an example where it is used: C++03, 9.4 static members > A static member s of class X may be referred to using the > qualified-id expression X::s; it is > not necessary to use t...
Static functions doesn´t need an instanciated object for being called, so ``` k.DoCrash(); ``` behaves exactly the same as ``` Test::DoCrash(); ``` using the scope resolution operator (::) to determine the static function inside the class. *Notice that in both case the compiler doesn´t put the `this` pointer in th...
C++ Static member method call on class instance
[ "", "c++", "visual-c++", "standards", "" ]
I´m working on a project, in Visual Studio 2008, which DLL currently surpasses 20 MB. Is there a way to profile that DLL, searching the main contributors to this size? I suspect that breaking it in smaller projects inside the solution would help, but I'm looking for a faster solution (although not better, I'm afraid)....
Yowser! Have you perchance got some huge resx files (or other embedded content) that are getting embedded in the dll? Perhaps treat those as external content? I'd start by looking at the files in the project tree... that 20Mb has to come from somewhere obvious - large graphics, etc.
[PE Explorer](http://www.heaventools.com/overview.htm) will show you the contents. [This](http://wiki.answers.com/Q/How_do_you_open_.dll_files_to_see_what_is_written_inside) may also help? Update: [Dependency Walker](http://www.dependencywalker.com/) may also help here. You can run it in "Profile Mode" which works by...
How to minimize a ASP.NET C# project DLL size?
[ "", "c#", "asp.net", "visual-studio-2008", "" ]
I have a file and I don't know how big it's going to be (it could be quite large, but the size will vary greatly). I want to search the last 10 lines or so to see if any of them match a string. I need to do this as quickly and efficiently as possible and was wondering if there's anything better than: ``` s = "foo" las...
``` # Tail from __future__ import with_statement find_str = "FIREFOX" # String to find fname = "g:/autoIt/ActiveWin.log_2" # File to check with open(fname, "r") as f: f.seek (0, 2) # Seek @ EOF fsize = f.tell() # Get Size f.seek (max (fsize-1024, 0), 0) # Set pos @ ...
Here's an answer like MizardX's, but without its apparent problem of taking quadratic time in the worst case from rescanning the working string repeatedly for newlines as chunks are added. Compared to the Active State solution (which also seems to be quadratic), this doesn't blow up given an empty file and does one se...
Most efficient way to search the last X lines of a file?
[ "", "python", "file", "search", "" ]
I have very little experience building software for Windows, and zero experience using the Windows API, but I'm reasonably familiar with Python. How should I go about learning to use the Windows API with Python?
Honestly, no. The Windows API is an 800 pound monster covered with hair. [Charlie Petzold's 15 pound book](http://www.charlespetzold.com/faq.html) was the canonical reference once upon a time. That said, the [Python for Windows](http://python.net/crew/mhammond/win32/) folks have some good material. Microsoft has the [...
About 4 years ago I set out to truly understand the Windows API. I was coding in C# at the time, but I felt like the framework was abstracting me too much from the API (which it was). So I switched to Delphi (C++ or C would have also been good choices). In my opinion, it is important that you start working in a langua...
How should I learn to use the Windows API with Python?
[ "", "python", "winapi", "" ]
**Does anyone know of an algorithm (or search terms / descriptions) to locate a known image within a larger image?** e.g. I have an image of a single desktop window containing various buttons and areas (target). I also have code to capture a screen shot of the current desktop. I would like an algorithm that will help...
You said your image may not be exactly the same, but then say you don't want "fuzzy" algorithms. I'm not sure those are compatible. In general, though, I think you want to look at [image registration](http://en.wikipedia.org/wiki/Image_registration) algorithms. There's an open source C++ package called [ITK](http://itk...
Have a look at the paper I wrote: <http://werner.yellowcouch.org/Papers/subimg/index.html>. It's highly detailed and appears to be the only article discussing how to apply fourier transformation to the problem of subimage finding. In short, if you want to use the fourier transform one could apply the following formula...
Find known sub image in larger image
[ "", "java", "algorithm", "image-processing", "image-manipulation", "" ]
I have class with internal property: ``` internal virtual StateEnum EnrolmentState { get { ..getter logic } set { ..setter logic } } ``` However I want to be able to access to this property outside of the assembly so I created method that simply returns this property: ``` public StateEnum GetCurrentState()...
Why is the property internal in the first place? If you want to have public access to it, make it public. I assume you have some control over this, as otherwise you wouldn't be able to add a public method to access it in the first place. If you only want selected other assemblies to be able to access it, `InternalsVis...
This sounds like you should reconsider your choice of design. Internal is used to avoid what you are trying to do, so consider using some kind of public access to the properties instead. It's possible to use the InternalsVisibleTo Attribute to make a specific assembly able to reach internal properties but from my poin...
Accessing internal property out of the assembly scope
[ "", "c#", "oop", "language-features", "" ]
There seems to be three common approaches for mapping an application end user to a database user. 1. **One to One Mapping:** Each Application user (bob, nancy and fred) also get a corresponding database user account (bob nancy and fred). 2. **N to M mapping:** Each application user is mapped to a database user that re...
In addition to the simpler administration, there are performance advantages of option 3 on web-servers; this allows pooling of connections - i.e. a low number of physical database connections can be re-used continuously to service a large number of app users. This is known as the "[trusted subsystem](http://msdn.micros...
Re 2), application security/permission needs are usually of a much finer granularity than can be provided by database security layers, unless you put most of your application logic into the database. A simple example is that while two users may need to update the orders table, one may be creating their own order and th...
What are the advantages to each approach for mapping application end users to database users?
[ "", "sql", "database", "oracle", "security", "" ]
I don't understand, why does the following regular expression: ``` ^*$ ``` Match the string "127.0.0.1"? Using `Regex.IsMatch("127.0.0.1", "^*$");` Using Expresso, it does not match, which is also what I would expect. Using the expression `^.*$` does match the string, which I would also expect. Technically, `^*$` s...
Well, theoretically you are right, it should not match. But this depends on how the implementation works internally. Most regex impl. will take your regex and strip ^ from the front (taking note that it must match from start of the string) and strip $ from the end (noting that it must to the end of the string), what is...
Asterisk (\*) matches the preceding element **ZERO OR MORE** times. If you want one or more, use the + operator instead of the \*. You are asking it to match an optional start of string marker and the end of string marker. I.e. if we omit the start of string marker, you're only looking for the end of string marker... ...
Why ^*$ matches "127.0.0.1"
[ "", "c#", "regex", "" ]
I have used extension methods to extend html helpers to make an RSS repeater: ``` public static string RSSRepeater(this HtmlHelper html, IEnumerable<IRSSable> rss) { string result=""; foreach (IRSSable item in rss) { result += "<item>" + item.GetRSSItem().InnerXml + "</item...
Ahh... try: ``` public static string RSSRepeater<T>(this HtmlHelper html, IEnumerable<T> rss) where T : IRSSable { ... } ``` This then should allow you to pass any sequence of things that implement `IRSSable` - and the generic type inference should mean you don't need to specify the `T` (as `Issue`) your...
You're running into [generic variance issues](https://stackoverflow.com/questions/229656). Just because something implements `IEnumerable<Issue>` doesn't mean it implements `IEnumerable<IRssable>`. (It will in C# 4, but I'm assuming you're not using that :) You could make your extension method take just `IEnumerable` ...
Passing interface as a parameter to an extension method
[ "", "c#", "asp.net-mvc", "extension-methods", "interface", "" ]
I want to create a C# program to provision Windows Mobile devices. I have found MSDN documentation on a function called [DMProcessConfigXML](http://msdn.microsoft.com/en-us/library/ms852998.aspx), but no instructions on how to use this function. How can I use this function in my Windows Mobile app? I suspect it has so...
From managed code, you can call ConfigurationManager.ProcessConfiguration found in the Microsoft.WindowsMobile.Configuration namespace. [msdn](http://msdn.microsoft.com/en-us/library/microsoft.windowsmobile.configuration.configurationmanager.processconfiguration.aspx) Here is sample code: ``` XmlDocument configDoc = n...
I looked at the MSDN and indeed very little information is available. I did some google searching and I found this [example](http://cowo.supersized.org/archives/14-Example-usage-of-DMProcessConfigXML-on-WinCE-5.0.html). Also this [blog entry](http://blogs.msdn.com/andrewarnottms/archive/tags/provisioning/default.aspx) ...
How do I use DMProcessConfigXML to provision my Windows Mobile device?
[ "", "c#", ".net", "windows-mobile", "pinvoke", "" ]
I have a table where I'm recording if a user has viewed an object at least once, hence: ``` HasViewed ObjectID number (FK to Object table) UserId number (FK to Users table) ``` Both fields are NOT NULL and together form the Primary Key. My question is, since I don't care how many times someone has vie...
I would normally just insert and trap the DUP\_VAL\_ON\_INDEX exception, as this is the simplest to code. This is more efficient than checking for existence before inserting. I don't consider doing this a "bad smell" (horrible phrase!) because the exception we handle is raised by Oracle - it's not like raising your own...
I don't think there is a downside to your second option. I think it's a perfectly valid use of the named exception, plus it avoids the lookup overhead.
How bad is ignoring Oracle DUP_VAL_ON_INDEX exception?
[ "", "sql", "oracle", "exception", "plsql", "" ]