Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
I'm writing an application and I'm trying to tie simple AJAX functionality in. It works well in Mozilla Firefox, but there's an interesting bug in Internet Explorer: Each of the links can only be clicked once. The browser must be completely restarted, simply reloading the page won't work. I've written a [very simple example application](http://static.stillinbeta.com/page/) that demonstrates this. Javascript reproduced below: ``` var xmlHttp = new XMLHttpRequest(); /* item: the object clicked on type: the type of action to perform (one of 'image','text' or 'blurb' */ function select(item,type) { //Deselect the previously selected 'selected' object if(document.getElementById('selected')!=null) { document.getElementById('selected').id = ''; } //reselect the new selcted object item.id = 'selected'; //get the appropriate page if(type=='image') xmlHttp.open("GET","image.php"); else if (type=='text') xmlHttp.open("GET","textbox.php"); else if(type=='blurb') xmlHttp.open("GET","blurb.php"); xmlHttp.send(null); xmlHttp.onreadystatechange = catchResponse; return false; } function catchResponse() { if(xmlHttp.readyState == 4) { document.getElementById("page").innerHTML=xmlHttp.responseText; } return false; } ``` Any help would be appreciated.
This happens because Internet Explorer ignores the no-cache directive, and caches the results of ajax calls. Then, if the next request is identical, it will just serve up the cached version. There's an easy workaround, and that is to just append random string on the end of your query. ``` xmlHttp.open("GET","blurb.php?"+Math.random(); ```
It looks like IE is caching the response. If you either change your calls to POST methods, or send the appropriate headers to tell IE not to cache the response, it should work. The headers I send to be sure it doesn't cache are: ``` Pragma: no-cache Cache-Control: no-cache Expires: Fri, 30 Oct 1998 14:19:41 GMT ``` Note the expiration date can be any time in the past.
Internet Explorer 7 Ajax links only load once
[ "", "javascript", "ajax", "internet-explorer", "" ]
I just migrated to Windows Ultimate 64 SP1, because my system's hard drive crashed. I installed Visual Studio 2005 SP1 and all the patches that Microsoft has recommended. I finally got my source code from my SCM, but now debugging does not stop on any of my breakpoints I have set. This is just a plain Winforms app, nothing fancy. The first thing I did was to change the build target to x86. No dice. Then I went and downloaded Debugging Tools for x64, still no dice. I set the debugger to break on all exceptions both handled and unhandled. No dice either. I've been looking at Google search results, but no luck there either. I've been at this for 3 days now with no luck. Has anybody dealt with this issue before? **Update:** The projects are all set to Debug (x86). Breakpoints stay normal when the debugging session starts. I already did a re-install, and that didn't work either. I am running as Administrator and turned off UAC. I attached to the project using "Attach to Process", and I was able to step into the code that way. I'm hoping to find out why it is not auto attaching, in order to avoid having to do this manually every time.
This is listed as a [known issue for VS2005 on Vista (Via MSDN):](http://msdn.microsoft.com/en-us/vstudio/aa964140.aspx#question20a) > **Title**: Just-In-Time (JIT) Debugging of > an elevated process will fail > > **Description**: Elevated processes cannot > be JIT Debugged by VS 2005. This > includes system processes, such as > IIS, and applications started by > selecting ‘Run as administrator’. > > **Workaround**: The debugger must be > attached manually before the debugger > will catch unhandled exceptions or > user break points > (System.Diagnostics.Debugger.Break, > \_\_debugbreak, etc).
Couple of questions. When your code fires up, does the breakpoint become an empty circle with a tooltip that indicates that the breakpoint won't be hit? Or does it become a full circle with a tooltip that indicates the process it's attached to? You can try manually attaching the debugger to see if you get any traction that way. Just fire up the app and once it's running, go to the debug menu and choose "Attach to Process" - select the process that your app is running in and click "Attach". I run Vista64 w/o issues - VS2008, though.
VS2005 SP1 breakpoints in Vista Ultimate 64 not working
[ "", "c#", "visual-studio-2005", "vista64", "" ]
Consider the following two ways of writing a loop in Java to see if a list contains a given value: ### Style 1 ``` boolean found = false; for(int i = 0; i < list.length && !found; i++) { if(list[i] == testVal) found = true; } ``` ### Style 2 ``` boolean found = false; for(int i = 0; i < list.length && !found; i++) { found = (list[i] == testVal); } ``` The two are equivalent, but I always use style 1 because 1) I find it more readable, and 2) I am assuming that reassigning `found` to `false` hundreds of times feels like it would take more time. I am wondering: is this second assumption true? ### Nitpicker's corner * I am well aware that this is a case of premature optimization. That doesn't mean that it isn't something that is useful to know. * I don't care which style you think is more readable. I am only interested in whether one has a performance penalty compared to the other. * I know that style 1 has the advantage of allowing you to also put a `break;` statement in the `if` block, but I don't care. Again, this question is about performance, not style.
Well, just write a micro benchmark: ``` import java.util.*; public class Test { private static int[] list = new int[] {1, 2, 3, 4, 5, 6, 7, 8, 9} ; private static int testVal = 6; public static boolean version1() { boolean found = false; for(int i = 0; i < list.length && !found; i++) { if(list[i] == testVal) found = true; } return found; } public static boolean version2() { boolean found = false; for(int i = 0; i < list.length && !found; i++) { found = (list[i] == testVal); } return found; } public static void main(String[] args) { // warm up for (int i=0; i<100000000; i++) { version1(); version2(); } long time = System.currentTimeMillis(); for (int i=0; i<100000000; i++) { version1(); } System.out.println("Version1:" + (System.currentTimeMillis() - time)); time = System.currentTimeMillis(); for (int i=0; i@lt;100000000; i++) { version2(); } System.out.println("Version2:" + (System.currentTimeMillis() - time)); } } ``` On my machine version1 seems to be a little bit faster: Version1:5236 Version2:5477 (But that's 0.2 seconds on a 100 million iterations. I wouldn't care about this.) If you look at the generated bytecode there are two more instructions in version2 which probably cause the longer execution time: ``` public static boolean version1(); Code: 0: iconst_0 1: istore_0 2: iconst_0 3: istore_1 4: iload_1 5: getstatic #2; //Field list:[I 8: arraylength 9: if_icmpge 35 12: iload_0 13: ifne 35 16: getstatic #2; //Field list:[I 19: iload_1 20: iaload 21: getstatic #3; //Field testVal:I 24: if_icmpne 29 27: iconst_1 28: istore_0 29: iinc 1, 1 32: goto 4 35: iload_0 36: ireturn public static boolean version2(); Code: 0: iconst_0 1: istore_0 2: iconst_0 3: istore_1 4: iload_1 5: getstatic #2; //Field list:[I 8: arraylength 9: if_icmpge 39 12: iload_0 13: ifne 39 16: getstatic #2; //Field list:[I 19: iload_1 20: iaload 21: getstatic #3; //Field testVal:I 24: if_icmpne 31 27: iconst_1 28: goto 32 31: iconst_0 32: istore_0 33: iinc 1, 1 36: goto 4 39: iload_0 40: ireturn ```
Comment about nitpicks corner: If you're *really* concerned with absolute performance, putting a break in and removing the "&& !found" will give you theoretically better performance on #1. Two less binary ops to worry about every iteration. If you wanted to get really anal about optimization without using breaks then ``` boolean notFound = true; for(int i = 0; notFound && i < list.length; i++) { if(list[i] == testVal) notFound = false; } ``` will run faster in the average case than the existing option #1. And of course it's personal preference, but I prefer to never put any extra evaluations inside the head of a for loop. I find it can cause confusion while reading code, because it's easy to miss. If I can't get the desired behavior using break/continues I will use a while or do/while loop instead.
Will reassigning a variable in every iteration of a loop affect performance?
[ "", "java", "optimization", "" ]
What is the fastest list implementation (in java) in a scenario where the list will be created one element at a time then at a later point be read one element at a time? The reads will be done with an iterator and then the list will then be destroyed. I know that the Big O notation for get is O(1) and add is O(1) for an ArrayList, while LinkedList is O(n) for get and O(1) for add. Does the iterator behave with the same Big O notation?
It depends largely on whether you know the maximum size of each list up front. If you do, use `ArrayList`; it will certainly be faster. Otherwise, you'll probably have to profile. While access to the `ArrayList` is O(1), creating it is not as simple, because of dynamic resizing. Another point to consider is that the space-time trade-off is not clear cut. Each Java object has quite a bit of overhead. While an `ArrayList` may waste some space on surplus slots, each slot is only 4 bytes (or 8 on a 64-bit JVM). Each element of a `LinkedList` is probably about 50 bytes (perhaps 100 in a 64-bit JVM). So you have to have quite a few wasted slots in an `ArrayList` before a `LinkedList` actually wins its presumed space advantage. Locality of reference is also a factor, and `ArrayList` is preferable there too. In practice, I almost always use `ArrayList`.
**First Thoughts:** * Refactor your code to not need the list. * Simplify the data down to a scalar data type, then use: **int[]** * Or even just use an array of whatever object you have: **Object[]** - John Gardner * Initialize the list to the full size: **new ArrayList(123);** Of course, as everyone else is mentioning, do performance testing, prove your new solution is an improvement.
Which list<Object> implementation will be the fastest for one pass write, read, then destroy?
[ "", "java", "list", "collections", "big-o", "" ]
Has anyone used [Pear: Spreadsheet\_Excel\_Writer](http://pear.php.net/package/Spreadsheet_Excel_Writer/)? The [Formatting Tutorial](http://pear.php.net/manual/en/package.fileformats.spreadsheet-excel-writer.intro-format.php) lists a script similar to what I'm working with: (trimmed down) ``` <?php require_once 'Spreadsheet/Excel/Writer.php'; $workbook = new Spreadsheet_Excel_Writer(); $worksheet =& $workbook->addWorksheet(); $worksheet->write(0, 0, "Quarterly Profits for Dotcom.Com"); $workbook->send('test.xls'); $workbook->close(); ?> ``` What I think I understand so far about it... `$workbook->send('test.xls');` sets the headers up for Excel file transfer. Now, no errors seem to come up, but the file downloaded is entirely empty (even in a hex editor). So... Where (in what class/method) is the `$workbook` binary supposed to be written? Or, am I misunderstanding it all? **Note**: I honestly don't know what version of Spreadsheet\_Excel\_Writer is being used; the sources don't include such useful information. I can tell you the copyright is ***2002-2003***; so, anywhere from version 0.1 to 0.6. [**Edit**] Sorry, thought I'd mentioned this somewhere.. This is someone else's script that I've been assigned to fix.
Here is some sample code: ``` <?php require_once 'Spreadsheet/Excel/Writer.php'; $workbook = new Spreadsheet_Excel_Writer('test.xls'); $worksheet =& $workbook->addWorksheet('My first worksheet'); if (PEAR::isError($worksheet)) { die($worksheet->getMessage()); } $workbook->close(); ?> ``` I think for starters, give your worksheet a name and try to write a file directly (without `send()`). Also, make sure with all methods you call, test the response with `PEAR::isError()`.
It is not very clear, but I think that the send command only creates the headers with the correct content type and file name. You have to send the data afterwards, with something lik ``` $tmpDocument = '/path/to/tmp/file.xls'; $workbook = new Spreadsheet_Excel_Writer($tmpDocument); ``` /\* Code to generate the XLS file \*/ ``` $workbook->close(); $workbook->send('Report.xls'); readfile($tmpDocument); ```
PHP PEAR Spreadsheet_Excel_Writer sending an empty file
[ "", "php", "export-to-excel", "pear", "" ]
Are there any plugins/tools available to go through the classpath of an eclipse project (or workspace) and highlight any unused jars?
[ClassPathHelper](http://classpathhelper.sourceforge.net/) is a good start. It automatically identifies orphan jars and much more. The only limitation is with dependencies that are not defined in classes, e.g. in dependency injection framework configuration files. You also have other options/complements, such as: * [workingfrog "Relief"](http://web.archive.org/web/20120507193800/http://www.workingfrog.org/), which relies on the ability to deal with real objects by examining their shape, size or relative place in space it gives a "physical" view on java packages, types and fields and their relationships, making them easier to handle. * [Unnecessary Code Detector](http://www.ucdetector.org/): a eclipse PlugIn tool to find unnecessary (dead) public java code.
**UCDetector** does not help for this : It does not work on JARs. And for **classpathHelper**, I wan't able to find out an easy way just to list the orphan JARs (BTW, if someone has a tutorial for this, i am interested). So, if you are also using Maven as I do, I find out [this great Maven plugin](http://maven.apache.org/plugins/maven-dependency-plugin/analyze-mojo.html), and I would like to share this solution with you. Just type : ``` mvn dependency:analyze ``` And you will instantly get a list of unused JARs in your dependencies. Very handy !
Finding unused jars used in an eclipse project
[ "", "java", "eclipse", "jar", "" ]
Anyone have a good resource or provide a sample of a natural order sort in C# for an `FileInfo` array? I am implementing the `IComparer` interface in my sorts.
The easiest thing to do is just P/Invoke the built-in function in Windows, and use it as the comparison function in your `IComparer`: ``` [DllImport("shlwapi.dll", CharSet = CharSet.Unicode)] private static extern int StrCmpLogicalW(string psz1, string psz2); ``` Michael Kaplan has some [examples of how this function works here](http://www.siao2.com/2006/10/01/778990.aspx), and the changes that were made for Vista to make it work more intuitively. The plus side of this function is that it will have the same behaviour as the version of Windows it runs on, however this does mean that it differs between versions of Windows so you need to consider whether this is a problem for you. So a complete implementation would be something like: ``` [SuppressUnmanagedCodeSecurity] internal static class SafeNativeMethods { [DllImport("shlwapi.dll", CharSet = CharSet.Unicode)] public static extern int StrCmpLogicalW(string psz1, string psz2); } public sealed class NaturalStringComparer : IComparer<string> { public int Compare(string a, string b) { return SafeNativeMethods.StrCmpLogicalW(a, b); } } public sealed class NaturalFileInfoNameComparer : IComparer<FileInfo> { public int Compare(FileInfo a, FileInfo b) { return SafeNativeMethods.StrCmpLogicalW(a.Name, b.Name); } } ```
Just thought I'd add to this (with the most concise solution I could find): ``` public static IOrderedEnumerable<T> OrderByAlphaNumeric<T>(this IEnumerable<T> source, Func<T, string> selector) { int max = source .SelectMany(i => Regex.Matches(selector(i), @"\d+").Cast<Match>().Select(m => (int?)m.Value.Length)) .Max() ?? 0; return source.OrderBy(i => Regex.Replace(selector(i), @"\d+", m => m.Value.PadLeft(max, '0'))); } ``` The above pads any numbers in the string to the max length of all numbers in all strings and uses the resulting string to sort. The cast to (`int?`) is to allow for collections of strings without any numbers (`.Max()` on an empty enumerable throws an `InvalidOperationException`).
Natural Sort Order in C#
[ "", "c#", "sorting", "file", "natural-sort", "" ]
Does anyone know of a graphing library for simple transformation of a point from one coordinate system to another coordinate system which is rotated by a angle and some point transformation and just for 2d? And any graphing tool for plotting and verifying the same visually?
double[3][3]
The [Angtigrain Geometry](http://www.antigrain.com/) library contains code that can do this, and you can also go farther and use it for drawing as well, but you don't have to. You should look at the agg::trans\_affine class in the agg\_trans\_affine.h file. Dave
C++ library for rotating a point over a given axis?
[ "", "c++", "geometry", "graph", "point", "" ]
Would it be possible to write a class that is virtually indistinguishable from an actual PHP array by implementing all the necessary SPL interfaces? Are they missing anything that would be critical? I'd like to build a more advanced Array object, but I want to make sure I wouldn't break an existing app that uses arrays everywhere if I substituted them with a custom Array class.
The only problems i can think of are the gettype() and the is\_array() functions. Check your code for ``` gettype($FakeArray) == 'array' is_array($FakeArray) ``` Because although you can use the object just like an array, it will still be identified as an object.
In addition to the points made above, you would not be able to make user-space array type hints work with instances of your class. For example: ``` <?php function f(array $a) { /*...*/ } $ao = new ArrayObject(); f($ao); //error ?> ``` Output: ``` Catchable fatal error: Argument 1 passed to f() must be an array, object given ```
PHP's SPL: Do its interfaces involving arrays cover all array properties?
[ "", "php", "arrays", "spl", "" ]
I have a private const int defined in a C# class. I want compilation to fail with an error if the value of this int mod 3 != 0. How can I accomplish this?
Timothy Khouri almost got it. It should be this: ``` int compilerError = 1 / (MY_CONST % 3 == 0 ? 1 : 0); ```
Although there is an [*#error*](http://msdn.microsoft.com/en-us/library/x5hedts0.aspx) pre-processor directive for generating compile-time errors, there is no way for it to be based on the existence of a const value. It only works with compiler symbols, like "DEBUG", for which a value can't be assigned.
Force C# compiler error based on const value
[ "", "c#", "compiler-construction", "" ]
I'm wondering if it is possible to add methods in main program to an existing class defined in header file. For example: There is `class CFun` defined in file `CFun.hpp`, but in our `party.cpp` we want to add a method `void hello() {cout << "hello" << endl;};`without editing `CFun.hpp` Obviously (unfortunately) construction: ``` #include "CFun.hpp" class CFun { public: void hello() {cout << "hello" << endl;}; }; ``` doesn't work returning an error `Multiple declaration for 'CFun'` Is it possible to make it work without class inheritance?
No, but you could add a method that takes a reference/pointer to a CFun class - you just won't have access to private data: ``` void Hello(CFun &fun) { cout << "hello" << endl; } ``` This is probably the best you'll be able to do. As pointed out by litb - this function has to be in the same namespace as CFun. Fortunately, namespaces, unlike classes, can be added to in multiple places.
You can redefine the class like this: ``` #define CFun CLessFun #include "CFun.hpp" #undef CFun class CFun : CLessFun { public: void hello() {cout << "hello" << endl;}; }; ``` Put this in a new header file `CMoreFun.hpp` and include that instead of `CFun.hpp`
c++ adding method to class defined in header file
[ "", "c++", "file", "class", "header", "methods", "" ]
A [similar question discusses `__construct`](https://stackoverflow.com/questions/217618/construct-vs-sameasclassname-for-constructor-in-php), but I left it in my title for people searching who find this one. Apparently, \_\_get and \_\_set take a parameter that is the variable being gotten or set. However, you have to know the variable name (eg, know that the age of the person is $age instead of $myAge). So I don't see the point if you HAVE to know a variable name, especially if you are working with code that you aren't familiar with (such as a library). I found some pages that explain [`__get()`](http://www.hudzilla.org/phpbook/read.php/6_14_2), [`__set()`](http://www.hudzilla.org/phpbook/read.php/6_14_3), and [`__call()`](http://www.hudzilla.org/phpbook/read.php/6_14_4), but I still don't get why or when they are useful.
[This page](http://uk.php.net/manual/en/language.oop5.overloading.php) will probably be useful. (Note that what you say is incorrect - `__set()` takes as a parameter both the name of the variable and the value. `__get()` just takes the name of the variable). `__get()` and `__set()` are useful in library functions where you want to provide generic access to variables. For example in an ActiveRecord class, you might want people to be able to access database fields as object properties. For example, in Kohana PHP framework you might use: ``` $user = ORM::factory('user', 1); $email = $user->email_address; ``` This is accomplished by using `__get()` and `__set()`. Something similar can be accomplished when using `__call()`, i.e. you can detect when someone is calling getProperty() and setProperty() and handle accordingly.
\_\_get(), \_\_set(), and \_\_call() are what PHP calls "magic methods" which is a moniker I think that is a bit silly - I think "hook" is a bit more apt. Anyway, I digress... The purpose of these is to provide execution cases for when datamembers (properties, or methods) that *are not* defined on the object are accessed, which can be used for all sorts of "clever" thinks like variable hiding, message forwarding, etc. There is a cost, however - a call that invokes these is around 10x slower than a call to defined datamembers.
When do/should I use __construct(), __get(), __set(), and __call() in PHP?
[ "", "php", "magic-function", "" ]
I'm using a the TreeView control and it scrolls automatically to left-align TreeViewItem when one of them is clicked. I've gone looking at my Styles and ControlTemplates, but I haven't found anything. Is there a default ControlTemplate that causes this? I want to disable it.
The items scroll because the ScrollViewer calls BringIntoView() on them. So one way to avoid scrolling is to suppress the handling of the RequestBringIntoView event. You can try that out quickly by subclassing TreeView and instantiating this control instead: ``` public class NoScrollTreeView : TreeView { public class NoScrollTreeViewItem : TreeViewItem { public NoScrollTreeViewItem() : base() { this.RequestBringIntoView += delegate (object sender, RequestBringIntoViewEventArgs e) { e.Handled = true; }; } protected override DependencyObject GetContainerForItemOverride() { return new NoScrollTreeViewItem(); } } protected override DependencyObject GetContainerForItemOverride() { return new NoScrollTreeViewItem(); } } ```
after spending some hours on this problem i found a solution that works for me. brians solution to prevent the RequestBringIntoView event on a TreeViewItem from bubbling was the first step. unfortunately this also stops a treeviewitem to be shown if you change the selected item programmatically by ``` yourtreeview.SelectedItem = yourtreeviewitem ``` so, for me the solution is to modify the controltemplate of the treeview as follows: ``` <Style x:Key="{x:Type TreeView}" TargetType="TreeView"> <Setter Property="OverridesDefaultStyle" Value="True" /> <Setter Property="SnapsToDevicePixels" Value="True" /> <Setter Property="ScrollViewer.HorizontalScrollBarVisibility" Value="Auto"/> <Setter Property="ScrollViewer.VerticalScrollBarVisibility" Value="Auto"/> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="TreeView"> <Border Name="Border" BorderThickness="0" Padding="0" Margin="1"> <ScrollViewer Focusable="False" CanContentScroll="False" Padding="0"> <Components:AutoScrollPreventer Margin="0"> <ItemsPresenter/> </Components:AutoScrollPreventer> </ScrollViewer> </Border> </ControlTemplate> </Setter.Value> </Setter> </Style> ``` the "autoscrollpreventer" is: ``` using System; using System.Windows; using System.Windows.Controls; namespace LiveContext.Designer.GUI.Components { public class AutoScrollPreventer : StackPanel { public AutoScrollPreventer() { this.RequestBringIntoView += delegate(object sender, RequestBringIntoViewEventArgs e) { // stop this event from bubbling so that a scrollviewer doesn't try to BringIntoView.. e.Handled = true; }; } } ``` } hope it helps..
WPF ControlTemplate for scrolling TreeView Control
[ "", "c#", "wpf", "" ]
I'm looking for a library that has functionality similar to Perl's [WWW::Mechanize](http://search.cpan.org/dist/WWW-Mechanize/lib/WWW/Mechanize.pm#SYNOPSIS), but for PHP. Basically, it should allow me to submit HTTP GET and POST requests with a simple syntax, and then parse the resulting page and return in a simple format all forms and their fields, along with all links on the page. I know about CURL, but it's a little too barebones, and the syntax is pretty ugly (tons of `curl_foo($curl_handle, ...)` statements **Clarification:** I want something more high-level than the answers so far. For example, in Perl, you could do something like: ``` # navigate to the main page $mech->get( 'http://www.somesite.com/' ); # follow a link that contains the text 'download this' $mech->follow_link( text_regex => qr/download this/i ); # submit a POST form, to log into the site $mech->submit_form( with_fields => { username => 'mungo', password => 'lost-and-alone', } ); # save the results as a file $mech->save_content('somefile.zip'); ``` To do the same thing using HTTP\_Client or wget or CURL would be a lot of work, I'd have to manually parse the pages to find the links, find the form URL, extract all the hidden fields, and so on. The reason I'm asking for a PHP solution is that I have no experience with Perl, and I could probably build what I need with a lot of work, but it would be much quicker if I could do the above in PHP.
SimpleTest's [ScriptableBrowser](http://simpletest.sourceforge.net/en/browser_documentation.html) can be used independendly from the testing framework. I've used it for numerous automation-jobs.
I feel compelled to answer this, even though its an old post... I've been working with PHP curl a lot and it is not as good anywhere near comparable to something like WWW:Mechanize, which I am switching to (I think I am going to go with the Ruby language implementation).. Curl is outdated as it requires too much "grunt work" to automate anything, the simpletest scriptable browser looked promising to me but in testing it, it won't work on most web forms I try it on... honestly, I think PHP is lacking in this category of scraping, web automation so its best to look at a different language, just wanted to post this since I have spent countless hours on this topic and maybe it will save someone else some time in the future.
Is there a PHP equivalent of Perl's WWW::Mechanize?
[ "", "php", "automation", "screen-scraping", "mechanize", "www-mechanize", "" ]
Is it possible in .NET to ascertain whether my application is closing due to Windows being given a shutdown command (as opposed to any old application closing) in order to either write out some temporary cache files or even block the shutdown long enough to prompt for user input? Whilst my current scope involves a Winform app and a windows service, I am interested in understanding this in a generic way if possible
[SystemEvents.SessionEnding](http://msdn.microsoft.com/en-us/library/microsoft.win32.systemevents.sessionending.aspx) looks like a good starting point for you. That article talks about the event sequence involved when a logout/shutdown is occurring.
In general, you will want to handle the [`WM_QUERYENDSESSION`](http://msdn.microsoft.com/en-us/library/aa376890(VS.85).aspx) Windows message. This will give your application a chance to do cleanup, or to block the shutdown if it's really necessary.
Ascertaining a shutdown is closing my application
[ "", "c#", ".net", "shutdown", "" ]
I want to do a select in MySql that combines several columns... something like this pseudocode: ``` SELECT payment1_paid AND payment2_paid AS paid_in_full FROM denormalized_payments WHERE payment1_type = 'check'; ``` **Edit**: payment1\_paid and payment2\_paid are booleans. I can't use any other language for this particular problem than MySql. Thanks for any help! **Edit**: Sorry to everybody who gave me suggestions for summing and concatenating, but I've voted those early answers up because they're useful anyway. And **thanks** to everybody for your incredibly quick answers!
Ok, for logical and you can do ``` Select (payment1_paid && payment2_paid) as paid_in_full from denormalized_payments where payment1_type = 'check'; ``` As seen [here](http://dev.mysql.com/doc/refman/5.0/en/logical-operators.html#operator_and).
Just do ``` Select CONCAT(payment1_paid, payment2_paid) as paid_in_full from denormalized_payments where payment1_type = 'check'; ``` You can concat any number of field you want.
How can I do boolean logic on two columns in MySQL?
[ "", "sql", "mysql", "select", "boolean", "" ]
I have a strange issue: I am using SPContext.Current.Web in a .aspx page, but at the end, I get a "Trying to use an SPWeb object that has been closed or disposed and is no longer valid." error message. From what I see, SPContext.Current.Web is Disposed by someone, **but I have no idea where**. I just wonder: With Visual Studio 2005's Debugger, can I somehow see where/who disposed an Object? As I neither create nor have the source code, setting breakpoints is a problem. What would be a good approach for finding out who disposes a given object where, without just randomly commenting out lines? (Note: The Issue has been resolve, but the question itself also applies outside of Sharepoint)
Check if this helps: 1. Add a new breakpoint using **Debug > New Breakpoint > Break at Function... (Ctrl+B)**. 2. Enter **Microsoft.SharePoint.SPWeb.Dispose** in the Function edit box. 3. Dismiss the dialog box that says that Intellisense could not find the specified location. 4. Run under the debugger. 5. When the breakpoint is hit you can see on the call stack who called the Dispose method. Hopefully for some of the times the breakpoint is hit one stack frame is in your source code. If a dialog appears saying that *There is no source code available for the current location* when the breakpoint is hit dismiss it. --- **Note:** Because I do not have SharePoint installed I have tested this with `System.IO.StreamReader.Dispose` but I am guessing that this should also work for SPContext.Current.Web. Drop a note on this.
In your custom code make sure you didn't get a reference to the actual SPWeb object of the Context object and dispose of it. For example, the following is very bad. ``` using (SPWeb myWeb = SPContext.Current.Web) { // do something } ``` This will cause the SPContext's object to be disposed and may not cause an issue in your code, but will likely cause issues later.
Where is my Object being disposed?
[ "", "c#", ".net", "sharepoint", "" ]
I have headers in `<h1>` through `<h6>` tags. Is there a way that I can use JavaScript to generate a table of contents for the contents that serves as anchor tags as well? I would like the output to be something like: ``` <ol> <li>Header 1</li> <li>Header 1</li> <li>Header 2</li> <li>Header 3</li> </ol> ``` I am not currently using a JavaScript framework, but I don't see why I couldn't use one. I am also looking for something done, since I'm guessing this is a common problem, but if not, a starting point to roll my own would be good.
I couldn't resist putting together a quick implementation. Add the following script anywhere on your page: ``` window.onload = function () { var toc = ""; var level = 0; document.getElementById("contents").innerHTML = document.getElementById("contents").innerHTML.replace( /<h([\d])>([^<]+)<\/h([\d])>/gi, function (str, openLevel, titleText, closeLevel) { if (openLevel != closeLevel) { return str; } if (openLevel > level) { toc += (new Array(openLevel - level + 1)).join("<ul>"); } else if (openLevel < level) { toc += (new Array(level - openLevel + 1)).join("</ul>"); } level = parseInt(openLevel); var anchor = titleText.replace(/ /g, "_"); toc += "<li><a href=\"#" + anchor + "\">" + titleText + "</a></li>"; return "<h" + openLevel + "><a name=\"" + anchor + "\">" + titleText + "</a></h" + closeLevel + ">"; } ); if (level) { toc += (new Array(level + 1)).join("</ul>"); } document.getElementById("toc").innerHTML += toc; }; ``` Your page should be structured something like this: ``` <body> <div id="toc"> <h3>Table of Contents</h3> </div> <hr/> <div id="contents"> <h1>Fruits</h1> <h2>Red Fruits</h2> <h3>Apple</h3> <h3>Raspberry</h3> <h2>Orange Fruits</h2> <h3>Orange</h3> <h3>Tangerine</h3> <h1>Vegetables</h1> <h2>Vegetables Which Are Actually Fruits</h2> <h3>Tomato</h3> <h3>Eggplant</h3> </div> </body> ``` You can see it in action at <https://codepen.io/scheinercc/pen/KEowRK> (old link: <http://magnetiq.com/exports/toc.htm> (Works in IE, FF, Safari, Opera))
Here's a great script to do this: <https://github.com/matthewkastor/html-table-of-contents/wiki> To use it: 1. Add this tag: ``` <script src="./node_modules/html-table-of-contents/src/html-table-of-contents.js" type="text/javascript"> ``` 2. Call the function, such as in your body's onload attribute: ``` <body onload="htmlTableOfContents();"> ``` Here is the definition of the method that does the generation: ``` /** * Generates a table of contents for your document based on the headings * present. Anchors are injected into the document and the * entries in the table of contents are linked to them. The table of * contents will be generated inside of the first element with the id `toc`. * @param {HTMLDOMDocument} documentRef Optional A reference to the document * object. Defaults to `document`. * @author Matthew Christopher Kastor-Inare III * @version 20130726 * @example * // call this after the page has loaded * htmlTableOfContents(); */ function htmlTableOfContents (documentRef) { var documentRef = documentRef || document; var toc = documentRef.getElementById('toc'); var headings = [].slice.call(documentRef.body.querySelectorAll('h1, h2, h3, h4, h5, h6')); headings.forEach(function (heading, index) { var anchor = documentRef.createElement('a'); anchor.setAttribute('name', 'toc' + index); anchor.setAttribute('id', 'toc' + index); var link = documentRef.createElement('a'); link.setAttribute('href', '#toc' + index); link.textContent = heading.textContent; var div = documentRef.createElement('div'); div.setAttribute('class', heading.tagName.toLowerCase()); div.appendChild(link); toc.appendChild(div); heading.parentNode.insertBefore(anchor, heading); }); } try { module.exports = htmlTableOfContents; } catch (e) { // module.exports is not defined } ```
Is there a JavaScript solution to generating a "table of contents" for a page?
[ "", "javascript", "tableofcontents", "html-heading", "" ]
I am aware of how to setup autocompletion of python objects in the python interpreter (on unix). * Google shows many hits for explanations on how to do this. * Unfortunately, there are so many references to that it is difficult to find what I need to do, which is slightly different. I need to know how to enable, tab/auto completion of arbitrary items in a command-line program written in python. My specific use case is a command-line python program that needs to send emails. I want to be able to autocomplete email addresses (I have the addresses on disk) when the user types part of it (and optionally presses the TAB key). I do not need it to work on windows or mac, just linux.
Use Python's `readline` bindings. For example, ``` import readline def completer(text, state): options = [i for i in commands if i.startswith(text)] if state < len(options): return options[state] else: return None readline.parse_and_bind("tab: complete") readline.set_completer(completer) ``` The [official module docs](https://docs.python.org/3/library/readline.html) aren't much more detailed, see [the readline docs](http://tiswww.case.edu/php/chet/readline/readline.html#SEC44) for more info.
Follow the [cmd documentation](http://docs.python.org/library/cmd.html#cmd.Cmd.cmdloop) and you'll be fine ``` import cmd addresses = [ 'here@blubb.com', 'foo@bar.com', 'whatever@wherever.org', ] class MyCmd(cmd.Cmd): def do_send(self, line): pass def complete_send(self, text, line, start_index, end_index): if text: return [ address for address in addresses if address.startswith(text) ] else: return addresses if __name__ == '__main__': my_cmd = MyCmd() my_cmd.cmdloop() ``` Output for tab -> tab -> send -> tab -> tab -> f -> tab ``` (Cmd) help send (Cmd) send foo@bar.com here@blubb.com whatever@wherever.org (Cmd) send foo@bar.com (Cmd) ```
How to make a python, command-line program autocomplete arbitrary things NOT interpreter
[ "", "python", "linux", "unix", "command-line", "autocomplete", "" ]
I'm building an open source project that uses python and c++ in Windows. I came to the following error message: ``` ImportError: No module named win32con ``` The same happened in a "prebuilt" code that it's working ( except in my computer :P ) I think this is kind of "popular" module in python because I've saw several messages in other forums but none that could help me. I have Python2.6, should I have that module already installed? Is that something of VC++? Thank you for the help. I got this url <http://sourceforge.net/projects/pywin32/> but I'm not sure what to do with the executable :S
This module contains constants related to Win32 programming. It is not part of the Python 2.6 release, but should be part of the download of the pywin32 project. **Edit:** I imagine that the executable is an installation program, though the last time I downloaded pywin32 it was just a zip file.
``` pip install pypiwin32 ``` [Glyph](https://glyph.twistedmatrix.com) had packed packed it until somebody sends patch to build wheels as part of `pywin32` build process to close <https://sourceforge.net/p/pywin32/bugs/680/>
What's win32con module in python? Where can I find it?
[ "", "python", "module", "" ]
I am creating a small web page using PHP that will be accessed as an IFRAME from a couple of sites. I'm wanting to restrict access to this site to work ONLY within the "approved" sites, and not other sites or accessed directly. Does anyone have any suggestions? Is this even possible? The PHP site will be Apache, and the sites iframing the content will probably be .NET. Just to clarify, any site can view the page, as long as it's iframe'd within an approved site. I want to block people from accessing it directly. I'm thinking cookies might be a solution, but I'm not sure.
Thanks for all the great ideas! I think the solution I'm going to go with is a session cookie set by the approved "iframing" site. Someone really determined will still be able to get the content, but I think I can prevent most of the abuse by coming up with a decent "secret" algorithm based on some sort of shared secret on both sides, and have the approved site set a session cookie that will be read by my PHP site. If the cookie is valid and meets my criteria, I'll display the contents, otherwise I won't. The information I'm protecting isn't mission-critical, I'm just trying to prevent it from being abused.
Thinking about this... I'm not convinced this is completely secure, but here's a shot while I think about it more - The only way you could do this, is if you control the sites it would be embedded in. If you control them, you could pass the time, encrypted, from the frameset to the frame: > ``` > <iframe src="http://yourdomain/frame.php?key=p21n9u234p8yfb8yfy234m3lunflb8hv" /> > ``` frame.php then decrypts the message to find the time within a small delta (say 10 seconds). Because frame.php knows only acceptable sites could have encrypted the time, it knows it's okay to display itself. Otherwise, it outputs nothing. Anything else, whether it's javascript or HTTP\_REFER, can be spoofed, turned off, or circumvented. And in fact, with that url, an attacker will be able to show your frame anywhere, as long as the user loads it within 10 seconds. So the attacker would just scrape the accepted site, and grab the key. If that threat model is unacceptable to you - then there really is nothing you can do (except maybe an even more complicated protocol).
Restricting IFRAME access in PHP
[ "", "php", "security", "iframe", "" ]
I have a class with a nullable int? datatype set to serialize as an xml element. Is there any way to set it up so the xml serializer will not serialize the element if the value is null? I've tried to add the `[System.Xml.Serialization.XmlElement(IsNullable=false)]` attribute, but I get a runtime serialization exception saying there was a an error reflecting the type, because "IsNullable may not be set to 'false' for a Nullable<System.Int32> type. Consider using 'System.Int32' type or removing the IsNullable property from the XmlElement attribute." ``` [Serializable] [System.Xml.Serialization.XmlRoot("Score", Namespace = "http://mycomp.com/test/score/v1")] public class Score { private int? iID_m; ... /// <summary> /// /// </summary> public int? ID { get { return iID_m; } set { iID_m = value; } } ... } ``` The above class will serialize to: ``` <Score xmlns="http://mycomp.com/test/score/v1"> <ID xsi:nil="true" /> </Score> ``` But for IDs that are null I don't want the ID element at all, primarily because when I use OPENXML in MSSQL, it returns a 0 instead of null for an element that looks like
XmlSerializer supports the `ShouldSerialize{Foo}()` pattern, so you can add a method: ``` public bool ShouldSerializeID() {return ID.HasValue;} ``` There is also the `{Foo}Specified` pattern - not sure if XmlSerializer supports that one.
I'm using this micro-pattern to implement Nullable serialization: ``` [XmlIgnore] public double? SomeValue { get; set; } [XmlAttribute("SomeValue")] // or [XmlElement("SomeValue")] [EditorBrowsable(EditorBrowsableState.Never)] public double XmlSomeValue { get { return SomeValue.Value; } set { SomeValue= value; } } [EditorBrowsable(EditorBrowsableState.Never)] public bool XmlSomeValueSpecified { get { return SomeValue.HasValue; } } ``` This provides the right interface to the user without compromise and still does the right thing when serializing.
How to serialize a nullable int without "xsi:nil" being added to the resulting XML?
[ "", "c#", ".net", "xml", "serialization", "" ]
I just came onto a project with a pretty huge code base. I'm mostly dealing with C++ and a lot of the code they write uses double negation for their boolean logic. ``` if (!!variable && (!!api.lookup("some-string"))) { do_some_stuff(); } ``` I know these guys are intelligent programmers, it's obvious they aren't doing this by accident. I'm no seasoned C++ expert, my only guess at why they are doing this is that they want to make absolutely positive that the value being evaluated is the actual boolean representation. So they negate it, then negate that again to get it back to its actual boolean value. Is this correct, or am I missing something?
It's a trick to convert to bool.
It's actually a very useful idiom in some contexts. Take these macros (example from the Linux kernel). For GCC, they're implemented as follows: ``` #define likely(cond) (__builtin_expect(!!(cond), 1)) #define unlikely(cond) (__builtin_expect(!!(cond), 0)) ``` Why do they have to do this? GCC's `__builtin_expect` treats its parameters as `long` and not `bool`, so there needs to be some form of conversion. Since they don't know what `cond` is when they're writing those macros, it is most general to simply use the `!!` idiom. They could probably do the same thing by comparing against 0, but in my opinion, it's actually more straightforward to do the double-negation, since that's the closest to a cast-to-bool that C has. This code can be used in C++ as well... it's a lowest-common-denominator thing. If possible, do what works in both C and C++.
Double Negation in C++
[ "", "c++", "boolean", "" ]
Suppose I have the following two strings containing regular expressions. How do I coalesce them? More specifically, I want to have the two expressions as alternatives. ``` $a = '# /[a-z] #i'; $b = '/ Moo /x'; $c = preg_magic_coalesce('|', $a, $b); // Desired result should be equivalent to: // '/ \/[a-zA-Z] |Moo/' ``` Of course, doing this as string operations isn't practical because it would involve parsing the expressions, constructing syntax trees, coalescing the trees and then outputting another regular expression equivalent to the tree. I'm completely happy without this last step. Unfortunately, PHP doesn't have a RegExp class (or does it?). Is there *any* way to achieve this? Incidentally, does any other language offer a way? Isn't this a pretty normal scenario? Guess not. :-( **Alternatively**, is there a way to check **efficiently** if either of the two expressions matches, and which one matches earlier (and if they match at the same position, which match is longer)? This is what I'm doing at the moment. Unfortunately, I do this on long strings, very often, for more than two patterns. The result is *slow* (and yes, this is definitely the bottleneck). ## EDIT: I should have been more specific – sorry. `$a` and `$b` are *variables*, their content is outside of my control! Otherwise, I would just coalesce them manually. Therefore, I can't make any assumptions about the delimiters or regex modifiers used. Notice, for example, that my first expression uses the `i` modifier (ignore casing) while the second uses `x` (extended syntax). Therefore, I can't just concatenate the two because the second expression does *not* ignore casing and the first doesn't use the extended syntax (and any whitespace therein is significant!
I see that porneL actually [described](https://stackoverflow.com/questions/244959/coalescing-regular-expressions-in-php#245326) a bunch of this, but this handles most of the problem. It cancels modifiers set in previous sub-expressions (which the other answer missed) and sets modifiers as specified in each sub-expression. It also handles non-slash delimiters (I could not find a specification of what characters are **allowed** here so I used `.`, you may want to narrow further). One weakness is it doesn't handle back-references within expressions. My biggest concern with that is the limitations of back-references themselves. I'll leave that as an exercise to the reader/questioner. ``` // Pass as many expressions as you'd like function preg_magic_coalesce() { $active_modifiers = array(); $expression = '/(?:'; $sub_expressions = array(); foreach(func_get_args() as $arg) { // Determine modifiers from sub-expression if(preg_match('/^(.)(.*)\1([eimsuxADJSUX]+)$/', $arg, $matches)) { $modifiers = preg_split('//', $matches[3]); if($modifiers[0] == '') { array_shift($modifiers); } if($modifiers[(count($modifiers) - 1)] == '') { array_pop($modifiers); } $cancel_modifiers = $active_modifiers; foreach($cancel_modifiers as $key => $modifier) { if(in_array($modifier, $modifiers)) { unset($cancel_modifiers[$key]); } } $active_modifiers = $modifiers; } elseif(preg_match('/(.)(.*)\1$/', $arg)) { $cancel_modifiers = $active_modifiers; $active_modifiers = array(); } // If expression has modifiers, include them in sub-expression $sub_modifier = '(?'; $sub_modifier .= implode('', $active_modifiers); // Cancel modifiers from preceding sub-expression if(count($cancel_modifiers) > 0) { $sub_modifier .= '-' . implode('-', $cancel_modifiers); } $sub_modifier .= ')'; $sub_expression = preg_replace('/^(.)(.*)\1[eimsuxADJSUX]*$/', $sub_modifier . '$2', $arg); // Properly escape slashes $sub_expression = preg_replace('/(?<!\\\)\//', '\\\/', $sub_expression); $sub_expressions[] = $sub_expression; } // Join expressions $expression .= implode('|', $sub_expressions); $expression .= ')/'; return $expression; } ``` Edit: I've rewritten this (because I'm OCD) and ended up with: ``` function preg_magic_coalesce($expressions = array(), $global_modifier = '') { if(!preg_match('/^((?:-?[eimsuxADJSUX])+)$/', $global_modifier)) { $global_modifier = ''; } $expression = '/(?:'; $sub_expressions = array(); foreach($expressions as $sub_expression) { $active_modifiers = array(); // Determine modifiers from sub-expression if(preg_match('/^(.)(.*)\1((?:-?[eimsuxADJSUX])+)$/', $sub_expression, $matches)) { $active_modifiers = preg_split('/(-?[eimsuxADJSUX])/', $matches[3], -1, PREG_SPLIT_NO_EMPTY|PREG_SPLIT_DELIM_CAPTURE); } // If expression has modifiers, include them in sub-expression if(count($active_modifiers) > 0) { $replacement = '(?'; $replacement .= implode('', $active_modifiers); $replacement .= ':$2)'; } else { $replacement = '$2'; } $sub_expression = preg_replace('/^(.)(.*)\1(?:(?:-?[eimsuxADJSUX])*)$/', $replacement, $sub_expression); // Properly escape slashes if another delimiter was used $sub_expression = preg_replace('/(?<!\\\)\//', '\\\/', $sub_expression); $sub_expressions[] = $sub_expression; } // Join expressions $expression .= implode('|', $sub_expressions); $expression .= ')/' . $global_modifier; return $expression; } ``` It now uses `(?modifiers:sub-expression)` rather than `(?modifiers)sub-expression|(?cancel-modifiers)sub-expression` but I've noticed that both have some weird modifier side-effects. For instance, in both cases if a sub-expression has a `/u` modifier, it will fail to match (but if you pass `'u'` as the second argument of the new function, that will match just fine).
## EDIT **I’ve rewritten the code!** It now contains the changes that are listed as follows. Additionally, I've done extensive tests (which I won’t post here because they’re too many) to look for errors. So far, I haven’t found any. * The function is now split into two parts: There’s a separate function `preg_split` which takes a regular expression and returns an array containing the bare expression (without delimiters) and an array of modifiers. This might come in handy (it already has, in fact; this is why I made this change). * **The code now correctly handles back-references.** This was necessary for my purpose after all. It wasn’t difficult to add, the regular expression used to capture the back-references just looks weird (and may actually be extremely inefficient, it looks NP-hard to me – but that’s only an intuition and only applies in weird edge cases). By the way, does anyone know a better way of checking for an uneven number of matches than my way? Negative lookbehinds won't work here because they only accept fixed-length strings instead of regular expressions. However, I need the regex here to test whether the preceeding backslash is actually escaped itself. Additionally, I don’t know how good PHP is at caching anonymous `create_function` use. Performance-wise, this might not be the best solution but it seems good enough. * I’ve fixed a bug in the sanity check. * I’ve removed the cancellation of obsolete modifiers since my tests show that it isn't necessary. By the way, this code is one of the core components of a syntax highlighter for various languages that I’m working on in PHP since I’m not satisfied with the alternatives listed [elsewhere](https://stackoverflow.com/questions/230270/php-syntax-highlighting). ## Thanks! **porneL**, **eyelidlessness**, amazing work! Many, many thanks. I had actually given up. I've built upon your solution and I'd like to share it here. ~~I didn't implement re-numbering back-references since this isn't relevant in my case (I think …). Perhaps this will become necessary later, though.~~ ## Some Questions … One thing, *@eyelidlessness*: ~~Why do you feel the necessity to cancel old modifiers? As far as I see it, this isn't necessary since the modifiers are only applied locally anyway. Ah yes, one other thing. Your escaping of the delimiter seems overly complicated. Care to explain why you think this is needed? I believe my version should work as well but I could be very wrong.~~ Also, I've changed the signature of your function to match my needs. I also thing that my version is more generally useful. Again, I might be wrong. BTW, you should now realize the importance of real names on SO. ;-) I can't give you real credit in the code. :-/ ## The Code Anyway, I'd like to share my result so far because I can't believe that nobody else ever needs something like that. The code *seems* to work very well. ~~Extensive tests are yet to be done, though.~~ **Please comment!** And without further ado … ``` /** * Merges several regular expressions into one, using the indicated 'glue'. * * This function takes care of individual modifiers so it's safe to use * <em>different</em> modifiers on the individual expressions. The order of * sub-matches is preserved as well. Numbered back-references are adapted to * the new overall sub-match count. This means that it's safe to use numbered * back-refences in the individual expressions! * If {@link $names} is given, the individual expressions are captured in * named sub-matches using the contents of that array as names. * Matching pair-delimiters (e.g. <code>"{…}"</code>) are currently * <strong>not</strong> supported. * * The function assumes that all regular expressions are well-formed. * Behaviour is undefined if they aren't. * * This function was created after a {@link https://stackoverflow.com/questions/244959/ * StackOverflow discussion}. Much of it was written or thought of by * “porneL” and “eyelidlessness”. Many thanks to both of them. * * @param string $glue A string to insert between the individual expressions. * This should usually be either the empty string, indicating * concatenation, or the pipe (<code>|</code>), indicating alternation. * Notice that this string might have to be escaped since it is treated * like a normal character in a regular expression (i.e. <code>/</code>) * will end the expression and result in an invalid output. * @param array $expressions The expressions to merge. The expressions may * have arbitrary different delimiters and modifiers. * @param array $names Optional. This is either an empty array or an array of * strings of the same length as {@link $expressions}. In that case, * the strings of this array are used to create named sub-matches for the * expressions. * @return string An string representing a regular expression equivalent to the * merged expressions. Returns <code>FALSE</code> if an error occurred. */ function preg_merge($glue, array $expressions, array $names = array()) { // … then, a miracle occurs. // Sanity check … $use_names = ($names !== null and count($names) !== 0); if ( $use_names and count($names) !== count($expressions) or !is_string($glue) ) return false; $result = array(); // For keeping track of the names for sub-matches. $names_count = 0; // For keeping track of *all* captures to re-adjust backreferences. $capture_count = 0; foreach ($expressions as $expression) { if ($use_names) $name = str_replace(' ', '_', $names[$names_count++]); // Get delimiters and modifiers: $stripped = preg_strip($expression); if ($stripped === false) return false; list($sub_expr, $modifiers) = $stripped; // Re-adjust backreferences: // We assume that the expression is correct and therefore don't check // for matching parentheses. $number_of_captures = preg_match_all('/\([^?]|\(\?[^:]/', $sub_expr, $_); if ($number_of_captures === false) return false; if ($number_of_captures > 0) { // NB: This looks NP-hard. Consider replacing. $backref_expr = '/ ( # Only match when not escaped: [^\\\\] # guarantee an even number of backslashes (\\\\*?)\\2 # (twice n, preceded by something else). ) \\\\ (\d) # Backslash followed by a digit. /x'; $sub_expr = preg_replace_callback( $backref_expr, create_function( '$m', 'return $m[1] . "\\\\" . ((int)$m[3] + ' . $capture_count . ');' ), $sub_expr ); $capture_count += $number_of_captures; } // Last, construct the new sub-match: $modifiers = implode('', $modifiers); $sub_modifiers = "(?$modifiers)"; if ($sub_modifiers === '(?)') $sub_modifiers = ''; $sub_name = $use_names ? "?<$name>" : '?:'; $new_expr = "($sub_name$sub_modifiers$sub_expr)"; $result[] = $new_expr; } return '/' . implode($glue, $result) . '/'; } /** * Strips a regular expression string off its delimiters and modifiers. * Additionally, normalize the delimiters (i.e. reformat the pattern so that * it could have used '/' as delimiter). * * @param string $expression The regular expression string to strip. * @return array An array whose first entry is the expression itself, the * second an array of delimiters. If the argument is not a valid regular * expression, returns <code>FALSE</code>. * */ function preg_strip($expression) { if (preg_match('/^(.)(.*)\\1([imsxeADSUXJu]*)$/s', $expression, $matches) !== 1) return false; $delim = $matches[1]; $sub_expr = $matches[2]; if ($delim !== '/') { // Replace occurrences by the escaped delimiter by its unescaped // version and escape new delimiter. $sub_expr = str_replace("\\$delim", $delim, $sub_expr); $sub_expr = str_replace('/', '\\/', $sub_expr); } $modifiers = $matches[3] === '' ? array() : str_split(trim($matches[3])); return array($sub_expr, $modifiers); } ``` PS: I've made this posting community wiki editable. You know what this means …!
Coalescing regular expressions in PHP
[ "", "php", "regex", "abstract-syntax-tree", "" ]
Windbg fans claim that it is quite powerful and I tend to agree. But when it comes to debugging STL containers, I am always stuck. If the variable is on the stack, the `!stl` extension sometimes figures it out, but when a container with a complex type (e.g. `std::vector<TemplateField, std::allocator<TemplateField> >`) is on the heap or part of some other structure, I just don't know how to view its contents. Appreciate any tips, pointers.
You might also want to give this [debugger extension](http://www.nynaeve.net/?p=7) a try. It is a library called SDbgExt, developed by [Skywing](http://www.nynaeve.net).
I often find debugger support for STL data types inadequate. For this reason I'm increasingly using [logging frameworks and logging statements](http://www.spinellis.gr/blog/20060501/). I used to think that these are for people who can't use a debugger, but I now realize that they offer real value. They allow you to embed portable debugging knowledge in your code and maintain it together with the code. In contrast, work you do in the debugger is typically ephemeral.
Debugging C++ STL containers in Windbg
[ "", "c++", "stl", "windbg", "" ]
In .NET, Windows Forms have an event that fires before the Form is loaded (Form.Load), but there is no corresponding event that is fired AFTER the form has loaded. I would like to execute some logic after the form has loaded. Can anyone advise on a solution?
You could use the "Shown" event: [MSDN - Form.Shown](http://msdn.microsoft.com/en-us/library/system.windows.forms.form.shown.aspx) "The Shown event is only raised the first time a form is displayed; subsequently minimizing, maximizing, restoring, hiding, showing, or invalidating and repainting will not raise this event."
I sometimes use (in Load) ``` this.BeginInvoke((MethodInvoker) delegate { // some code }); ``` or ``` this.BeginInvoke((MethodInvoker) this.SomeMethod); ``` (change "this" to your form variable if you are handling the event on an instance other than "this"). This pushes the invoke onto the windows-forms loop, so it gets processed when the form is processing the message queue. [updated on request] The Control.Invoke/Control.BeginInvoke methods are intended for use with threading, and are a mechanism to push work onto the UI thread. Normally this is used by worker threads etc. Control.Invoke does a synchronous call, where-as Control.BeginInvoke does an asynchronous call. Normally, these would be used as: ``` SomeCodeOrEventHandlerOnAWorkerThread() { // this code running on a worker thread... string newText = ExpensiveMethod(); // perhaps a DB/web call // now ask the UI thread to update itself this.Invoke((MethodInvoker) delegate { // this code runs on the UI thread! this.Text = newText; }); } ``` It does this by pushing a message onto the windows message queue; the UI thread (at some point) de-queues the message, processes the delegate, and signals the worker that it completed... so far so good ;-p OK; so what happens if we use Control.Invoke / Control.BeginInvoke on the UI thread? It copes... if you call Control.Invoke, it is sensible enough to know that blocking on the message queue would cause an immediate deadlock - so if you are already on the UI thread it simply runs the code immediately... so that doesn't help us... But Control.BeginInvoke works differently: it *always* pushes work onto the queue, even it we are already on the UI thread. This makes a really simply way of saying "in a moment", but without the inconvenience of timers etc (which would still have to do the same thing anyway!).
How do I execute code AFTER a form has loaded?
[ "", "c#", ".net", "winforms", "events", "" ]
I have a `GridView` control in an Asp.net application, that has a `<asp:buttonField>` of `type="image"` and `CommandName="Delete"`. Is there any way to execute a piece of javascript before reaching the `OnRowDelete` event? I want just a simple confirm before deleting the row. Thanks! **EDIT**: Please Note that `<asp:ButtonField>` tag **does not have** an `OnClientClick` attribute.
I would use a TemplateField instead, and populate the ItemTemplate with a regular asp:Button or asp:ImageButton, depending one what is needed. You can then execute the same logic that the RowCommand event was going to do when it intercepted the Delete command. On either of those buttons I would then use the OnClientClick property to execute the JavaScript confirm dialog prior to this. ``` <script type="text/javascript"> function confirmDelete() { return confirm("Are you sure you want to delete this?"); } </script> ... <asp:TemplateField> <ItemTemplate> <asp:ImageButton ID="DeleteButton" runat="server" ImageUrl="..." AlternateText="Delete" ToolTip="Delete" CommandName="Delete" CommandArgument='<%# Eval("ID") %>' OnClientClick="return confirmDelete();" /> </ItemTemplate> </asp:TemplateField> ```
I found that the most elegant way to do this is to use jQuery to wire the onClick event: ``` <script type="text/javascript"> $(".deleteLink").click(function() { return confirm('Are you sure you wish to delete this record?'); }); </script> ... <asp:ButtonField ButtonType="Link" Text="Delete" CommandName="Delete" ItemStyle-CssClass="deleteLink" /> ``` Notice that I use an arbitrary CSS class to identify the link button.
Javascript before asp:ButtonField click
[ "", "asp.net", "javascript", "gridview", "" ]
I have a JSP page that will display the exact content of another web page on a different server. My understanding was that c:import from the JSTL should be able to include content from files that are not part of the current web application. I added c:import url="page on my server in a different application" and it works fine, but when I try to include a page from another server it fails. Any suggestions as to what might be wrong? **EDIT:** The exact error is: "The server encountered an internal error () that prevented it from fulfilling this request.". However, requesting a page from the same server, different app works...I get the content of the page.
I had a similar error once. It turned out to be that the machine that I was running the app on had some problems connecting to the internet through the firewall. Once I deployed the app to a machine that was always connected it worked fine.
An exact code and how "it fails" would be a great help. All mind-readers are currently on vacation. Meanwhile, take a look at <http://www.ibm.com/developerworks/java/library/j-jsp06173.html> ``` <%@ taglib prefix="c" uri="http://java.sun.com/jstl/core" %> ... <c:import url="http://www.truenorthguitars.com/Clients/Richman/index.htm" /> ```
Importing the content of another web resource using JSTL
[ "", "java", "jsp", "import", "jstl", "" ]
I tried searching around, but I couldn't find anything that would help me out. I'm trying to do this in SQL: ``` declare @locationType varchar(50); declare @locationID int; SELECT column1, column2 FROM viewWhatever WHERE CASE @locationType WHEN 'location' THEN account_location = @locationID WHEN 'area' THEN xxx_location_area = @locationID WHEN 'division' THEN xxx_location_division = @locationID ``` I know that I shouldn't have to put '= @locationID' at the end of each one, but I can't get the syntax even close to being correct. SQL keeps complaining about my '=' on the first WHEN line... How can I do this?
``` declare @locationType varchar(50); declare @locationID int; SELECT column1, column2 FROM viewWhatever WHERE @locationID = CASE @locationType WHEN 'location' THEN account_location WHEN 'area' THEN xxx_location_area WHEN 'division' THEN xxx_location_division END ```
without a case statement... ``` SELECT column1, column2 FROM viewWhatever WHERE (@locationType = 'location' AND account_location = @locationID) OR (@locationType = 'area' AND xxx_location_area = @locationID) OR (@locationType = 'division' AND xxx_location_division = @locationID) ```
SQL Switch/Case in 'where' clause
[ "", "sql", "switch-statement", "case", "" ]
This question will expand on: [Best way to open a socket in Python](https://stackoverflow.com/questions/68774/best-way-to-open-a-socket-in-python) When opening a socket how can I test to see if it has been established, and that it did not timeout, or generally fail. Edit: I tried this: ``` try: s.connect((address, '80')) except: alert('failed' + address, 'down') ``` but the alert function is called even when that connection should have worked.
It seems that you catch not the exception you wanna catch out there :) if the `s` is a `socket.socket()` object, then the right way to call `.connect` would be: ``` import socket s = socket.socket() address = '127.0.0.1' port = 80 # port number is a number, not string try: s.connect((address, port)) # originally, it was # except Exception, e: # but this syntax is not supported anymore. except Exception as e: print("something's wrong with %s:%d. Exception is %s" % (address, port, e)) finally: s.close() ``` Always try to see what kind of exception is what you're catching in a try-except loop. You can check what types of exceptions in a socket module represent what kind of errors (timeout, unable to resolve address, etc) and make separate `except` statement for each one of them - this way you'll be able to react differently for different kind of problems.
You can use the function [connect\_ex](http://docs.python.org/2/library/socket.html#socket.socket.connect_ex). It doesn't throw an exception. Instead of that, returns a C style integer value (referred to as [errno](http://linux.die.net/man/3/errno) in C): ``` s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) result = s.connect_ex((host, port)) s.close() if result: print "problem with socket!" else: print "everything it's ok!" ```
Testing socket connection in Python
[ "", "python", "sockets", "" ]
We have the following simple Stored Procedure that runs as an overnight SQL server agent job. Usually it runs in 20 minutes, but recently the MatchEvent and MatchResult tables have grown to over 9 million rows each. This has resulted in the store procedure taking over 2 hours to run, with all 8GB of memory on our SQL box being used up. This renders the database unavailable to the regular queries that are trying to access it. I assume the problem is that temp table is too large and is causing the memory and database unavailablity issues. How can I rewrite the stored procedure to make it more efficient and less memory intensive? Note: I have edited the SQL to indicate that there is come condition affecting the initial SELECT statement. I had previously left this out for simplicity. Also, when the query runs CPU usage is at 1-2%, but memoery, as previously stated, is maxed out ``` CREATE TABLE #tempMatchResult ( matchId VARCHAR(50) ) ``` INSERT INTO #tempMatchResult SELECT MatchId FROM MatchResult WHERE SOME\_CONDITION DELETE FROM MatchEvent WHERE MatchId IN (SELECT MatchId FROM #tempMatchResult) DELETE FROM MatchResult WHERE MatchId In (SELECT MatchId FROM #tempMatchResult) DROP TABLE #tempMatchResult
There's probably a lot of stuff going on here, and it's not all your query. First, I agree with the other posters. Try to rewrite this without a temp table if at all possible. But assuming that you need a temp table here, you have a BIG problem in that you have no PK defined on it. It's vastly going to expand the amount of time your queries will take to run. Create your table like so instead: ``` CREATE TABLE #tempMatchResult ( matchId VARCHAR(50) NOT NULL PRIMARY KEY /* NOT NULL if at all possible */ ); INSERT INTO #tempMatchResult SELECT DISTINCT MatchId FROM MatchResult; ``` Also, make sure that your TempDB is sized correctly. Your SQL server may very well be expanding the database file dynamically on you, causing your query to suck CPU and disk time. Also, make sure your transaction log is sized correctly, and that it is not auto-growing on you. Good luck.
First, indexes are a MUST here see Dave M's answer. Another approach that I will sometime use when deleting very large data sets, is creating a shadow table with all the data, recreating indexes and then using sp\_rename to switch it in. You have to be careful with transactions here, but depending on the amount of data being deleted this can be faster. *Note* If there is pressure on tempdb consider using joins and not copying all the data into the temp table. So for example ``` CREATE TABLE #tempMatchResult ( matchId VARCHAR(50) NOT NULL PRIMARY KEY /* NOT NULL if at all possible */ ); INSERT INTO #tempMatchResult SELECT DISTINCT MatchId FROM MatchResult; set transaction isolation level serializable begin transaction create table MatchEventT(columns... here) insert into MatchEventT select * from MatchEvent m left join #tempMatchResult t on t.MatchId = m.MatchId where t.MatchId is null -- create all the indexes for MatchEvent drop table MatchEvent exec sp_rename 'MatchEventT', 'MatchEvent' -- similar code for MatchResult commit transaction DROP TABLE #tempMatchResult ```
SQL stored procedure temporary table memory problem
[ "", "sql", "sql-server", "stored-procedures", "" ]
I was wondering if there was an alternative to `itoa()` for converting an integer to a string because when I run it in visual Studio I get warnings, and when I try to build my program under Linux, I get a compilation error.
In C++11 you can use [`std::to_string`](http://en.cppreference.com/w/cpp/string/basic_string/to_string): ``` #include <string> std::string s = std::to_string(5); ``` If you're working with prior to C++11, you could use C++ streams: ``` #include <sstream> int i = 5; std::string s; std::stringstream out; out << i; s = out.str(); ``` Taken from <http://notfaq.wordpress.com/2006/08/30/c-convert-int-to-string/>
[boost::lexical\_cast](http://www.boost.org/doc/libs/1_36_0/libs/conversion/lexical_cast.htm) works pretty well. ``` #include <boost/lexical_cast.hpp> int main(int argc, char** argv) { std::string foo = boost::lexical_cast<std::string>(argc); } ```
Alternative to itoa() for converting integer to string C++?
[ "", "c++", "integer", "stdstring", "itoa", "" ]
I have the following problem using template instantiation [\*]. file **foo.h** ``` class Foo { public: template <typename F> void func(F f) private: int member_; }; ``` file **foo.cc** ``` template <typename F> Foo::func(F f) { f(member_); } ``` file **caller.cc** ``` Foo::func(boost::bind(&Bar::bar_func, bar_instance, _1)); ``` While this compiles fine, the linker complains about an undefined symbol: `void Foo::func<boost::_bi::bind_t...>` How can I instantiate the *function* `Foo::func`? Since it takes a function as argument, I am little bit confused. I tried to add an instantiation function in **foo.cc**, as I am used to with regular *non-function* types: ``` instantiate() { template<> void Foo::func<boost::function<void(int)> >(boost::function<void(int)>); } ``` Obviously, this does not work. I would appreciate if someone can point me in the right direction. Thanks! [\*] Yes, I read the parashift FAQ lite.
The answer to this is compiler dependent. Some versions of the Sun C++ compiler would handle this automatically by building a cache of template function implementations that would be shared across separate translation units. If you're using Visual C++, and any other compiler that can't do this, you may as well put the function definition in the header. Don't worry about duplicate definitions if the header is included by multiple .cc files. The compiler marks template-generated methods with a special attribute so the linker knows to throw away duplicates instead of complaining. This is one reason why C++ has the "one definition rule". **Edit:** The above comments apply in the general case where your template must be capable of linking given any type parameters. If you know a closed set of types that clients will use, you can ensure they are available by using explicit instantiation in the template's implementation file, which will cause the compiler to generate definitions for other files to link against. But in the general case where your template needs to work with types possibly only known to the client, then there is little point in separating the template into a header file and and implementation file; any client needs to include both parts anyway. If you want to isolate clients from complex dependencies, hide those dependencies behind non-templated functions and then call into them from the template code.
Splitting it into files Like you want: Not that I recommend this. Just showing that it is possible. plop.h ``` #include <iostream> class Foo { public: Foo(): member_(15){} // Note No definition of this in a header file. // It is defined in plop.cpp and a single instantiation forced // Without actually using it. template <typename F> void func(F f); private: int member_; }; struct Bar { void bar_func(int val) { std::cout << val << "\n"; } }; struct Tar { void tar_func(int val) { std::cout << "This should not print because of specialisation of func\n";} }; ``` Plop.cpp ``` #include "plop.h" #include <boost/bind.hpp> #include <iostream> template <typename F> void Foo::func(F f) { f(member_); } // Gnarly typedef typedef boost::_bi::bind_t<void, boost::_mfi::mf1<void, Bar, int>, boost::_bi::list2<boost::_bi::value<Bar>, boost::arg<1> (*)()> > myFunc; // Force the compiler to generate an instantiation of Foo::func() template void Foo::func<myFunc>(myFunc f); // Note this is not a specialization as that requires the <> after template. // See main.cpp for an example of specialization. ``` main.cpp ``` #include "plop.h" #include <boost/bind.hpp> #include <iostream> // Gnarly typedef typedef boost::_bi::bind_t<void, boost::_mfi::mf1<void, Tar, int>, boost::_bi::list2<boost::_bi::value<Tar>, boost::arg<1> (*)()> > myTar; // Specialization of Foo::func() template<> void Foo::func<myTar>(myTar f) { std::cout << "Special\n"; } // Note. This is not instantiated unless it is used. // But because it is used in main() we get a version. int main(int argc,char* argv[]) { Foo f; Bar b; Tar t; f.func(boost::bind(&Bar::bar_func, b, _1)); // Uses instantiation from plop.cpp f.func(boost::bind(&Tar::tar_func, t, _1)); // Uses local specialization } ```
C++ template instantiation of function template parameters
[ "", "c++", "templates", "boost", "function", "linker", "" ]
I've just had to write a string reverse function in C# 2.0 (i.e. LINQ not available) and came up with this: ``` public string Reverse(string text) { char[] cArray = text.ToCharArray(); string reverse = String.Empty; for (int i = cArray.Length - 1; i > -1; i--) { reverse += cArray[i]; } return reverse; } ``` Personally I'm not crazy about the function and am convinced that there's a better way to do it. Is there?
``` public static string Reverse( string s ) { char[] charArray = s.ToCharArray(); Array.Reverse(charArray); return new string(charArray); } ```
Here a solution that properly reverses the string `"Les Mise\u0301rables"` as `"selbare\u0301siM seL"`. This should render just like `selbarésiM seL`, not `selbaŕesiM seL` (note the position of the accent), as would the result of most implementations based on code units (`Array.Reverse`, etc) or even code points (reversing with special care for surrogate pairs). ``` using System; using System.Collections.Generic; using System.Globalization; using System.Linq; public static class Test { private static IEnumerable<string> GraphemeClusters(this string s) { var enumerator = StringInfo.GetTextElementEnumerator(s); while(enumerator.MoveNext()) { yield return (string)enumerator.Current; } } private static string ReverseGraphemeClusters(this string s) { return string.Join("", s.GraphemeClusters().Reverse().ToArray()); } public static void Main() { var s = "Les Mise\u0301rables"; var r = s.ReverseGraphemeClusters(); Console.WriteLine(r); } } ``` (And live running example here: <https://ideone.com/DqAeMJ>) It simply uses the .NET [API for grapheme cluster iteration](http://msdn.microsoft.com/en-us/library/x2f3k4f6.aspx), which has been there since ever, but a bit "hidden" from view, it seems.
Best way to reverse a string
[ "", "c#", ".net", "performance", "algorithm", "unicode", "" ]
I'm developing an application that manages network interfaces on behalf of the user and it calls out to several external programs (such as ifconfig) that requires root to make changes. (Specifically, changing the IP address of a local interface, etc.) During development, I have been running the IDE as root (ugh) and the debugger as root (double-ugh). Is there a nice way for the end-user to run these under a non-root account? I strongly dislike the size of the attack surface presented by GTK, wxPython, Python, and my application when it runs as root. I have looked into capabilities, but they look half-baked and I'm not sure if I'd be able to use them in Python, especially if they are on a thread basis. The only option I haven't explored is a daemon that has the setuid bit set and does all the root-type stuff on behalf of the UI. I'm hesitant to introduce that complexity this early in the project, as running as root is not a dealbreaker for the users.
Your idea about the daemon has much merit, despite the complexity it introduces. As long as the actions don't require some user interface interaction *as root*, a daemon allows you to control what operations are allowed and disallowed. However, you can use SUDO to create a controlled compromise between ROOT and normal users... simply grant SUDO access to the users in question for the specific tools they need. That reduces the attack surface by allowing only "permitted" root launches.
What you want is a "Group" You create a group, specify that the account wanting to do the action belongs to the group, then you specify that the resource you want access to is a member of that group. Sometimes group management can be kind of irritating, but it should allow you to do anything you want, and it's the user that is authorized, not your program. (If you want your program authorized, you can create a specific user to run it as and give that user the proper group membership, then su to that group within your program to execute the operation without giving the running user the ability.)
Is there something between a normal user account and root?
[ "", "python", "linux", "root", "" ]
``` const static int foo = 42; ``` I saw this in some code here on StackOverflow and I couldn't figure out what it does. Then I saw some confused answers on other forums. My best guess is that it's used in C to hide the constant `foo` from other modules. Is this correct? If so, why would anyone use it in a C++ context where you can just make it `private`?
It has uses in both C and C++. As you guessed, the `static` part limits its scope to that [compilation unit](https://stackoverflow.com/questions/1106149/what-is-a-translation-unit-in-c). It also provides for static initialization. `const` just tells the compiler to not let anybody modify it. This variable is either put in the data or bss segment depending on the architecture, and might be in memory marked read-only. All that is how C treats these variables (or how C++ treats namespace variables). In C++, a member marked `static` is shared by all instances of a given class. Whether it's private or not doesn't affect the fact that one variable is shared by multiple instances. Having `const` on there will warn you if any code would try to modify that. If it was strictly private, then each instance of the class would get its own version (optimizer notwithstanding).
A lot of people gave the basic answer but nobody pointed out that in C++ `const` defaults to `static` at `namespace` level (and some gave wrong information). See the C++98 standard section 3.5.3. First some background: *Translation unit:* A source file after the pre-processor (recursively) included all its include files. *Static linkage:* A symbol is only available within its translation unit. *External linkage:* A symbol is available from other translation units. ### At `namespace` level *This includes the global namespace aka global variables*. ``` static const int sci = 0; // sci is explicitly static const int ci = 1; // ci is implicitly static extern const int eci = 2; // eci is explicitly extern extern int ei = 3; // ei is explicitly extern int i = 4; // i is implicitly extern static int si = 5; // si is explicitly static ``` ### At function level `static` means the value is maintained between function calls. The semantics of function `static` variables is similar to global variables in that they reside in the [program's data-segment](https://stackoverflow.com/questions/93039/where-are-static-variables-stored-in-cc) (and not the stack or the heap), see [this question](https://stackoverflow.com/questions/246564) for more details about `static` variables' lifetime. ### At `class` level `static` means the value is shared between all instances of the class and `const` means it doesn't change.
What does 'const static' mean in C and C++?
[ "", "c++", "c", "" ]
What is the best way to check if a given url points to a valid file (i.e. not return a 404/301/etc.)? I've got a script that will load certain .js files on a page, but I need a way to verify each URL it receives points to a valid file. I'm still poking around the PHP manual to see which file functions (if any) will actually work with remote URLs. I'll edit my post as I find more details, but if anyone has already been down this path feel free to chime in.
The file\_get\_contents is a bit overshooting the purpose as it is enough to have the HTTP header to make the decision, so you'll need to use curl to do so: ``` <?php // create a new cURL resource $ch = curl_init(); // set URL and other appropriate options curl_setopt($ch, CURLOPT_URL, "http://www.example.com/"); curl_setopt($ch, CURLOPT_HEADER, 1); curl_setopt($ch, CURLOPT_NOBODY, 1); // grab URL and pass it to the browser curl_exec($ch); // close cURL resource, and free up system resources curl_close($ch); ?> ```
one such way would be to request the url and get a response with a status code of 200 back, aside from that, there's really no good way because the server has the option of handling the request however it likes (including giving you other status codes for files that exist, but you don't have access to for a number of reasons).
Equivalent is_file() function for URLs?
[ "", "php", "" ]
I'd like my program to read the cache line size of the CPU it's running on in C++. I know that this can't be done portably, so I will need a solution for Linux and another for Windows (Solutions for other systems could be useful to others, so post them if you know them). For Linux I could read the content of /proc/cpuinfo and parse the line beginning with cache\_alignment. Maybe there is a better way involving a call to an API. For Windows I simply have no idea.
On Win32, [`GetLogicalProcessorInformation`](http://msdn.microsoft.com/en-us/library/ms683194.aspx) will give you back a [`SYSTEM_LOGICAL_PROCESSOR_INFORMATION`](http://msdn.microsoft.com/en-us/library/ms686694.aspx) which contains a [`CACHE_DESCRIPTOR`](http://msdn.microsoft.com/en-us/library/ms681979.aspx), which has the information you need.
On Linux try the [proccpuinfo library](https://savannah.nongnu.org/projects/proccpuinfo/), an architecture independent C API for reading /proc/cpuinfo
How to programmatically get the CPU cache line size in C++?
[ "", "c++", "linux", "windows", "cpu", "cpu-cache", "" ]
I'm developing a simple Qt 4 app and making my own dialog. I subclassed `QDialog`, inserted the `Q_OBJECT` macro in the class declaration block, and... I get > [Linker error] undefined reference to `vtable for MyDialog' and there is no > moc\_MyDialog.cpp generated by the moc compiler. I am using Qt 4.1.3 on Windows XP and mingw. I followed the build process from the Qt-supplied build shell. I used qmake to create make files and compiled everything with a make command. I have other classes that subclass `QPushButton` and `QObject` respectively, but they compile OK. I can't find any differences between them and the broken one. There must be missing something in the broken class, but I'm unable to spot it.
The undefined reference to "vtable for MyDialog" is caused because there is no moc file. Most c++ compilers create the vtable definition in the object file containing the first virtual function. When subclassing a qt object and using the Q\_OBJECT macro, this will be in the moc\*.cpp file. Therefore, this error means that the moc file is missing. The possible problems I can think of are: 1. The header file for the class MyDialog.h is not added to HEADERS in the qmake file. 2. You ran qmake to generate the make file *before* adding the Q\_OBJECT macro. This created a make file without the moc rules. This is easily fixed by simply running qmake again. 3. Your dialog derives from more than one class and QDialog is not the first class that it derives from. For qmake to work correctly, the QObject derived base class needs to be the first class that is inherited from. 4. If you are using Qt Creator, you might get this error if your previous deployment was failed due to some reason (like application already running). In that case, simply do a 'Clean Project' and then 'Rebuild Project' and then 'Run' to deploy.
If you have your header file included, follow the steps: 1. Right click on the project where you have added this. 2. Hit 'Run qmake'. This will will clear up the old references and build with th Q\_OBJECT macro. QT doesn't do it on rebuild.
Qt and no moc_*.cpp file
[ "", "c++", "qt", "qt4", "" ]
What I would like to achive is: * I go to admin site, apply some filters to the list of objects * I click and object edit, edit, edit, hit 'Save' * Site takes me to the list of objects... unfiltered. I'd like to have the filter from step 1 remembered and applied. Is there an easy way to do it?
Unfortunately there's no easy way to do this. The filtering does not seem to be saved in any session variable. Clicking back twice is the normal method, but it can be unweildy and annoying if you've just changed an object so that it should no longer be shown using your filter. If it's just a one-off, click back twice or go through the filtering again, it's the easiest way. If you're going to be filtering more often, or you just want to learn about hacking the admin (which is pretty open and easy), you'll want to write a [FilterSpec](http://code.djangoproject.com/browser/django/trunk/django/contrib/admin/filterspecs.py). Have a look [here](http://www.djangosnippets.org/snippets/1051/) and [here](http://www.djangosnippets.org/snippets/587/) for examples of people writing their own. A really, really terrible way to do this would be to edit the admin interface so that after you click "Save", you are redirected to you filtered URL. I wouldn't recommend this at all, but it's an option. Another fairly simple way to do this would be to write a generic view to show your filtered objects, then use Django forms to edit the items from there. I'd have a look at this, you'll be stunned just how little code you have to write to get a simple view/edit page going.
Click 2 times "Back"?
Keeping filters in Django Admin
[ "", "python", "django", "django-admin", "" ]
I'm looking for a container that keeps all its items in order. I looked at SortedList, but that requires a separate key, and does not allow duplicate keys. I could also just use an unsorted container and explicitly sort it after each insert. Usage: * Occasional insert * Frequent traversal in order * Ideally not working with keys separate from the actual object, using a compare function to sort. * Stable sorting for equivalent objects is desired, but not required. * Random access is not required. I realize I can just build myself a balanced tree structure, I was just wondering if the framework already contains such a beast.
You might want to take a look at the [Wintellect Power Collections](https://github.com/timdetering/Wintellect.PowerCollections). It is available on CodePlex and contains quite a few collections that are very helpful. The OrderedBag collection in the project is exactly what you are looking for. It essentially uses a [red-black tree](https://en.wikipedia.org/wiki/Red-black_tree) to provide a pretty efficient sort.
Just to make [EBarr's comment](https://stackoverflow.com/questions/196512/is-there-a-sorted-collection-type-in-net/198699#comment10376249_196549) as answer, there is [`SortedSet<T>`](http://msdn.microsoft.com/en-us/library/dd412070%28v=vs.100%29.aspx) since .NET 4.0. Of course it is a set, which means you cannot have duplicates.
Is there a sorted collection type in .NET?
[ "", "c#", ".net", "sorting", "containers", "" ]
Problem with dynamic controls Hello all, I'm wanting to create some dynamic controls, and have them persist their viewstate across page loads. Easy enough, right? All I have to do is re-create the controls upon each page load, using the same IDs. HOWEVER, here's the catch - in my PreRender event, I'm wanting to clear the controls collection, and then recreate the dynamic controls with new values. The reasons for this are complicated, and it would probably take me about a page or so to explain why I want to do it. So, in the interests of brevity, let's just assume that I absolutely must do this, and that there's no other way. The problem comes in after I re-create the controls in my PreRender event. The re-created controls never bind to the viewstate, and their values do not persist across page loads. I don't understand why this happens. I'm already re-creating the controls in my OnLoad event. When I do this, the newly created controls bind to the ViewState just fine, provided that I use the same IDs every time. However, when I try to do the same thing in the PreRender event, it fails. In any case, here is my example code : namespace TestFramework.WebControls { ``` public class ValueLinkButton : LinkButton { public string Value { get { return (string)ViewState[ID + "vlbValue"]; } set { ViewState[ID + "vlbValue"] = value; } } } public class TestControl : WebControl { protected override void OnLoad(EventArgs e) { base.OnLoad(e); Controls.Clear(); ValueLinkButton tempLink = null; tempLink = new ValueLinkButton(); tempLink.ID = "valueLinkButton"; tempLink.Click += new EventHandler(Value_Click); if (!Page.IsPostBack) { tempLink.Value = "old value"; } Controls.Add(tempLink); } protected override void OnPreRender(EventArgs e) { base.OnPreRender(e); ValueLinkButton tempLink = ((ValueLinkButton)FindControl("valueLinkButton")); //[CASE 1] //ValueLinkButton tempLink = new ValueLinkButton(); [CASE 2] tempLink.ID = "valueLinkButton"; tempLink.Value = "new value"; tempLink.Text = "Click"; Controls.Clear(); Controls.Add(tempLink); } void Value_Click(object sender, EventArgs e) { Page.Response.Write("[" + ((ValueLinkButton)sender).Value + "]"); } } ``` } So, let's examine case 1, where the line next to [CASE 1] is not commented out, but the line next to [CASE 2] is commented out. Here, everything works just fine. When I put this control on a page and load the page, I see a link that says "Click". When I click the link, the page outputs the text "[new value]", and on the next line, we see the familiar "Click" link. Every subesquent time I click on the "Click" link, we see the same thing. So far, so good. But now let's examine case 2, where the line next to [CASE 1] is commented out, but the line next to [CASE 2] is not commented out. Here we run into problems. When we load the page, we see the "Click" link. However, when I click on the link, the page outputs the text "[]" instead of "[new value]". The click event is firing normally. However, the "new value" text that I assigned to the Value attribute of the control does not get persisted. Once again, this is a bit of a mystery to me. How come, when I recreate the control in OnLoad, everything's fine and dandy, but when I recreate the control in PreRender, the value doesn't get persisted? I feel like there simply has to be a way to do this. When I re-create the control in PreRender, is there some way to bind the newly created control to the ViewState? I've struggled with this for days. Any help that you can give me will be appreciated. Thanks.
ViewState-backed properties are only persisted to ViewState if the control is currently tracking ViewState. This is by design to keep ViewState as small as possible: it should only contain data that is truly dynamic. The upshot of this is that: ViewState propeties set during the Init event are *not* backed to ViewState (because the Page has not yet started tracking ViewState). Thus Init is a good place to add controls and set (a) properties that won't change between postbacks (ID, CssClass...) as well as initial values for dynamic properties (which can then be modified by code in the rest of the page lifecycle - Load, event handlers, PreRender). When dynamically adding controls in Load or PreRender, ViewState is being tracked. The developer can then control which propeties are persisted for dynamically added controls as follows: * Properties set before the control is added to the page's control tree are not persisted to ViewState. You typically set properties that are not dynamic (ID etc) before adding a control to the control tree. * Properties set after the control is added to the page's control tree are persisted to ViewState (ViewState tracking is enabled from before the Load Event to after the PreRender event). In your case, your PreRender handler is setting properties before adding the control to the page's control tree. To get the result you want, set dynamic properties after adding the control to the control tree: . ``` protected override void OnPreRender(EventArgs e) { base.OnPreRender(e); ValueLinkButton tempLink = new ValueLinkButton(); // [CASE 2] tempLink.ID = "valueLinkButton"; // Not persisted to ViewState Controls.Clear(); Controls.Add(tempLink); tempLink.Value = "new value"; // Persisted to ViewState tempLink.Text = "Click"; // Persisted to ViewState } ```
As others have statement you'll need to ensure that you are creating via the Init method. To learn more about the ASP.NET page life cycle check out this article: <http://msdn.microsoft.com/en-us/library/ms178472.aspx>
Problem with dynamic controls in .NET
[ "", "c#", "asp.net", "dynamic", "controls", "viewstate", "" ]
What's the best/most efficient way to extract text set between parenthesis? Say I wanted to get the string "text" from the string "ignore everything except this (text)" in the most efficient manner possible. So far, the best I've come up with is this: ``` $fullString = "ignore everything except this (text)"; $start = strpos('(', $fullString); $end = strlen($fullString) - strpos(')', $fullString); $shortString = substr($fullString, $start, $end); ``` Is there a better way to do this? I know in general using regex tends to be less efficient, but unless I can reduce the number of function calls, perhaps this would be the best approach? Thoughts?
i'd just do a regex and get it over with. unless you are doing enough iterations that it becomes a huge performance issue, it's just easier to code (and understand when you look back on it) ``` $text = 'ignore everything except this (text)'; preg_match('#\((.*?)\)#', $text, $match); print $match[1]; ```
So, actually, the code you posted doesn't work: `substr()'s` parameters are $string, $start and **$length**, and `strpos()'s` parameters are `$haystack`, `$needle`. Slightly modified: ``` $str = "ignore everything except this (text)"; $start = strpos($str, '('); $end = strpos($str, ')', $start + 1); $length = $end - $start; $result = substr($str, $start + 1, $length - 1); ``` Some subtleties: I used `$start + 1` in the offset parameter in order to help PHP out while doing the `strpos()` search on the second parenthesis; we increment `$start` one and reduce `$length` to exclude the parentheses from the match. Also, there's no error checking in this code: you'll want to make sure `$start` and `$end` do not === false before performing the `substr`. As for using `strpos/substr` versus regex; performance-wise, this code will beat a regular expression hands down. It's a little wordier though. I eat and breathe `strpos/substr`, so I don't mind this too much, but someone else may prefer the compactness of a regex.
PHP: Best way to extract text within parenthesis?
[ "", "php", "parsing", "string", "" ]
I've programmed C and C++ for a long time and so far I've never used exceptions and try / catch. What are the benefits of using that instead of just having functions return error codes?
Possibly an obvious point - a developer can ignore (or not be aware of) your return status and go on blissfully unaware that something failed. An exception needs to be acknowledged in some way - it can't be silently ignored without actively putting something in place to do so.
The advantage of exceptions are two fold: * **They can't be ignored.** You must deal with them at some level, or they will terminate your program. With error code, you must explicitly check for them, or they are lost. * **They can be ignored.** If an error can't be dealt with at one level, it will automatically bubble up to the next level, where it can be. Error codes must be explicitly passed up until they reach the level where it can be dealt with.
In C++ what are the benefits of using exceptions and try / catch instead of just returning an error code?
[ "", "c++", "exception", "try-catch", "" ]
Does anyone know of a sample distributed application (.NET or J2EE) using RMI or Web Services?
**Here's a simple solution:** [BEA Weblogic](http://www.bea.com/framework.jsp?CNT=index.htm&FP=/content/products/weblogic/server) has a sample web application called **MedRec** that I've been using for a while. This sample comes with a .NET client built in called **CSharpClient** that connects to MedRec via Web Services. I was thrilled that I didn't need to install anything else. In Weblogic 10 the client can be found in the folder "bea\wlserver\_10.0\samples\server\medrec\src\clients\CSharpClient".
As often, Sun has an excellent tutorial on RMI: <http://java.sun.com/docs/books/tutorial/rmi/index.html>
RMI or Web Services sample application
[ "", "java", ".net", "web-services", "" ]
I was hoping to implement a simple XMPP server in Java. What I need is a library which can parse and understand xmpp requests from a client. I have looked at Smack (mentioned below) and JSO. Smack appears to be client only so while it might help parsing packets it doesn't know how to respond to clients. Is JSO maintained it looks very old. The only promising avenue is to pull apart Openfire which is an entire commercial (OSS) XMPP server. I was just hoping for a few lines of code on top of Netty or Mina, so I could get started processing some messages off the wire. --- Joe - Well the answer to what I am trying to do is somewhat long - I'll try to keep it short. There are two things, that are only loosely related: 1) I wanted to write an XMPP server because I imagine writing a custom protocol for two clients to communicate. Basically I am thinking of a networked iPhone app - but I didn't want to rely on low-level binary protocols because using something like XMPP means the app can "grow up" very quickly from a local wifi based app to an internet based one... The msgs exchanged should be relatively low latency, so strictly speaking a binary protocol would be best, but I felt that it might be worth exploring if XMPP didn't introduce too much overhead such that I could use it and then reap benefits of it's extensability and flexability later. 2) I work for Terracotta - so I have this crazy bent to cluster everything. As soon as I started thinking about writing some custom server code, I figured I wanted to cluster it. Terracotta makes scaling out Java POJOs trivial, so my thought was to build a super simple XMPP server as a demonstration app for Terracotta. Basically each user would connect to the server over a TCP connection, which would register the user into a hashmap. Each user would have a LinkedBlockingQueue with a listener thread taking message from the queue. Then any connected user that wants to send a message to any other user (e.g. any old chat application) simply issues an XMPP message (as usual) to that user over the connection. The server picks it up, looks up the corresponding user object in a map and places the message onto the queue. Since the queue is clustered, regardless of wether the destination user is connected to the same physical server, or a different physical server, the message is delivered and the thread that is listening picks it up and sends it back down the destination user's tcp connection. So - not too short of a summary I'm afraid. But that's what I want to do. I suppose I could just write a plugin for Openfire to accomplish #1 but I think it takes care of a lot of plumbing so it's harder to do #2 (especially since I was hoping for a very small amount of code that could fit into a simple 10-20kb Maven project).
<http://xmpp.org/xmpp-software/libraries/> has a list of software libraries for XMPP. Here is an *outdated* snapshot of it: ### ActionScript * [as3xmpp](http://code.google.com/p/as3xmpp/) ### C * [iksemel](http://code.google.com/p/iksemel/) * [libstrophe](http://www.onlinegamegroup.com/projects/libstrophe) * [Loudmouth](http://www.loudmouth-project.org/) ### C++ * [gloox](http://camaya.net/gloox) * [Iris](http://delta.affinix.com/iris/) * [oajabber](http://www.openaether.org/oajabber.html) ### C# / .NET / Mono * [agsXMPP SDK](http://www.ag-software.de/index.php?page=agsxmpp-sdk) * [jabber-net](http://code.google.com/p/jabber-net/) ### Erlang * [Jabberlang](http://support.process-one.net/doc/display/CONTRIBS/Jabberlang) ### Flash * [XIFF](http://www.igniterealtime.org/projects/xiff/) ### Haskell * [hsxmpp](http://www.dtek.chalmers.se/~henoch/text/hsxmpp.html) ### Java * [Echomine Feridian](http://freecode.com/projects/feridian) * [Jabber Stream Objects (JSO)](http://java.net/projects/jso/) * [Smack](http://www.igniterealtime.org/projects/smack/index.jsp) ### JavaScript * [strophe.js](http://strophe.im/strophejs/) * [xmpp4js](http://xmpp4js.sourceforge.net/) ### Lisp * [cl-xmpp](http://common-lisp.net/project/cl-xmpp/) ### Objective-C * [xmppframework](http://code.google.com/p/xmppframework/) ### Perl * [AnyEvent::XMPP](http://www.ta-sa.org/projects/net_xmpp2.html) ### PHP * [Lightr](https://area51.myyearbook.com/trac.cgi/wiki/Lightr) * [xmpphp](http://code.google.com/p/xmpphp/) ### Python * [jabber.py](http://jabberpy.sourceforge.net/) * [pyxmpp](http://pyxmpp.jajcus.net/) * [SleekXMPP](http://code.google.com/p/sleekxmpp/) * [Twisted Words](http://twistedmatrix.com/trac/) * [xmpp-psn](http://code.google.com/p/xmpp-psn/) * [xmpppy](http://xmpppy.sourceforge.net/) ### Ruby * [XMPP4R](http://xmpp4r.github.io/) ### Tcl * [JabberLib](http://coccinella.im/jabberlib)
I went through the same search. I first tried Smack and then realized it's targeted at c2s (client to server) and didn't have what I need. I looked at Tinder but didn't like the licensing model (also when I looked it was much more raw). I finally looked at Whack and realized it was what I needed - but it's missing a lot (that's why Tinder came about I think). So..my solution? Forked Whack, added some code to abstract out things, and try to make it easier to use: <http://github.com/Communitivity/Adirondack> I wrote a Scala library based on that to help create external component based agents, see <http://github.com/Communitivity/Shellack> and <http://github.com/Communitivity/MinimalScalaXMPPComponent> One of my main goals was to make it easy to write a component quickly. An example of such a component is below: ``` object Main { /** * @param args the command line arguments */ def main(args: Array[String]) :Unit = { new XMPPComponent( new ComponentConfig() { def secret() : String = { "secret.goes.here" } def server() : String = { "communitivity.com" } def subdomain() : String = { "weather" } def name() : String = { "US Weather" } def description() : String = { "Weather component that also supported SPARQL/XMPP" } }, actor { loop { react { case (pkt:Packet, out : Actor) => Console.println("Received packet...\n"+pkt.toXML) pkt match { case message:Message => val reply = new Message() reply.setTo(message.getFrom()) reply.setFrom(message.getTo()) reply.setType(message.getType()) reply.setThread(message.getThread()) reply.setBody("Received '"+message.getBody()+"', tyvm") out ! reply case _ => Console.println("Received something other than Message") } case _ => Console.println("Received something other than (Packet, actor)") } } } ).start } } ```
Good XMPP Java Libraries for server side?
[ "", "java", "xmpp", "" ]
I am after a regular expression that validates a percentage from 0 100 and allows two decimal places. Does anyone know how to do this or know of good web site that has example of common regular expressions used for client side validation in javascript? @Tom - Thanks for the questions. Ideally there would be no leading 0's or other trailing characters. Thanks to all those who have replied so far. I have found the comments really interesting.
Rather than using regular expressions for this, I would simply convert the user's entered number to a floating point value, and then check for the range you want (0 to 100). Trying to do numeric range validation with regular expressions is almost always the wrong tool for the job. ``` var x = parseFloat(str); if (isNaN(x) || x < 0 || x > 100) { // value is out of range } ```
I propose this one: ``` (^100(\.0{1,2})?$)|(^([1-9]([0-9])?|0)(\.[0-9]{1,2})?$) ``` It matches 100, 100.0 and 100.00 using this part ``` ^100(\.0{1,2})?$ ``` and numbers like 0, 15, 99, 3.1, 21.67 using ``` ^([1-9]([0-9])?|0)(\.[0-9]{1,2})?$ ``` Note what leading zeros are prohibited, but trailing zeros are allowed (though no more than two decimal places).
Javascript percentage validation
[ "", "javascript", "regex", "" ]
My friend was given this free google website optimizer tshirt and came to me to try and figure out what the front logo meant. [t-shirt](http://2.bp.blogspot.com/_iQVgmEEAit4/SPkKHA3e8fI/AAAAAAAAAB8/ugUerJjuBw8/s1600-h/GWO-tshirt.jpg) So, I have a couple of guesses as to what it means, but I was just wondering if there is something more. My first guess is that each block represents a page layout, and the logo "You should test that" just means that you should use google website optimizer to test which is the best layout. I hope that this isn't the answer, it just seems to simple and unsatisfying. Well, I've spent the past hour trying to figure out if there is any deeper meaning, but to no avail. So, I'm here hoping that someone might be able to help. I did though write a program to see if the blocks represent something in binary. I'll post the code below. My code tests every permutation of reading a block as 4 bits, and then tries to interpret these bits as letters, hex, and ip addresses. I hope someone knows better. ``` #This code interprets the google t-shirt as a binary code, each box 4 bits. # I try every permutation of counting the bits and then try to interpret these # interpretations as letters, or hex numbers, or ip addresses. # I need more interpretations, maybe one will find a pattern import string #these represent the boxes binary codes from left to right top to bottom boxes = ['1110', '1000', '1111', '0110', '0011', '1011', '0001', '1001'] #changing the ordering permutations = ["1234", "1243", "1324", "1342", "1423", "1432", "2134", "2143", "2314", "2341", "2413", "2431", "3124", "3142", "3214", "3241", "3412", "3421", "4123", "4132", "4213", "4231","4312", "4321"] #alphabet hashing where 0 = a alphabet1 = {'0000':'a', '0001':'b', '0010':'c', '0011':'d', '0100':'e', '0101':'f', '0110':'g', '0111':'h', '1000':'i', '1001':'j', '1010':'k', '1011':'l', '1100':'m', '1101':'n', '1110':'o', '1111':'p'} #alphabet hasing where 1 = a alphabet2 = {'0000':'?', '0001':'a', '0010':'b', '0011':'c', '0100':'d', '0101':'e', '0110':'f', '0111':'g', '1000':'h', '1001':'i', '1010':'j', '1011':'k', '1100':'l', '1101':'m', '1110':'n', '1111':'o'} hex = {'0000':'0', '0001':'1', '0010':'2', '0011':'3', '0100':'4', '0101':'5', '0110':'6', '0111':'7', '1000':'8', '1001':'9', '1010':'a', '1011':'b', '1100':'c', '1101':'d', '1110':'e', '1111':'f'} #code to convert from a string of ones and zeros(binary) to decimal number def bin_to_dec(bin_string): l = len(bin_string) answer = 0 for index in range(l): answer += int(bin_string[l - index - 1]) * (2**index) return answer #code to try and ping ip addresses def ping(ipaddress): #ping the network addresses import subprocess # execute the code and pipe the result to a string, wait 5 seconds test = "ping -t 5 " + ipaddress process = subprocess.Popen(test, shell=True, stdout=subprocess.PIPE) # give it time to respond process.wait() # read the result to a string result_str = process.stdout.read() #For now, need to manually check if the ping worked, fix later print result_str #now iterate over the permuation and then the boxes to produce the codes for permute in permutations: box_codes = [] for box in boxes: temp_code = "" for index in permute: temp_code += box[int(index) - 1] box_codes.append(temp_code) #now manipulate the codes using leter translation, network, whatever #binary print string.join(box_codes, "") #alphabet1 print string.join( map(lambda x: alphabet1[x], box_codes), "") #alphabet2 print string.join( map(lambda x: alphabet2[x], box_codes), "") #hex print string.join( map(lambda x: hex[x], box_codes), "") #ipaddress, call ping and see who is reachable ipcodes = zip(box_codes[0:8:2], box_codes[1:8:2]) ip = "" for code in ipcodes: bin = bin_to_dec(code[0] + code[1]) ip += repr(bin) + "." print ip[:-1] #ping(ip[:-1]) print print ``` [t-shirt](http://2.bp.blogspot.com/_iQVgmEEAit4/SPkKHA3e8fI/AAAAAAAAAB8/ugUerJjuBw8/s1600-h/GWO-tshirt.jpg).
I emailed the Website Optimizer Team, and they said "There's no secret code, unless you find one. :)"
I think Google are just trying to drive their point home - here are a bunch of different representations of the same page, test them, see which is best. Which block do you like best?
Possible Google Riddle?
[ "", "python", "" ]
What is the best way to access an ASP.NET HiddenField control that is embedded in an ASP.NET PlaceHolder control through JavaScript? The Visible attribute is set to false in the initial page load and can changed via an AJAX callback. Here is my current source code: ``` <script language="javascript" type="text/javascript"> function AccessMyHiddenField() { var HiddenValue = document.getElementById("<%= MyHiddenField.ClientID %>").value; //do my thing thing..... } </script> <asp:PlaceHolder ID="MyPlaceHolder" runat="server" Visible="false"> <asp:HiddenField ID="MyHiddenField" runat="server" /> </asp:PlaceHolder> ``` **EDIT:** How do I set the style for a div tag in the ascx code behind in C#? This is the description from the code behind: CssStyleCollection HtmlControl.Style **UPDATE:** I replaced the asp:hiddenfield with an asp:label and I am getting an "undefined" when I display the HiddenValue variable in a alert box. How would I resolve this. **UPDATE 2:** I went ahead and refactored the code, I replaced the hidden field control with a text box control and set the style to "display: none;". I also removed the JavaScript function (it was used by a CustomValidator control) and replaced it with a RequiredFieldValidator control.
My understanding is if you set controls.Visible = false during initial page load, it doesn't get rendered in the client response. My suggestion to solve your problem is 1. Don't use placeholder, judging from the scenario, you don't really need a placeholder, unless you need to dynamically add controls on the server side. Use div, without runat=server. You can always controls the visiblity of that div using css. 2. If you need to add controls dynamically later, use placeholder, but don't set visible = false. Placeholder won't have any display anyway, Set the visibility of that placeholder using css. Here's how to do it programmactically : placeholderId.Attributes["style"] = "display:none"; Anyway, as other have stated, your problems occurs because once you set control.visible = false, it doesn't get rendered in the client response.
If the Visibility is set to false server-side, the placeholder won't be rendered and you won't be able to access anything inside it from JavaScript. Your code should work when the placeholder is visible="true" Get rid of the placeholder, leave the hidden field empty at first, after the search populate it.
Access an asp:hiddenfield control in JavaScript
[ "", "asp.net", "javascript", "" ]
First of all there is a [partial question](https://stackoverflow.com/questions/59880/are-stored-procedures-more-efficient-in-general-than-inline-statements-on-moder) regarding this, but it is not exactly what I'm asking, so, bear with me and go for it. My question is, after looking at what [SubSonic](http://subsonicproject.com/) does and the excellent videos from Rob Connery I need to ask: **Shall we use a tool like this and do Inline queries or** shall we do the queries **using** a call to the **stored procedure?** I don't want to minimize any work from Rob (which I think it's amazing) but I just want your opinion on this cause I need to start a new project and I'm in the middle of the line; shall I use SubSonic (or other like tool, like NHibernate) or I just continue my method that is always call a stored procedure even if it's a simple as ``` Select this, that from myTable where myStuff = StackOverflow; ```
It doesn't need to be one or the other. If it's a simple query, use the SubSonic query tool. If it's more complex, use a stored procedure and load up a collection or create a dataset from the results. See here: [What are the pros and cons to keeping SQL in Stored Procs versus Code](https://stackoverflow.com/questions/15142/what-are-the-pros-and-cons-to-keeping-sql-in-stored-procs-versus-code) and here [SubSonic and Stored Procedures](https://stackoverflow.com/questions/228175/subsonic-and-stored-procedures)
See answers [here](https://stackoverflow.com/questions/15142/what-are-the-pros-and-cons-to-keeping-sql-in-stored-procs-versus-code) and [here](https://stackoverflow.com/questions/59880/are-stored-procedures-more-efficient-in-general-than-inline-statements-on-moder). I use sprocs whenever I can, except when red tape means it takes a week to make it into the database.
Stored procedures or inline queries?
[ "", "sql", "stored-procedures", "subsonic", "" ]
I'm writing a query for an application that needs to list all the products with the number of times they have been purchased. I came up with this and it works, but I am not too sure how optimized it is. My SQL is really rusty due to my heavy usage of ORM's, But in this case a query is a much more elegant solution. Can you spot anything wrong (approach wise) with the query? --- ``` SELECT products.id, products.long_name AS name, count(oi.order_id) AS sold FROM products LEFT OUTER JOIN ( SELECT * FROM orderitems INNER JOIN orders ON orderitems.order_id = orders.id AND orders.paid = 1 ) AS oi ON oi.product_id = products.id GROUP BY products.id ``` --- The schema (with relevant fields) looks like this: ``` *orders* id, paid *orderitems* order_id, product_id *products* id ``` ## UPDATE This is for MySQL
I'm not sure about the "(SELECT \*" ... business. This executes (always a good start) and I think is equivalent to what was posted. ``` SELECT products.id, products.long_name AS name, count(oi.order_id) AS sold FROM products LEFT OUTER JOIN orderitems AS oi INNER JOIN orders ON oi.order_id = orders.id AND orders.paid = 1 ON oi.product_id = products.id GROUP BY products.id ```
Here a solution for those of us who are nesting impaired. (I get so confused when I start nesting joins) ``` SELECT products.id, products.long_name AS name, count(oi.order_id) AS sold FROM orders INNER JOIN orderitems AS oi ON oi.order_id = orders.id AND orders.paid = 1 RIGHT JOIN products ON oi.product_id = products.id GROUP BY products.id ``` However, I tested your solution, Mike's and mine on MS SQL Server and the query plans are identical. I can't speak for MySql but if MS SQL Server is anything to go by, you may find the performance of all three solutions equivalent. If that is the case I guess you pick which solution is clearest to you.
Does this query look optimized?
[ "", "mysql", "sql", "optimization", "" ]
What is the best way to copy a list? I know the following ways, which one is better? Or is there another way? ``` lst = ['one', 2, 3] lst1 = list(lst) lst2 = lst[:] import copy lst3 = copy.copy(lst) ```
If you want a shallow copy (elements aren't copied) use: ``` lst2=lst1[:] ``` If you want to make a deep copy then use the copy module: ``` import copy lst2=copy.deepcopy(lst1) ```
I often use: ``` lst2 = lst1 * 1 ``` If lst1 it contains other containers (like other lists) you should use deepcopy from the copy lib as shown by Mark. --- UPDATE: Explaining deepcopy ``` >>> a = range(5) >>> b = a*1 >>> a,b ([0, 1, 2, 3, 4], [0, 1, 2, 3, 4]) >>> a[2] = 55 >>> a,b ([0, 1, 55, 3, 4], [0, 1, 2, 3, 4]) ``` As you may see only a changed... I'll try now with a list of lists ``` >>> >>> a = [range(i,i+3) for i in range(3)] >>> a [[0, 1, 2], [1, 2, 3], [2, 3, 4]] >>> b = a*1 >>> a,b ([[0, 1, 2], [1, 2, 3], [2, 3, 4]], [[0, 1, 2], [1, 2, 3], [2, 3, 4]]) ``` Not so readable, let me print it with a for: ``` >>> for i in (a,b): print i [[0, 1, 2], [1, 2, 3], [2, 3, 4]] [[0, 1, 2], [1, 2, 3], [2, 3, 4]] >>> a[1].append('appended') >>> for i in (a,b): print i [[0, 1, 2], [1, 2, 3, 'appended'], [2, 3, 4]] [[0, 1, 2], [1, 2, 3, 'appended'], [2, 3, 4]] ``` You see that? It appended to the b[1] too, so b[1] and a[1] are the very same object. Now try it with deepcopy ``` >>> from copy import deepcopy >>> b = deepcopy(a) >>> a[0].append('again...') >>> for i in (a,b): print i [[0, 1, 2, 'again...'], [1, 2, 3, 'appended'], [2, 3, 4]] [[0, 1, 2], [1, 2, 3, 'appended'], [2, 3, 4]] ```
What is the best way to copy a list?
[ "", "python", "" ]
Is there a simple out of the box way to impersonate a user in .NET? So far I've been using [this class from code project](http://www.codeproject.com/KB/cs/zetaimpersonator.aspx) for all my impersonation requirements. Is there a better way to do it by using .NET Framework? I have a user credential set, (username, password, domain name) which represents the identity I need to impersonate.
Here is some good overview of .NET impersonation concepts. * [Michiel van Otegem: WindowsImpersonationContext made easy](https://web.archive.org/web/20150613031724/http://michiel.vanotegem.nl/2006/07/windowsimpersonationcontext-made-easy/) * [WindowsIdentity.Impersonate Method (check out the code samples)](http://msdn.microsoft.com/en-us/library/chf6fbt4.aspx) Basically you will be leveraging these classes that are out of the box in the .NET framework: * [WindowsImpersonationContext](http://msdn.microsoft.com/en-us/library/system.security.principal.windowsimpersonationcontext.aspx) * [WindowsIdentity](http://msdn.microsoft.com/en-us/library/system.security.principal.windowsidentity.aspx) The code can often get lengthy though and that is why you see many examples like the one you reference that try to simplify the process.
"Impersonation" in the .NET space generally means running code under a specific user account. It is a somewhat separate concept than getting access to that user account via a username and password, although these two ideas pair together frequently. ## Impersonation The APIs for impersonation are provided in .NET via the `System.Security.Principal` namespace: * Newer code should generally use [`WindowsIdentity.RunImpersonated`](https://learn.microsoft.com/dotnet/api/system.security.principal.windowsidentity.runimpersonated), which accepts a handle to the token of the user account, and then either an `Action` or `Func<T>` for the code to execute. ``` WindowsIdentity.RunImpersonated(userHandle, () => { // do whatever you want as this user. }); ``` or ``` var result = WindowsIdentity.RunImpersonated(userHandle, () => { // do whatever you want as this user. return result; }); ``` There's also [`WindowsIdentity.RunImpersonatedAsync`](https://learn.microsoft.com/dotnet/api/system.security.principal.windowsidentity.runimpersonatedasync) for async tasks, available on .NET 5+, or older versions if you pull in the [System.Security.Principal.Windows](https://www.nuget.org/packages/System.Security.Principal.Windows) Nuget package. ``` await WindowsIdentity.RunImpersonatedAsync(userHandle, async () => { // do whatever you want as this user. }); ``` or ``` var result = await WindowsIdentity.RunImpersonated(userHandle, async () => { // do whatever you want as this user. return result; }); ``` * Older code used the [`WindowsIdentity.Impersonate`](https://learn.microsoft.com/dotnet/api/system.security.principal.windowsidentity.impersonate) method to retrieve a `WindowsImpersonationContext` object. This object implements `IDisposable`, so generally should be called from a `using` block. ``` using (WindowsImpersonationContext context = WindowsIdentity.Impersonate(userHandle)) { // do whatever you want as this user. } ``` While this API still exists in .NET Framework, it should generally be avoided. ## Accessing the User Account The API for using a username and password to gain access to a user account in Windows is [`LogonUser`](http://msdn.microsoft.com/en-us/library/windows/desktop/aa378184.aspx) - which is a Win32 native API. There is not currently a built-in managed .NET API for calling it. ``` [DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Unicode)] internal static extern bool LogonUser(String lpszUsername, String lpszDomain, String lpszPassword, int dwLogonType, int dwLogonProvider, out IntPtr phToken); ``` This is the basic call definition, however there is a lot more to consider to actually using it in production: * Obtaining a handle with the "safe" access pattern. * Closing the native handles appropriately * Code access security (CAS) trust levels (in .NET Framework only) * Passing `SecureString` when you can collect one safely via user keystrokes. Instead of writing that code yourself, consider using my [SimpleImpersonation](https://github.com/mattjohnsonpint/SimpleImpersonation) library, which provides a managed wrapper around the `LogonUser` API to get a user handle: ``` using System.Security.Principal; using Microsoft.Win32.SafeHandles; using SimpleImpersonation; var credentials = new UserCredentials(domain, username, password); using SafeAccessTokenHandle userHandle = credentials.LogonUser(LogonType.Interactive); // or another LogonType ``` You can now use that `userHandle` with any of the methods mentioned in the first section above. This is the preferred API as of version 4.0.0 of the SimpleImpersonation library. See the project readme for more details. ## Remote Computer Access It's important to recognize that impersonation is a *local machine* concept. One cannot impersonate using a user that is only known to a remote machine. If you want to access resources on a remote computer, the local machine and the remote machine must be attached to the same domain, or there needs to be a trust relationship between the domains of the two machines. If either computer is domainless, you cannot use `LogonUser` or SimpleImpersonation to connect to that machine.
How do you do Impersonation in .NET?
[ "", "c#", ".net", "impersonation", "" ]
Is there a simple way to prevent browser from downloading and displaying images, best would be via some magic style tag or javasctipe. The thing is, I'd like to tweak the company's website a bit to be more usable via mobile devices. The company is a gaming one, there's like 5MBs of images on it's main page (and those can't be touched). They alredy display deadly slow on my dsl, and they can be killers to someone who's paying for his GPRS per MB ;) The code of the page is not mine and shouldn't be touched too (in fact, it should be written from scratch, but it's not in my gesture to do it now) :) I was thinking about two solutions: 1) If there was some kind of style-tag (or maybe a javascript? the one that would work on mobile browsers tho) that would prevent browser from downloading images and force to display alt-parameter instead I could simply attach this style if I discovered a user-agent to be some known mobile thing. or 2) I could tweak the webserver a bit to check the User-agent header and if client requests an image (.png, .gif and .jpg) send 404 instead. That has a downside tho - I'd like to allow the user to view images if he actually wants to. It seems that first solution would be best - what you guys think? And is there a javascript way to do it? I could try building document DOM, then get all `<img>` elements, and replace their `src` with some placeholder even but will that work on most mobile browsers (Opera Mini I suppose, the Windows Mobile thingy, the basic Symbian browser from Nokia)? And would playing with document DOM be a good solution on a mobile device (I'm not sure about it's memory-and-cpu requirements to be honest).
You can use htaccess to redirect image requests made from mobile browser users. I haven't tested this but it should work: ``` RewriteCond %{HTTP_USER_AGENT} (nokia¦symbian¦iphone¦blackberry) [NC] RewriteCond %{REQUEST_URI} !^/images/$ RewriteRule (.*) /blank.jpg [L] ``` This code redirects all requests made to files in image folder by nokia,symbian,iphone and blackberry to a blank image file.
I would not rely on javascript or any other client side method with mobile browsers. Most mobile browsers just don't support javascript well enough. Some server side "branching" is probably the way to go. And don't forget to disable the css background images while you're at it.
A way to prevent a mobile browser from downloading and displaying images
[ "", "javascript", "http-headers", "mobile-website", "" ]
Every time I need to do something *N* times inside an algorithm using C# I write this code ``` for (int i = 0; i < N; i++) { ... } ``` Studying Ruby I have learned about method *times()* which can be used with the same semantics like this ``` N.times do ... end ``` Code fragment in C# looks more complex and we should declare useless variable *i*. I tried to write extension method which returns *IEnumerable*, but I am not satisfied with the result because again I have to declare a cycle variable *i*. ``` public static class IntExtender { public static IEnumerable Times(this int times) { for (int i = 0; i < times; i++) yield return true; } } ... foreach (var i in 5.Times()) { ... } ``` Is it possible using some new C# 3.0 language features to make *N* times cycle more elegant?
A slightly briefer version of [cvk's answer](https://stackoverflow.com/questions/177538/any-chances-to-imitate-times-ruby-method-in-c#177551): ``` public static class Extensions { public static void Times(this int count, Action action) { for (int i=0; i < count; i++) { action(); } } public static void Times(this int count, Action<int> action) { for (int i=0; i < count; i++) { action(i); } } } ``` Use: ``` 5.Times(() => Console.WriteLine("Hi")); 5.Times(i => Console.WriteLine("Index: {0}", i)); ```
It is indeed possible with C# 3.0: ``` public interface ILoopIterator { void Do(Action action); void Do(Action<int> action); } private class LoopIterator : ILoopIterator { private readonly int _start, _end; public LoopIterator(int count) { _start = 0; _end = count - 1; } public LoopIterator(int start, int end) { _start = start; _end = end; } public void Do(Action action) { for (int i = _start; i <= _end; i++) { action(); } } public void Do(Action<int> action) { for (int i = _start; i <= _end; i++) { action(i); } } } public static ILoopIterator Times(this int count) { return new LoopIterator(count); } ``` Usage: ``` int sum = 0; 5.Times().Do( i => sum += i ); ``` Shamelessly stolen from <http://grabbagoft.blogspot.com/2007/10/ruby-style-loops-in-c-30.html>
Any chances to imitate times() Ruby method in C#?
[ "", "c#", "ruby", "language-features", "cycle", "" ]
I'm writing a WinForms app which has two modes: console or GUI. Three projects within the same solution, one for the console app, one for the UI forms and the third to hold the logic that the two interfaces will both connect too. The Console app runs absolutely smoothly. A model which holds the user-selections, it has an `IList<T>` where T is a local object, `Step`, which implements `INotifyPropertyChanged`, so in the UI this is mounted on to a DataGridView. All is fine at runtime, the initial state of the objects is reflected on the screen. Each of the `Step` objects is a task which is performed in turn; some of the properties will change, being reflected back to the IList and passed on to the DataGridView. This action in the UI versions is done by creating a BackgroundWorker raising events back to the UI. The `Step` does it thing and generates a `StepResult` object which is an enumerated type indicating a result (e.g. Running, NotRun, OK, NotOK, Caveat) and a string to indicate a message (because the step ran but not quite as expected, i.e. with a Caveat). Normally the actions will involve a database interaction, but in debug mode I randomly generate a result. If the message is null, there's never a problem, but if I generate a response like this: ``` StepResult returnvalue = new StepResult(stat, "completed with caveat") ``` I get an error saying that the DataGridView was being accessed from a thread other than the thread it was created on. (I'm passing this through a custom handler which should handle the invoking when required - maybe it doesn't?) Then if I generate a unique response, e.g. using a random number `r`: ``` StepResult returnvalue = new StepResult(stat, r.ToString()); ``` the actions succeed with no problem, the numbers are written cleanly to the DataGridView. I'm baffled. I'm assuming it's somehow a string literal problem, but can anyone come up with a clearer explanation?
Since you are doing UI binding via event subscription, [you might find this helpful](http://groups.google.co.uk/group/microsoft.public.dotnet.languages.csharp/browse_thread/thread/214e55884b16f4d9/f12a3c5980567f06#f12a3c5980567f06); it is an example I wrote a while ago that shows how to subclass `BindingList<T>` so that the notifications are marshalled to the UI thread automatically. If there is no sync-context (i.e. console mode), then it reverts back to the simple direct invoke, so there is no overhead. When running in UI thread, note that this essentially uses `Control.Invoke`, which itself just runs the delegate directly if it is on the UI thread. So there is only any switch if the data is being edited from a non-UI thread - juts what we want ;-p
You've answered your own quesion:- > I get an error saying that the DataGridView was being accessed from a thread other than the thread it was created on. WinForms insists that all actions performed on forms and controls are done in the context of the thread the form was created in. The reason for this is complex, but has a lot to do with the underlying Win32 API. For details, see the various entries on [The Old New Thing](http://blogs.msdn.com/oldnewthing/) blog. What you need to do is use the InvokeRequired and Invoke methods to ensure that the controls are always accessed from the same thread (pseudocodeish): ``` object Form.SomeFunction (args) { if (InvokeRequired) { return Invoke (new delegate (Form.Somefunction), args); } else { return result_of_some_action; } } ```
Strange cross-threading UI errors
[ "", "c#", "string", "literals", "multithreading", "" ]
Specifically, I have a model that has a field like this ``` pub_date = models.DateField("date published") ``` I want to be able to easily grab the object with the most recent `pub_date`. What is the easiest/best way to do this? Would something like the following do what I want? ``` Edition.objects.order_by('pub_date')[:-1] ```
``` obj = Edition.objects.latest('pub_date') ``` You can also simplify things by putting [`get_latest_by`](http://docs.djangoproject.com/en/dev/ref/models/options/#get-latest-by) in the model's Meta, then you'll be able to do ``` obj = Edition.objects.latest() ``` See [the docs](http://docs.djangoproject.com/en/dev/ref/models/querysets/#latest-field-name-none) for more info. You'll probably also want to set the [`ordering`](http://docs.djangoproject.com/en/dev/ref/models/options/#ordering) Meta option.
Harley's answer is the way to go for the case where you want the latest according to some ordering criteria for particular Models, as you do, but the general solution is to reverse the ordering and retrieve the first item: ``` Edition.objects.order_by('-pub_date')[0] ```
In django, how do I sort a model on a field and then get the last item?
[ "", "sql", "django", "sorting", "django-models", "" ]
This is something that's been bothering me a while and there just has to be a solution to this. Every time I call ShellExecute to open an external file (be it a document, executable or a URL) this causes a very long lockup in my program before ShellExecute spawns the new process and returns. Does anyone know how to solve or work around this? EDIT: And as the tags might indicate, this is on Win32 using C++.
Are you multithreaded? I've seen issues with opening files with ShellExecute. Not executables, but files associated an application - usually MS Office. Applications that used DDE to open their files did some of broadcast of a message to all threads in all (well, I don't know if it was *all*...) programs. Since I wasn't pumping messages in worker threads in my application I'd hang the shell (and the opening of the file) for some time. It eventually timed out waiting for me to process the message and the application would launch and open the file. I recall using PeekMessage in a loop to just remove messages in the queue for that worker thread. I always assumed there was a way to avoid this in another way, maybe create the thread differently as to never be the target of messages? --- **Update** It must have not just been any thread that was doing this but one servicing a window. ***Raymond [(link 1)](http://blogs.msdn.com/oldnewthing/archive/2006/02/10/529525.aspx) knows all [(link 2)](http://blogs.msdn.com/oldnewthing/archive/2005/06/27/432303.aspx)***. I bet either CoInitialize (single threaded apartment) or something in MFC created a hidden window for the thread.
I don't know what is causing it, but Mark Russinovich (of sysinternal's fame) has a really great blog where he explains how to debug these kinds of things. A good one to look at for you would be [The Case of the Delayed Windows Vista File Open Dialogs](http://blogs.technet.com/markrussinovich/archive/2006/11/27/532465.aspx), where he debugged a similar issue using only process explorer (it turned out to be a problem accessing the domain). You can of course do similar things using a regular windows debugger. You problem is probably not the same as his, but using these techniques may help you get closer to the source of the problem. I suggest invoking the `CreateProcess` call and then capturing a few stack traces and seeing where it appears to be hung. [The Case of the Process Startup Delays](http://blogs.technet.com/markrussinovich/archive/2006/08/31/453100.aspx) might be even more relevant for you.
Getting rid of the evil delay caused by ShellExecute
[ "", "c++", "winapi", "shellexecute", "" ]
I have Eclipse 3.3.2 with PDT doing PHP development. All projects that I create, even SVN projects have code completion. Now I just opened another SVN project and it has no code completion or PHP templates (CTRL-space does nothing in that project). However, I can open the other projects and code completion all work in them. Why would code completion and templates be "off" in just one project and how can I turn it back on?
Maybe Eclipse doesn't understand the project has a "PHP nature". Try comparing the .project file on both projects to look for differences. It should contain something like: ``` <natures> <nature>org.eclipse.php.core.PHPNature</nature> </natures> ``` The .project file will be in your workspace under the project directories.
Look out for the file .buildpath in your project... put this line between the tag: `<buildpathentry kind="con" path="org.eclipse.php.core.LANGUAGE"/>` Save it and restart eclipse. Now everything should be OK... This worked for me. :)
Why does Eclipse code completion not work on some projects?
[ "", "php", "eclipse", "eclipse-pdt", "eclipse-3.3", "" ]
Lucene is an excellent search engine, but the .NET version is behind the official Java release (latest stable .NET release is 2.0, but the latest Java Lucene version is 2.4, which has more features). How do you get around this?
One way I found, which was surprised could work: Create a .NET DLL from a Java .jar file! Using [IKVM](http://www.ikvm.net/) you can [download Lucene](http://www.apache.org/dyn/closer.cgi/lucene/java/), get the .jar file, and run: ``` ikvmc -target:library <path-to-lucene.jar> ``` which generates a .NET dll like this: lucene-core-2.4.0.dll You can then just reference this DLL from your project and you're good to go! There are some java types you will need, so also reference IKVM.OpenJDK.ClassLibrary.dll. Your code might look a bit like this: ``` QueryParser parser = new QueryParser("field1", analyzer); java.util.Map boosts = new java.util.HashMap(); boosts.put("field1", new java.lang.Float(1.0)); boosts.put("field2", new java.lang.Float(10.0)); MultiFieldQueryParser multiParser = new MultiFieldQueryParser (new string[] { "field1", "field2" }, analyzer, boosts); multiParser.setDefaultOperator(QueryParser.Operator.OR); Query query = multiParser.parse("ABC"); Hits hits = isearcher.search(query); ``` I never knew you could have Java to .NET interoperability so easily. The best part is that C# and Java is "almost" source code compatible (where Lucene examples are concerned). Just replace `System.Out` with `Console.Writeln` :). ======= Update: When building libraries like the Lucene highlighter, make sure you reference the core assembly (else you'll get warnings about missing classes). So the highlighter is built like this: ``` ikvmc -target:library lucene-highlighter-2.4.0.jar -r:lucene-core-2.4.0.dll ```
Download the source and build it. I did this just last weekend and it was easy. No problem at all. The source is at version 2.3.1. I'm subscribed to the mailing list and judging from it, Lucene.Net is being developed actively.
How do you run Lucene on .net?
[ "", "java", ".net", "search", "indexing", "lucene", "" ]
I was just wondering, since the **sealed** keyword's existence indicates that it's the class author's decision as to whether other classes are allowed to inherit from it, why aren't classes sealed by default, with some keyword to mark them explicitly as extensible? I know it's somewhat different, but access modifiers work this way. With the default being restrictive and fuller access only being granted with the insertion of a keyword. There's a large chance that I haven't thought this through properly, though, so please be humane!
**In my opinion** there should be no default syntax, that way you always write explicitly what you want. This forces the coder to understand/think more. If you want a class to be inheritable then you write ``` public extensible class MyClass ``` otherwise ``` public sealed class MyClass ``` BTW I think the same should go with access modifiers, disallow default access modifiers.
I'd say it was just a mistake. I know many people (including myself) who believe that classes should indeed be sealed by default. There are at least a couple of people in the C# design team in that camp. The pendulum has swung somewhat away from inheritance since C# was first designed. (It has its place, of course, but I find myself using it relatively rarely.) For what it's worth, that's not the only mistake along the lines of being too close to Java: personally I'd rather Equals and GetHashCode weren't in object, and that you needed specific Monitor instances for locking too...
Why aren't classes sealed by default?
[ "", "c#", "inheritance", "sealed", "" ]
The code at the end produces a compile error: ``` NotApplicable.java:7: run() in cannot be applied to (int) run(42); ^ 1 error ``` The question is why? Why does javac think I am calling run(), and does not find run(int bar)? It correctly called foo(int bar). Why do I have to use NotApplicable.this.run(42);? Is it a bug? ``` public class NotApplicable { public NotApplicable() { new Runnable() { public void run() { foo(42); run(42); // uncomment below to fix //NotApplicable.this.run(42); } }; } private void run(int bar) { } public void foo(int bar) { } } ```
The explanation for the behavior of your code sample is that `this` is defined to be the class that you are currently "most" inside of. In this case, you are "most" inside the anonymous inner class that subclasses runnable and there is no method which matches `run(int)`. To broaden your search you specify which `this` you want to use by stating `NotApplicable.this.run(42)`. The jvm will evaluate as follows: `this` -> currently executing instance of `Runnable` with method `run()` `NotApplicable.this` -> currently executing instance of `NotApplicable` with method `run(int)` The compiler will look up the nesting tree for the first method that matches the NAME of the method. *–Thanks to DJClayworth for this clarification* The anonymous inner class is not a subclass of the outer class. Because of this relationship, both the inner class and the outer class should be able to have a method with exactly the same signature and the innermost code block should be able to identify which method it wants to run. ``` public class Outer{ public Outer() { new Runnable() { public void printit() { System.out.println( "Anonymous Inner" ); } public void run() { printit(); // prints "Anonymous Inner" this.printit(); //prints "Anonymous Inner" // would not be possible to execute next line without this behavior Outer.this.printit(); //prints "Outer" } }; } public void printit() { System.out.println( "Outer" ); } } ```
As far as I recall the rules for selecting a method to run between nested classes are approximately the same as the rules for selecting a method in an inheritance tree. That means that what we are getting here is not overloading, it's hiding. The difference between these is crucial to understanding methods in inheritance. If your Runnable was declared as a subclass, then the run() method would hide the run(int) method in the parent. Any call to run(...) would try to execute the one on Runnable, but would fail if it couldn't match signatures. Since foo is not declared in the child then the one on the parent is called. The same principle is happening here. Look up references to "method hiding" and it should be clear.
Why can't I call a method outside of an anonymous class of the same name
[ "", "java", "methods", "javac", "anonymous-class", "" ]
Hopefully I can do the problem justice, because it was too difficult to summarise it in the title! (suggestions are welcome in the comments) Right, so here's my table: ``` Tasks task_id (number) job_id (number) to_do_by_date (date) task_name (varchar / text) status (number) completed_date (date) ``` for arguments sake let's make the values of status: ``` 1 = New 2 = InProgress 3 = Done ``` and what I'm having trouble trying to do is create a query that pulls back all of the tasks: * where any of the tasks for a `job_id` have a `status` <> Done + except where all tasks for a `job_id` are are done, but one or more tasks have a `completed_date` of today * ordered by the `to_be_done_by` date, but grouping all of the job\_id tasks together + so the `job_id` with the next `to\_do\_by\_date' task is shown first some information about the data: * a `job_id` can have an arbitrary number of tasks **Here's an example of the output I'm trying to get:** ``` task_id job_id to_do_by_date task_name status completed_date 1 1 yesterday - 3 yesterday 2 1 today - 3 today 3 2 now - 3 today 4 2 2 hours time - 2 {null} 5 2 4 hours time - 2 {null} 6 2 tomorrow - 1 {null} 7 3 3 hours time - 2 {null} 8 3 tomorrow - 1 {null} 9 3 tomorrow - 1 {null} ``` I'm using Oracle 10g, so answers for Oracle or ANSI SQL, or a hint for how to approach this would be ideal, and I can create Views or wrap this in a Stored Procedure to offload logic from the application if your solution calls for it. here's a sql script that will create the example test data shown above: ``` create table tasks (task_id number, job_id number, to_do_by_date date, task_name varchar2(50), status number, completed_date date); insert into tasks values (0,0,sysdate -2, 'Job 0, Task 1 - dont return!', 3, sysdate -2); insert into tasks values (1,1,sysdate -1, 'Job 1, Task 1', 3, sysdate -1); insert into tasks values (2,1,sysdate -2/24, 'Job 1, Task 2', 3, sysdate -2/24); insert into tasks values (3,2,sysdate, 'Job 2, Task 1', 3, sysdate); insert into tasks values (4,2,sysdate +2/24, 'Job 2, Task 2', 2, null); insert into tasks values (5,2,sysdate +4/24, 'Job 2, Task 3', 2, null); insert into tasks values (6,2,sysdate +1, 'Job 2, Task 4', 1, null); insert into tasks values (7,3,sysdate +3/24, 'Job 3, Task 1', 2, null); insert into tasks values (8,3,sysdate +1, 'Job 3, Task 2', 1, null); insert into tasks values (9,3,sysdate +1, 'Job 3, Task 3', 1, null); commit; ``` Many, many thanks for your help :o)
Obviously you will have to fix this up a bit but I hope you get the idea. ``` SELECT task_id, job_id, to_do_by_date, task_name, status, completed_date FROM Tasks WHERE job_id IN ( SELECT job_id FROM Tasks WHERE status <> 'Done' GROUP BY job_id) OR job_id IN ( SELECT job_id FROM Tasks WHERE status = 'Done' AND completed_date = 'Today' AND job_id NOT IN (SELECT job_id FROM Tasks WHERE status <> 'Done' GROUP BY job_id) GROUP BY job_id) ORDER BY job_id, to_do_by_date ```
I agree with Justin -- I don't get why 2 is returned. Here's a query using analytic functions to return the right rows according to the logic description. ``` select * from ( select t.*, min(status) over (partition by job_id) min_status_over_job, max(status) over (partition by job_id) max_status_over_job, sum(case when trunc(completed_date) = trunc(sysdate)-1 then 1 else 0 end) over (partition by job_id) num_complete_yest from tasks t ) where max_status_over_job < 3 or (min_status_over_job = 3 and num_complete_yest > 0) / ```
SQL Query Help - task ordering, grouping and status + date conditions problem
[ "", "sql", "oracle", "" ]
There's a lot of advice out there that you shouldn't expose your fields publically, and instead use trivial properties. I see it over & over. I understand the arguments, but [I don't think it's good advice in most cases](https://stackoverflow.com/questions/174198/c35-automatic-properties-why-not-access-the-field-directly#205567). Does anyone have an example of a time when it really mattered? When writing a trivial property made something important possible in the future (or when failing to use one got them in to real trouble)? EDIT: The DataBinding argument is correct, but not very interesting. It's a bug in the DataBinding code that it won't accept public fields. So, we have to write properties to work around that bug, not because properties are a wise class design choice. EDIT: To be clear, I'm looking for real-world examples, not theory. A time when it really mattered. EDIT: The ability to set a breakpoint on the setter seems valuable. Designing my code for the debugger is unfortunate: I'd rather the debugger get smarter, but given the debugger we have, I'll take this ability. Good stuff.
It may be hard to make code work in an uncertain future, but that's no excuse to be lazy. Coding a property over a field is convention and it's pragmatic. Call it defensive programming. Other people will also complain that there's a speed issue, but the JIT'er is smart enough to make it just about as fast as exposing a public field. Fast enough that I'll never notice. Some non-trivial things that come to mind 1. A public field is totally public, you can not impose read-only or write-only semantics 2. A property can have have different `get` versus `set` accessibility (e.g. public get, internal set) 3. You can not override a field, but you can have virtual properties. 4. Your class has no control over the public field 5. Your class can control the property. It can limit setting to allowable range of values, flag that the state was changed, and even lazy-load the value. 6. Reflection semantics differ. A public field is not a property. 7. No databinding, as others point out. (It's only a bug to you. - I can understand Why .net framework designers do not support patterns they are not in favour of.) 8. You can not put a field on an interface, but you can put a property on an interface. 9. Your property doesn't even need to store data. You can create a facade and dispatch to a contained object. You only type an extra 13 characters for correctness. That hardly seems like speculative generality. There is a semantic difference, and if nothing else, a property has a different semantic meaning and is far more flexible than a public field. ``` public string Name { get; set; } public string name; ``` I do recall one time when first using .net I coded a few classes as just fields, and then I needed to have them as properties for some reason, and it was a complete waste of time when I could have just done it right the first time. So what reasons do you have for *not* following convention? Why do you feel the need to swim upstream? What has it saved you by not doing this?
I used to think the same thing, Jay. Why use a property if it's only there to provide *direct* access to a private member? If you can describe it as an autoproperty, having a property at all rather than a field seemed kind of silly. Even if you ever need to change the implementation, you could always just refactor into a real property later and any dependent code would still work, right?. Well, maybe not. You see, I've recently seen the light on trivial properties, so maybe now I can help you do the same. What finally convinced me was the fairly obvious point (in retrospect) that properties in .Net are just syntactic sugar for getter and setter methods, and those methods have a *different name* from the property itself. Code in the same assembly will still work, because you have to recompile it at the same time anyway. But any code in a different assembly that links to yours will *fail* if you refactor a field to a property, unless it's recompiled against your new version at the same time. If it's a property from the get-go, everything is still good.
Have trivial properties ever saved your bacon?
[ "", "c#", ".net", "" ]
I have a simple website I'm testing. It's running on localhost and I can access it in my web browser. The index page is simply the word "running". `urllib.urlopen` will successfully read the page but `urllib2.urlopen` will not. Here's a script which demonstrates the problem (this is the actual script and not a simplification of a different test script): ``` import urllib, urllib2 print urllib.urlopen("http://127.0.0.1").read() # prints "running" print urllib2.urlopen("http://127.0.0.1").read() # throws an exception ``` Here's the stack trace: ``` Traceback (most recent call last): File "urltest.py", line 5, in <module> print urllib2.urlopen("http://127.0.0.1").read() File "C:\Python25\lib\urllib2.py", line 121, in urlopen return _opener.open(url, data) File "C:\Python25\lib\urllib2.py", line 380, in open response = meth(req, response) File "C:\Python25\lib\urllib2.py", line 491, in http_response 'http', request, response, code, msg, hdrs) File "C:\Python25\lib\urllib2.py", line 412, in error result = self._call_chain(*args) File "C:\Python25\lib\urllib2.py", line 353, in _call_chain result = func(*args) File "C:\Python25\lib\urllib2.py", line 575, in http_error_302 return self.parent.open(new) File "C:\Python25\lib\urllib2.py", line 380, in open response = meth(req, response) File "C:\Python25\lib\urllib2.py", line 491, in http_response 'http', request, response, code, msg, hdrs) File "C:\Python25\lib\urllib2.py", line 418, in error return self._call_chain(*args) File "C:\Python25\lib\urllib2.py", line 353, in _call_chain result = func(*args) File "C:\Python25\lib\urllib2.py", line 499, in http_error_default raise HTTPError(req.get_full_url(), code, msg, hdrs, fp) urllib2.HTTPError: HTTP Error 504: Gateway Timeout ``` Any ideas? I might end up needing some of the more advanced features of `urllib2`, so I don't want to just resort to using `urllib`, plus I want to understand this problem.
Sounds like you have proxy settings defined that urllib2 is picking up on. When it tries to proxy "127.0.0.01/", the proxy gives up and returns a 504 error. From [Obscure python urllib2 proxy gotcha](http://kember.net/articles/obscure-python-urllib2-proxy-gotcha): ``` proxy_support = urllib2.ProxyHandler({}) opener = urllib2.build_opener(proxy_support) print opener.open("http://127.0.0.1").read() # Optional - makes this opener default for urlopen etc. urllib2.install_opener(opener) print urllib2.urlopen("http://127.0.0.1").read() ```
Does calling urlib2.open first followed by urllib.open have the same results? Just wondering if the first call to open is causing the http server to get busy causing the timeout?
urllib.urlopen works but urllib2.urlopen doesn't
[ "", "python", "urllib2", "urllib", "" ]
I've got a file whose format I'm altering via a python script. I have several camel cased strings in this file where I just want to insert a single space before the capital letter - so "WordWordWord" becomes "Word Word Word". My limited regex experience just stalled out on me - can someone think of a decent regex to do this, or (better yet) is there a more pythonic way to do this that I'm missing?
You could try: ``` >>> re.sub(r"(\w)([A-Z])", r"\1 \2", "WordWordWord") 'Word Word Word' ```
If there are consecutive capitals, then Gregs result could not be what you look for, since the \w consumes the caracter in front of the captial letter to be replaced. ``` >>> re.sub(r"(\w)([A-Z])", r"\1 \2", "WordWordWWWWWWWord") 'Word Word WW WW WW Word' ``` A look-behind would solve this: ``` >>> re.sub(r"(?<=\w)([A-Z])", r" \1", "WordWordWWWWWWWord") 'Word Word W W W W W W Word' ```
A pythonic way to insert a space before capital letters
[ "", "python", "regex", "text-files", "" ]
I currently use Notepad++ for most of my development. I have been checking out other, more full-featured options and would like to switch (I'm in particular a fan of Aptana so far) but there is one thing about Notepad++ that I really like and I haven't been able to get so far. My current workflow is something like this: [Workflow](http://evanalyze.com/images/workflow) (I tried to embed this image and it showed up in previews but not in the post, sorry) [Workflow http://evanalyze.com/images/workflow.jpg](http://evanalyze.com/images/workflow.jpg) The process is this: 1. Download file from web server 2. Make edits in NP++ 3. Save (this automatically saves a local copy in my default directory, which is also the folder I have setup using Subversion with Tourtise SVN) 4. When I want to commit a change to SVN, go through the local folder that has an up to date copy What I can't figure out how to do with Aptana is automatically store a local copy of a file I download from my server, edit and save back to the server. Is there some way to do this? If so, that would solve my problem immediately. Other options would be a suggestion for a better way to manage the relationship between my server, my editor and my SVN repository. I know Aptana can access my SVN repository too. Is there an easy way to commit changes from within Aptana when I want to (which means I could take Tourtise out of the equation I guess)? Any suggestions appreciated. Thanks.
I think you're doing things a bit strange. You already have all your information in an SVN repository, so why not take advantage of that? You keep a working copy on your computer for development and testing. Save and commit your changes to SVN. On your server, do an SVN `export` (or `checkout`, with appropriate server rules to block web access to the `.svn` folders), and you're sweet! ``` ---------------------- ------------ --------------- | Local Working Copy | <---> | SVN Repo | <---> | Live server | ---------------------- ------------ --------------- ``` This means you never have to worry about FTP, or have to figure out which files have been changed locally and hence need to be updated.
Not too sure but I found [PhpEd](http://www.nusphere.com/) better than Zend for this kind of stuff - especially easy save to FTP.
PHP IDE--Want to sync local storage with FTP
[ "", "php", "ide", "tortoisesvn", "notepad++", "aptana", "" ]
I want to do something like this: ``` List<Animal> animals = new ArrayList<Animal>(); for( Class c: list_of_all_classes_available_to_my_app() ) if (c is Animal) animals.add( new c() ); ``` So, I want to look at all of the classes in my application's universe, and when I find one that descends from Animal, I want to create a new object of that type and add it to the list. This allows me to add functionality without having to update a list of things. I can avoid the following: ``` List<Animal> animals = new ArrayList<Animal>(); animals.add( new Dog() ); animals.add( new Cat() ); animals.add( new Donkey() ); ... ``` With the above approach, I can simply create a new class that extends Animal and it'll get picked up automatically. UPDATE: 10/16/2008 9:00 a.m. Pacific Standard Time: This question has generated a lot of great responses -- thank you. ~~From the responses and my research, I've found that what I really want to do is just not possible under Java. There are approaches, such as ddimitrov's ServiceLoader mechanism that can work -- but they are very heavy for what I want, and I believe I simply move the problem from Java code to an external configuration file.~~ **Update 5/10/19** (11 years later!) There are now several libraries that can help with this according to @IvanNik's [answer](https://stackoverflow.com/a/9240969/9648) [org.reflections](https://github.com/ronmamo/reflections) looks good. Also [ClassGraph](https://github.com/classgraph/classgraph) from @Luke Hutchison's [answer](https://stackoverflow.com/a/51625104/9648) looks interesting. There are several more possibilities in the answers as well. Another way to state what I want: a static function in my Animal class finds and instantiates all classes that inherit from Animal -- without any further configuration/coding. If I have to configure, I might as well just instantiate them in the Animal class anyway. I understand that because a Java program is just a loose federation of .class files that that's just the way it is. Interestingly, it seems this is [fairly trivial](http://my.safaribooksonline.com/0596003390/csharpckbk-CHP-12-SECT-8) in C#.
I use [org.reflections](https://github.com/ronmamo/reflections): ``` Reflections reflections = new Reflections("com.mycompany"); Set<Class<? extends MyInterface>> classes = reflections.getSubTypesOf(MyInterface.class); ``` Another example: ``` public static void main(String[] args) throws IllegalAccessException, InstantiationException { Reflections reflections = new Reflections("java.util"); Set<Class<? extends List>> classes = reflections.getSubTypesOf(java.util.List.class); for (Class<? extends List> aClass : classes) { System.out.println(aClass.getName()); if(aClass == ArrayList.class) { List list = aClass.newInstance(); list.add("test"); System.out.println(list.getClass().getName() + ": " + list.size()); } } } ```
The Java way to do what you want is to use the [ServiceLoader](http://java.sun.com/javase/6/docs/api/java/util/ServiceLoader.html) mechanism. Also many people roll their own by having a file in a well known classpath location (i.e. /META-INF/services/myplugin.properties) and then using [ClassLoader.getResources()](http://docs.oracle.com/javase/8/docs/api/java/lang/ClassLoader.html#getResources-java.lang.String-) to enumerate all files with this name from all jars. This allows each jar to export its own providers and you can instantiate them by reflection using Class.forName()
At runtime, find all classes in a Java application that extend a base class
[ "", "java", "reflection", "inheritance", "" ]
What are good reasons to prohibit inheritance in Java, for example by using final classes or classes using a single, private parameterless constructor? What are good reasons of making a method final?
Your best reference here is Item 19 of Joshua Bloch's excellent book "Effective Java", called "Design and document for inheritance or else prohibit it". (It's item 17 in the second edition and item 15 in the first edition.) You should really read it, but I'll summarize. The interaction of inherited classes with their parents can be surprising and unpredictable if the ancestor wasn't designed to be inherited from. Classes should therefore come in two kinds: 1. Classes *designed to be \*\*extended*\*\*, and with enough documentation to describe how it should be done 2. Classes *marked \*\*final*\*\* If you are writing purely internal code, this may be a bit of overkill. However, the extra effort involved in adding five characters to a class file is very small. If you are writing only for internal consumption, then a future coder can always remove the 'final' - you can think of it as a warning saying "this class was not designed with inheritance in mind".
You might want to make a method final so that overriding classes can't change behavior that is counted on in other methods. Methods called in constructors are often declared final so you don't get any unpleasant surprises when creating objects.
Good reasons to prohibit inheritance in Java?
[ "", "java", "inheritance", "final", "" ]
What is the differences and similarities between Domain Specific Languages (DSL) and Domain Driven Design (DDD)?
Domain Driven Design (DDD) is a way of thinking and communicating about the problems and its solutions. Domain Specific Language (DSL) is a way of writing code. They're similar because they both start with the word "domain". That's it, I guess. :-)
Domain-Driven Design emphasizes the role of the problem domain as you create the fundamental vocabulary, concepts, and object model for the system being designed. A Domain-Specific Language is a notation for specifying or implementing specific parts of the system, oriented to the needs of the practitioner in that domain (i.e. minimizing the "programmerese" aspects of most programming or specification languages).
Domain Specific Languages (DSL) and Domain Driven Design (DDD)
[ "", "c#", ".net", "domain-driven-design", "dsl", "" ]
I had a little discussion with a friend about the usage of collections in return/input values of a method. He told me that we have to use - the most derived type for return values. - the least derived type for input parameters. So, it means that, for example, a method has to get a ReadOnlyCollection as parameter, and as return a List. Moreover, he said that we must not use List or Dictionary in publics API, and that we have to use, instead Collection, ReadOnlyCollection, ... So, in the case where a method is public, its parameters and its return values must be Collection, ReadOnlyCollection, ... Is it right ?
Regarding input parameters, it's generally more flexible to use the least specific type. For example, if all your method is going to do is enumerate the items in a collection passed as an argument, it's more flexible to accept IEnumerable<T>. For example, consider a method "ProcessCustomers" that accepts a parameter that is a collection of customers: ``` public void ProcessCustomers(IEnumerable<Customer> customers) { ... implementation ... } ``` If you declare the parameter as IEnumerable<Customer>, your callers can easily pass in a subset of a collection, using code like the following (pre-NET 3.5: with .NET 3.5 you could use lambda expressions): ``` private IEnumerable<Customer> GetCustomersByCountryCode(IEnumerable<Customer> customers, int countryCode) { foreach(Customer c in customers) { if (c.CountryCode == countryCode) yield return c; } } ... ProcessCustomers(GetCustomersByCountryCode(myCustomers, myCountryCode); ... ``` In general MS guidelines recommend not exposing List<T>. For a discussion of why this is so, see [this blog entry](http://blogs.msdn.com/fxcop/archive/2006/04/27/faq-why-does-donotexposegenericlists-recommend-that-i-expose-collection-lt-t-gt-instead-of-list-lt-t-gt-david-kean.aspx) from the Code Analysis (FxCop) team.
I tend to agree with not returning or using List or Dictionary as parameters in API's because it really limits the developer targeting the API. Instead returning or passing IEnumerable<> works really well. Of coarse, all of this depends on the application. Just my opinion.
What are the code convention for parameters/return values (collections)
[ "", "c#", "" ]
How can I programmatically lock/unlock, or otherwise prevent/enable editing, a source file on Linux using C++. I want to be able to lock source file so that if I open it in an editor it will not allow me to save back to the same source file. I am thinking of maybe changing the permissions to read-only (and change it back to read-write later): how do I do that from C++?
Try man fchmod: ``` NAME chmod, fchmod - change permissions of a file SYNOPSIS #include <sys/types.h> #include <sys/stat.h> int chmod(const char *path, mode_t mode); int fchmod(int fildes, mode_t mode); ```
Why aren't you using a source code management tool like CVS or Subversion? CVS does nice locking (so does Subversion). More importantly, you have the history of changes. Better still (with CVS anyway) you have to make the step of doing a "checkout" to make the file writeable.
Lock / Prevent edit of source files on Linux using C++
[ "", "c++", "linux", "file-locking", "" ]
I know that I can insert multiple rows using a single statement, if I use the syntax in [this answer](https://stackoverflow.com/questions/39576/best-way-to-do-multi-row-insert-in-oracle#39602). However, one of the values I am inserting is taken from a sequence, i.e. ``` insert into TABLE_NAME (COL1,COL2) select MY_SEQ.nextval,'some value' from dual union all select MY_SEQ.nextval,'another value' from dual ; ``` If I try to run it, I get an ORA-02287 error. Is there any way around this, or should I just use a lot of INSERT statements? EDIT: If I have to specify column names for all other columns other than the sequence, I lose the original brevity, so it's just not worth it. In that case I'll just use multiple INSERT statements.
This works: ``` insert into TABLE_NAME (COL1,COL2) select my_seq.nextval, a from (SELECT 'SOME VALUE' as a FROM DUAL UNION ALL SELECT 'ANOTHER VALUE' FROM DUAL) ```
It does not work because sequence does not work in following scenarios: * In a WHERE clause * In a GROUP BY or ORDER BY clause * In a DISTINCT clause * Along with a UNION or INTERSECT or MINUS * In a sub-query Source: <http://www.orafaq.com/wiki/ORA-02287> However this does work: ``` insert into table_name (col1, col2) select my_seq.nextval, inner_view.* from (select 'some value' someval from dual union all select 'another value' someval from dual) inner_view; ``` --- Try it out: ``` create table table_name(col1 varchar2(100), col2 varchar2(100)); create sequence vcert.my_seq start with 1 increment by 1 minvalue 0; select * from table_name; ```
How can I insert multiple rows into oracle with a sequence value?
[ "", "sql", "oracle", "" ]
Is it possible to prevent the browser from following redirects when sending XMLHttpRequest-s (i.e. to get the redirect status code back and handle it myself)?
Not according to [the W3C standard for the XMLHttpRequest object](http://dvcs.w3.org/hg/xhr/raw-file/tip/Overview.html#infrastructure-for-the-send%28%29-method) (emphasis added): > If the response is an HTTP redirect: > > > If the origin of the URL conveyed by the Location header is same origin > > with the XMLHttpRequest origin and the > > redirect does not violate infinite > > loop precautions, **transparently > > follow the redirect** while observing > > the same-origin request event rules. They were [considering](http://www.w3.org/TR/2008/WD-XMLHttpRequest-20080415/#notcovered) it for a future release: > This specification does not include > the following features which are being > considered for a future version of > this specification: > > * Property to disable following redirects; but the [latest](http://www.w3.org/TR/XMLHttpRequest/) specification no longer mentions this.
The new [Fetch API](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API) supports different modes of redirect handling: `follow`, `error`, and `manual`, but I can't find a way to view the new URL or the status code when the redirection has been canceled. You just can stop the redirection itself, and then it looks like an error (empty response). If that's all you need, you are good to go. Also you should be aware that the requests made via this API are not cancelable [yet](https://github.com/whatwg/fetch/issues/27). *They [are](https://stackoverflow.com/a/46785332) now.* As for XMLHttpRequest, you can `HEAD` the server and inspect whether the URL has changed: ``` var http = new XMLHttpRequest(); http.open('HEAD', '/the/url'); http.onreadystatechange = function() { if (this.readyState === this.DONE) { console.log(this.responseURL); } }; http.send(); ``` You won't get the status code, but will find the new URL without downloading the whole page from it.
Prevent redirection of XMLHttpRequest
[ "", "javascript", "ajax", "xmlhttprequest", "" ]
I was making the following call: ``` result = RegOpenKeyEx(key, s, 0, KEY_READ, &key); ``` (C++, Visual Studio 5, Vista 64bit). It is failing with error code 2 ("File not found") even though "`regedit`" shows that the key exists. This code has always worked on 32bit XP. Why is it "file not found" when it clearly is there?
I discovered that I could solve my problem using the flag: `KEY_WOW64_64KEY` , as in: ``` result = RegOpenKeyEx(key, s, 0, KEY_READ|KEY_WOW64_64KEY, &key); ``` For a full explanation: [32-bit and 64-bit Application Data in the Registry](http://msdn.microsoft.com/en-us/library/ms724072(VS.85).aspx)
On a Windows 64-bit system the Registry is actually divided into two parts. One section is used by 64-bit processes, and one part by 32-bit processes. For example, if a 32-bit application programatically writes to what it believes is HKLM\SOFTWARE\Company\Application, it's actually redirected by the WoW64-layer to HKLM\SOFTWARE\Wow6432Node\Company\Application. So when you run your 32-bit application and call RegOpenKeyEx it's actually working against the Wow6432Node\ folder, and not the regular \SOFTWARE node.
Why is RegOpenKeyEx() returning error code 2 on Vista 64bit?
[ "", "c++", "winapi", "windows-vista", "registry", "wow64", "" ]
In our data access layer at work we have this standard implementation where the class is accessed through a singleton public property which looks something like this: ``` public static CustomerController Instance { get { lock(singletonLock) { if( _instance == null ) { _instance = new CustomerController(); } return _instance; } } } ``` now, I get what the code is doing, but I was wondering why you would do this over just creating an instance of the class each time it is used?
EDIT: Oh whoops I didn't catch the "Data Access Layers" part. But I have an example of that too: If your multithreaded app funnels all of its' database calls through a singleton class, only one thread will ever access the database at once, avoiding race conditions. If you have a logging mechanism in a multi-threaded application that you use to spit out all exceptions and just write info in (especially for services, or apps that are always running, printing out statuses whenever stuff happens), you will run into file-locking issues. I use a singleton logger class, so that only one thread ever will have access to the Logger, and the rest will wait until the Logger is free to write their line in the text file. There are lots of cool reasons to use a singleton, but I was like you and had no idea what they were FOR until I ran into this issue with file access in a multithreaded app.
You may wish to do this also, its double checked locking, it will speed up access to your singleton ``` public static CustomerController Instance { get { if( _instance == null ) { lock(singletonLock) { if( _instance == null ) { _instance = new CustomerController(); } } } return _instance; } } ```
Singleton Data Access Layers
[ "", "c#", "design-patterns", "singleton", "" ]
As far as I know there's no way to hint the c# compiler to inline a particular function and I guess it's like that by design. I also think that not letting the programmer to specify what to inline and what not is generally a good idea, as it would imply that you think you're smarter than the JIT compiler (my respects to those who actually are), but, what if I wanted to specify that a critical portion of code needs to be extremely fast at any cost, no matter how to achieve it on the target machine? As of yet you can't do such a thing and I wonder if both the c# language and the JIT will ever support this feature. In my case, I know what the target machine is, and I know that function inlining will help improve the performance. This leaves me thinking that the only way to enforce function inlining is getting to know under what circumstances the JIT will do it but I don't think that's a good idea either, Any light on the subject would be much appreciated. Thanks.
The situation has changed a little with the advent of .Net 4.5. You can now decorate a method with the attribute [`[MethodImplAttribute(MethodImplOptions.AggressiveInlining)]`](http://msdn.microsoft.com/en-us/library/system.runtime.compilerservices.methodimploptions%28v=vs.110%29.aspx) which will cause it to be inlined by the JIT if at all possible. See [this blog](http://blogs.microsoft.co.il/blogs/sasha/archive/2012/01/20/aggressive-inlining-in-the-clr-4-5-jit.aspx) for more details.
Short answer: no Long answer: <http://blogs.msdn.com/ericgu/archive/2004/01/29/64644.aspx> Criteria for inlining: <http://blogs.msdn.com/davidnotario/archive/2004/11/01/250398.aspx> and <http://blogs.msdn.com/ericgu/archive/2004/01/29/64717.aspx> Note that in the last two links about criteria for inlining, the one about structs not being inlines is out-of-date; updated information can be found at: <http://blogs.msdn.com/vancem/archive/2008/05/12/what-s-coming-in-net-runtime-performance-in-version-v3-5-sp1.aspx>
Is there a way to enforce function inlining in c#?
[ "", "c#", "optimization", "call", "overhead", "inlining", "" ]
I've been reading Skype4Java (java api for skype) and noticed they use jni to access the skype client. intuitively I'd assume that there already is a standard library in java that has an OS-sensitive jni implementation to access other processes. I set up to look for one, but couldn't find it. Is there such a library? if not, is there a best practice to access another process in the os, not necessarily a skype client?
I think that maybe you need to define what 'access' means to you. IF you are talking about plain old inter-process communication, then sockets or JNI are really your best bet. Garth's comment about using memory mapped files is interesting - I've used MMFs and virtual files for IPC between C applications many times, but it never occurred to me that Java's MMF implementation might be compatible with the native OS virtual file system. These kinds of virtual files usually require non-trivial setup, so I'd be surprised if it would work... All said, unless you are pumping massive amounts of data between apps, using sockets is probably the most universal and effective way of doing it. Be sure you account for endianness between the host OS and Java VM :-)
From Java 1.4 onwards you can use memory mapped files to exchange arbitrary information with another process. See java.nio.MappedByteBuffer for details.
is there a "best practice" to access another process in the OS through java?
[ "", "java", "operating-system", "native", "" ]
This seems to be a common problem but I cannot find a solution. I type in my username and password which are in a login control I have created. I then press enter once I've typed in my password and the page just refreshes. It triggers the page load event but not the button on click event. If I press the submit button then everything works fine.
using your forms default button is correct, but you need to supply it the correct id as it will be rendered to HTML. so you do as Jon said above: ``` <form runat="server" DefaultButton="SubmitButton"> ``` But ensure you use the Button name that will be rendered. You can achieve this my making the Button public in your control, or a method that will return it's ClientId. Let's say your button is called btnSubmit, and your implementation of your control ucLogin. Give your form an id ``` <form runat="server" id="form1"> ``` Then in your page load in your code behind of your page, set the DefaultButton by handing it your button client id. ``` protected void Page_Load(object sender, EventArgs e) { form1.DefaultButton = ucLogin.btnSubmit.ClientID; } ```
If you're using ASP.NET 2.0 or higher, you can set a default button attribute for your page's Form: ``` <form runat="server" DefaultButton="SubmitButton"> ```
Submitting a form on a user control by pressing enter on a text field does not work
[ "", "c#", "asp.net", "user-controls", "" ]
Greetings! I've created a custom button class to render the following: ``` <span class="btnOrange"> <input type="submit" id="ctl00_MainContent_m_GoBack" value="Back" name="ctl00$MainContent$m_GoBack"/> </span> ``` However, it renders like this instead (note the extraneous "class" attribute in the INPUT tag): ``` <span class="btnOrange"> <input type="submit" class="btnOrange" id="ctl00_MainContent_m_GoBack" value="Back" name="ctl00$MainContent$m_GoBack"/> </span> ``` My custom button class looks like this: ``` [ToolboxData(@"<{0}:MyButton runat=server></{0}:MyButton>")] public class MyButton : Button { public override void RenderBeginTag(HtmlTextWriter writer) { writer.AddAttribute(HtmlTextWriterAttribute.Class, this.CssClass); writer.RenderBeginTag("span"); base.RenderBeginTag(writer); } public override void RenderEndTag(HtmlTextWriter writer) { writer.RenderEndTag(); base.RenderEndTag(writer); } } ``` Since I only need to set the class attribute for the SPAN tag, is it possible to not include or "blank out" the class attribute for the INPUT tag?
You can do this: ``` private string _heldCssClass = null; public override void RenderBeginTag(HtmlTextWriter writer) { writer.AddAttribute(HtmlTextWriterAttribute.Class, this.CssClass); writer.RenderBeginTag("span"); _heldCssClass = this.CssClass; this.CssClass = String.Empty; base.RenderBeginTag(writer); } public override void RenderEndTag(HtmlTextWriter writer) { writer.RenderEndTag(); base.RenderEndTag(writer); this.CssClass = _heldCssClass; } ``` The reason why I retain the CssClass property in a private variable between the method invocations is so prevent side effects from occurring during rendering. This may be unimportant in your particular code ("is the CssClass property really that important -after- rendering?") but it is always a good idea to prevent or reduce the impact of side effects such as what the code above exhibits by blanking out the property.
How about removing the `class` attribute from the `writer` object after rendering the `span` begin tag? I don't know ASP though so I could be wrong.
Removing CSS Class Attribute From Tag in a Custom Server Control
[ "", "c#", "asp.net", "custom-server-controls", "" ]
I have a program that monitors debug messages and I have tried using a TextBox and appended the messages to it but it doesn't scale very well and slows way down when the number of messages gets large. I then tried a ListBox but the scrolling was snapping to the top when appending new messages. It also doesn't allow for cut and paste like the text box does. What is a better way to implement a console like element embedded in a winforms window. Edit: I would still like to be able to embed a output window like visual studio but since I can't figure out an easy way here are the two solutions I use. In addition to using the RichTextBox which works but you have to clear it every now and then. I use a console that I pinvoke. Here is a little wrapper class that I wrote to handle this. ``` using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Runtime.InteropServices; namespace Con { class Ext_Console { static bool console_on = false; public static void Show(bool on,string title) { console_on = on; if (console_on) { AllocConsole(); Console.Title = title; // use to change color Console.BackgroundColor = System.ConsoleColor.White; Console.ForegroundColor = System.ConsoleColor.Black; } else { FreeConsole(); } } public static void Write(string output) { if (console_on) { Console.Write(output); } } public static void WriteLine(string output) { if (console_on) { Console.WriteLine(output); } } [DllImport("kernel32.dll")] public static extern Boolean AllocConsole(); [DllImport("kernel32.dll")] public static extern Boolean FreeConsole(); } } // example calls Ext_Console.Write("console output "); Ext_Console.WriteLine("console output"); Ext_Console.Show(true,"Title of console"); ```
RichTextBox has an AppendText method that is fast. And it can handle large text well. I believe it is the best for what you need.
I do this in my C# window programs (WInforms or WPF) using a Win32 console window. I have a small class that wraps some basic Win32 APIs, thin I create a console when the program begins. This is just an example: in 'real life' you'd use a setting or some other thing to only enable the console when you needed it. ``` using System; using System.Windows.Forms; using Microsoft.Win32.SafeHandles; using System.Diagnostics; using MWin32Api; namespace WFConsole { static class Program { static private SafeFileHandle ConsoleHandle; /// <summary> /// Initialize the Win32 console for this process. /// </summary> static private void InitWin32Console() { if ( !K32.AllocConsole() ) { MessageBox.Show( "Cannot allocate console", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error ); return; } IntPtr handle = K32.CreateFile( "CONOUT$", // name K32.GENERIC_WRITE | K32.GENERIC_READ, // desired access K32.FILE_SHARE_WRITE | K32.FILE_SHARE_READ, // share access null, // no security attributes K32.OPEN_EXISTING, // device already exists 0, // no flags or attributes IntPtr.Zero ); // no template file. ConsoleHandle = new SafeFileHandle( handle, true ); if ( ConsoleHandle.IsInvalid ) { MessageBox.Show( "Cannot create diagnostic console", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error ); return; } // // Set the console screen buffer and window to a reasonable size // 1) set the screen buffer sizse // 2) Get the maximum window size (in terms of characters) // 3) set the window to be this size // const UInt16 conWidth = 256; const UInt16 conHeight = 5000; K32.Coord dwSize = new K32.Coord( conWidth, conHeight ); if ( !K32.SetConsoleScreenBufferSize( ConsoleHandle.DangerousGetHandle(), dwSize ) ) { MessageBox.Show( "Can't get console screen buffer information.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error ); return; } K32.Console_Screen_Buffer_Info SBInfo = new K32.Console_Screen_Buffer_Info(); if ( !K32.GetConsoleScreenBufferInfo( ConsoleHandle.DangerousGetHandle(), out SBInfo ) ) { MessageBox.Show( "Can't get console screen buffer information.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); return; } K32.Small_Rect sr; ; sr.Left = 0; sr.Top = 0; sr.Right = 132 - 1; sr.Bottom = 51 - 1; if ( !K32.SetConsoleWindowInfo( ConsoleHandle.DangerousGetHandle(), true, ref sr ) ) { MessageBox.Show( "Can't set console screen buffer information.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error ); return; } IntPtr conHWND = K32.GetConsoleWindow(); if ( conHWND == IntPtr.Zero ) { MessageBox.Show( "Can't get console window handle.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error ); return; } if ( !U32.SetForegroundWindow( conHWND ) ) { MessageBox.Show( "Can't set console window as foreground.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error ); return; } K32.SetConsoleTitle( "Test - Console" ); Trace.Listeners.Add( new ConsoleTraceListener() ); } /// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main() { InitWin32Console(); Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault( false ); Application.Run( new Main() ); } } } using System; using System.Runtime.InteropServices; namespace MWin32Api { #region Kernel32 Functions //-------------------------------------------------------------------------- /// <summary> /// Functions in Kernel32.dll /// </summary> public sealed class K32 { #region Data Structures, Types and Constants //---------------------------------------------------------------------- // Data Structures, Types and Constants // [StructLayout( LayoutKind.Sequential )] public class SecurityAttributes { public UInt32 nLength; public UIntPtr lpSecurityDescriptor; public bool bInheritHandle; } [StructLayout( LayoutKind.Sequential, Pack = 1, Size = 4 )] public struct Coord { public Coord( UInt16 tx, UInt16 ty ) { x = tx; y = ty; } public UInt16 x; public UInt16 y; } [StructLayout( LayoutKind.Sequential, Pack = 1, Size = 8 )] public struct Small_Rect { public Int16 Left; public Int16 Top; public Int16 Right; public Int16 Bottom; public Small_Rect( short tLeft, short tTop, short tRight, short tBottom ) { Left = tLeft; Top = tTop; Right = tRight; Bottom = tBottom; } } [StructLayout( LayoutKind.Sequential, Pack = 1, Size = 24 )] public struct Console_Screen_Buffer_Info { public Coord dwSize; public Coord dwCursorPosition; public UInt32 wAttributes; public Small_Rect srWindow; public Coord dwMaximumWindowSize; } public const int ZERO_HANDLE_VALUE = 0; public const int INVALID_HANDLE_VALUE = -1; #endregion #region Console Functions //---------------------------------------------------------------------- // Console Functions // [DllImport( "kernel32.dll", SetLastError = true )] public static extern bool AllocConsole(); [DllImport( "kernel32.dll", SetLastError = true )] public static extern bool SetConsoleScreenBufferSize( IntPtr hConsoleOutput, Coord dwSize ); [DllImport( "kernel32.dll", SetLastError = true )] public static extern bool GetConsoleScreenBufferInfo( IntPtr hConsoleOutput, out Console_Screen_Buffer_Info lpConsoleScreenBufferInfo ); [DllImport( "kernel32.dll", SetLastError = true )] public static extern bool SetConsoleWindowInfo( IntPtr hConsoleOutput, bool bAbsolute, ref Small_Rect lpConsoleWindow ); [DllImport( "kernel32.dll", SetLastError = true )] public static extern IntPtr GetConsoleWindow(); [DllImport( "kernel32.dll", SetLastError = true )] public static extern bool SetConsoleTitle( string Filename ); #endregion #region Create File //---------------------------------------------------------------------- // Create File // public const UInt32 CREATE_NEW = 1; public const UInt32 CREATE_ALWAYS = 2; public const UInt32 OPEN_EXISTING = 3; public const UInt32 OPEN_ALWAYS = 4; public const UInt32 TRUNCATE_EXISTING = 5; public const UInt32 FILE_SHARE_READ = 1; public const UInt32 FILE_SHARE_WRITE = 2; public const UInt32 GENERIC_WRITE = 0x40000000; public const UInt32 GENERIC_READ = 0x80000000; [DllImport( "kernel32.dll", SetLastError = true )] public static extern IntPtr CreateFile( string Filename, UInt32 DesiredAccess, UInt32 ShareMode, SecurityAttributes SecAttr, UInt32 CreationDisposition, UInt32 FlagsAndAttributes, IntPtr TemplateFile ); #endregion #region Win32 Miscelaneous //---------------------------------------------------------------------- // Miscelaneous // [DllImport( "kernel32.dll" )] public static extern bool CloseHandle( UIntPtr handle ); #endregion //---------------------------------------------------------------------- private K32() { } } #endregion //-------------------------------------------------------------------------- /// <summary> /// Functions in User32.dll /// </summary> #region User32 Functions public sealed class U32 { [StructLayout( LayoutKind.Sequential )] public struct Rect { public Int32 Left; public Int32 Top; public Int32 Right; public Int32 Bottom; public Rect( short tLeft, short tTop, short tRight, short tBottom ) { Left = tLeft; Top = tTop; Right = tRight; Bottom = tBottom; } } [DllImport( "user32.dll" )] public static extern bool GetWindowRect( IntPtr hWnd, [In][MarshalAs( UnmanagedType.LPStruct )]Rect lpRect ); [DllImport( "user32.dll", SetLastError = true )] public static extern bool SetForegroundWindow( IntPtr hWnd ); //---------------------------------------------------------------------- private U32() { } } // U32 class #endregion } // MWin32Api namespace ```
How do I add a console like element to a c# winforms program
[ "", "c#", ".net", "winforms", "" ]
I have a program that needs to run as a normal user most of the time, but once in a while I need to stop and start a service. How do I go about making a program that runs as a normal user most of the time but elevates into administrator mode for some function?
You can't elevate a process once its running but you could either :- ## Restart the process as elevated ``` private void elevateCurrentProcess() { ProcessStartInfo startInfo = new ProcessStartInfo(); startInfo.UseShellExecute = true; startInfo.WorkingDirectory = Environment.CurrentDirectory; startInfo.FileName = Application.ExecutablePath; startInfo.Verb = "runas"; try { Process p = Process.Start(startInfo); } catch { // User didn't allow UAC return; } Application.Exit(); } ``` This method means that your process continues to run elevated and no more UAC promopts - both a good and a bad thing, depends upon your audience. ## Put the code that requires elevation into a seperate exe Set the manifest as requireAdministrator and start it as a separate process. See this [sample code](http://www.microsoft.com/downloads/details.aspx?FamilyID=2cd92e43-6cda-478a-9e3b-4f831e899433&DisplayLang=en) This method means a UAC prompt every time you run the operation. Best method depends upon your audience (admin types or not) and frequency of the elevated operation.
As far as I know, you need to start a seperate process that runs as the administrator. You can't elevate a process once it's already been started. See [this question](https://stackoverflow.com/questions/78696/vista-uac-access-elevation-and-net).
Running as admin sometimes
[ "", "c#", "windows-vista", "uac", "" ]
Is there any alternative for WPF (windows presentation foundation) in python? <http://msdn.microsoft.com/en-us/library/aa970268.aspx#Programming_with_WPF>
Here is a list of [Python GUI Toolkits](http://wiki.python.org/moin/GuiProgramming). Also, you can [use IronPython to work with WPF directly](http://stevegilham.blogspot.com/2007/07/hello-wpf-in-ironpython.html).
You might want to look at [pygtk](http://www.pygtk.org/) and [glade](http://glade.gnome.org/). [Here](http://www.learningpython.com/2006/05/07/creating-a-gui-using-pygtk-and-glade/) is a tutorial. There is a long [list of alternatives](http://wiki.python.org/moin/GuiProgramming) on the [Python Wiki](http://wiki.python.org/moin/FrontPage).
WPF Alternative for python
[ "", "python", "user-interface", "" ]
How do I dictate the destination folder of a clickOnce application?
This is not possible with ClickOnce. ClickOnce applications are always installed in the `Apps` subdirectory of local application data.
As a further to the above, this is a security feature. Allowing websites to install software to arbitrary locations on someone's harddrive somewhat automatically is a bad idea.
How do I dictate the destination folder of a clickOnce application?
[ "", "c#", "deployment", "installation", "clickonce", "" ]
Can anyone recommend some useful performance analysis tools for PHP scripts? Anything that could help me find problematic or unusually slow blocks of code, details about execution time, etc. would be really helpful. I know there are tools out there, but I'm wondering what people recommend as being the most useful and well-designed.
Try [webgrind](http://code.google.com/p/webgrind/ "webgrind"). It gives you the profiling of CacheGrinder in an easy to read, browser based format. I'm on a Mac and it has made profiling a breeze.
XDebug's [profiler](http://www.xdebug.org/docs/profiler) is good. But then I'm a KDE user... I think you could install the KCacheGrind in other window managers though.
Can you recommend Performance Analysis tools for PHP?
[ "", "php", "performance", "testing", "" ]
Recently I wrote a function to generate certain sequences with nontrivial constraints. The problem came with a natural recursive solution. Now it happens that, even for relatively small input, the sequences are several thousands, thus I would prefer to use my algorithm as a generator instead of using it to fill a list with all the sequences. Here is an example. Suppose we want to compute all the permutations of a string with a recursive function. The following naive algorithm takes an extra argument 'storage' and appends a permutation to it whenever it finds one: ``` def getPermutations(string, storage, prefix=""): if len(string) == 1: storage.append(prefix + string) # <----- else: for i in range(len(string)): getPermutations(string[:i]+string[i+1:], storage, prefix+string[i]) storage = [] getPermutations("abcd", storage) for permutation in storage: print permutation ``` (Please don't care about inefficiency, this is only an example.) Now I want to turn my function into a generator, i.e. to yield a permutation instead of appending it to the storage list: ``` def getPermutations(string, prefix=""): if len(string) == 1: yield prefix + string # <----- else: for i in range(len(string)): getPermutations(string[:i]+string[i+1:], prefix+string[i]) for permutation in getPermutations("abcd"): print permutation ``` This code does *not* work (the function behaves like an empty generator). Am I missing something? Is there a way to turn the above recursive algorithm into a generator *without replacing it with an iterative one*?
``` def getPermutations(string, prefix=""): if len(string) == 1: yield prefix + string else: for i in xrange(len(string)): for perm in getPermutations(string[:i] + string[i+1:], prefix+string[i]): yield perm ``` Or without an accumulator: ``` def getPermutations(string): if len(string) == 1: yield string else: for i in xrange(len(string)): for perm in getPermutations(string[:i] + string[i+1:]): yield string[i] + perm ```
This avoids the `len(string)`-deep recursion, and is in general a nice way to handle generators-inside-generators: ``` from types import GeneratorType def flatten(*stack): stack = list(stack) while stack: try: x = stack[0].next() except StopIteration: stack.pop(0) continue if isinstance(x, GeneratorType): stack.insert(0, x) else: yield x def _getPermutations(string, prefix=""): if len(string) == 1: yield prefix + string else: yield (_getPermutations(string[:i]+string[i+1:], prefix+string[i]) for i in range(len(string))) def getPermutations(string): return flatten(_getPermutations(string)) for permutation in getPermutations("abcd"): print permutation ``` `flatten` allows us to continue progress in another generator by simply `yield`ing it, instead of iterating through it and `yield`ing each item manually. --- Python 3.3 will add [`yield from`](http://docs.python.org/dev/whatsnew/3.3.html#pep-380-syntax-for-delegating-to-a-subgenerator) to the syntax, which allows for natural delegation to a sub-generator: ``` def getPermutations(string, prefix=""): if len(string) == 1: yield prefix + string else: for i in range(len(string)): yield from getPermutations(string[:i]+string[i+1:], prefix+string[i]) ```
Python: using a recursive algorithm as a generator
[ "", "python", "recursion", "generator", "" ]
Is it possible to subscribe to a Windows event that fires when Windows is going into or coming out of Sleep or Hibernate state? I need my application to be made aware when the computer is going to sleep to do some cleanup and avoid timing issues when it comes out of sleep.
[`Microsoft.Win32.SystemEvents.PowerModeChanged`](http://msdn.microsoft.com/en-us/library/microsoft.win32.systemevents.powermodechanged.aspx) event will give you this information. This event is available in all variants of the .NET framework released by Microsoft so far.
In .NET, use the [PowerModeChanged](http://msdn.microsoft.com/en-us/library/microsoft.win32.systemevents.powermodechanged.aspx) event. In Win32, use the [WM\_POWERBROADCAST](http://msdn.microsoft.com/en-us/library/aa373247(VS.85).aspx) message.
How can I know when Windows is going into/out of sleep or Hibernate mode?
[ "", "c#", "windows", "sleep-mode", "hibernate-mode", "" ]
I need to index a varchar field on my table in MS SQL Server 2005, but it's not clear to me how to do so. If I try to add a non-clustered index on the field, it says "Column 'xxxx' in table 'mytable' is of a type that is invalid for use as a key column in an index" My table has an auto-increment int ID that is set as the primary key on the table. If I set this property as the index, and then add my varchar column as an "included column", the index goes through. But I'm not sure that's what I want - I want to be able to search the table based on the varchar field alone, and my understanding of indexes was that all indexed elements had to be provided to actually see a speedup in the query, but I don't want to have to included the int ID (because I don't know what it is, at the time of this given query). Am I trying to do this incorrectly? Would the ID + my varchar as an included column accomplish what I am looking for?
Is your `varchar(max)`? I think those aren't allowed to be used in an index. Otherwise, post your `CREATE TABLE` statement, normally there is no problem adding a `varchar` to an index.
I assume yours is a VARCHAR(MAX) column which, as the error says, is an invalida data type for an index. Suggestion: create a calculated column that is the hash value of the VARCHAR(MAX) column (e.g. using the HashBytes function) then create an index on the calculated column only. Then, in the search condition (e.g. WHERE clause) of your SQL DML you would use both the VARCHAR(MAX) search value itself *plus* a hash of your VARCHAR(MAX) search value on the respective columns in your table. It may be a good idea to encapsulate the hashing of search values in a 'helper' stored procedure.
Index varchar on MS SQL Server 2005
[ "", "sql", "sql-server-2005", "" ]
I need to recover form an error case where a file gets left in a locked state. How can I in c# tell this file to reset it's locks? I need to add to this the file is opened by a 3rd party dll and I don't actually have access to the file handle.
You could perhaps start a command line process like net or psfile with something along the lines of: `System.Diagnostics.Process.Start("psfile c:\myfile.txt -c");` You can get psfile [here](http://technet.microsoft.com/en-us/sysinternals/bb897552.aspx). You could also use `net file ID /close` but that would require you to know the file ID, which would take a bit more work. Untested but this should give you a starting point.
Locking a file is the responsibility of the Operating System (on behalf of the program that opens it). If a file is left in a locked state, its really up to the OS to unlock. This typically happens automatically when the process that opened the file exits. There is, however, a really cool utility that I came across that will help. It's called [Unlocker](http://www.emptyloop.com/unlocker/).
Removing file locks
[ "", "c#", "file-io", "locking", "" ]
I have a MySQL database table with a couple thousand rows. The table is setup like so: `id | text` The `id` column is an auto-incrementing integer, and the `text` column is a 200-character varchar. Say I have the following rows: `3 | I think I'll have duck tonight` `4 | Maybe the chicken will be alright` `5 | I have a pet duck now, awesome!` `6 | I love duck` Then the list I'm wanting to generate might be something like: * 3 occurrences of 'duck' * 3 occurrences of 'I' * 2 occurrences of 'have' * 1 occurrences of 'chicken' * .etc .etc Plus, I'll probably want to maintain a list of substrings to ignore from the list, like 'I', 'will' and 'have. It's important to note that I do not know what people will post. I do not have a list of words that I want to monitor, I just want to find the most common substrings. I'll then filter out any erroneous substrings that are not interesting from the list manually by editing the query. Can anyone suggest the best way to do this? Thanks everyone!
MySQL already does this for you. First make sure your table is a MyISAM table Define a FULLTEXT index on your column On a shell command line navigate to the folder where your MySQL data is stored, then type: ``` myisam_ftdump -c yourtablename 1 >wordfreq.dump ``` You can then process wordfreq.dump to eliminate the unwanted column and sort by frequency decending. You could do all the above with a single command line and some sed/awk wizardry no doubt. And you could incorporate it into your program without needing a dump file. More info on myisam\_ftdump here: <http://dev.mysql.com/doc/refman/5.0/en/myisam-ftdump.html> Oh... one more thing, the stopwords for MySQL are precompiled into the engine. And words with 3 or less characters are not indexed. The full list is here: <http://dev.mysql.com/doc/refman/5.0/en/fulltext-stopwords.html> If this list isn't adequate for your needs, or you need words with less than 3 characters to count, the only way is to recompile MySQL with different rules for FULLTEXT. I don't recommend that!
Extract to flat file and then use your favorite quick language, perl, python, ruby, etc to process the flat file. If you don't have one these languages as part of your skillset, this is a perfect little task to start using one, and it won't take you long. Some database tasks are just so much easier to do OUTSIDE of the database.
How can I create an ordered list of the most common substrings inside of my MySQL varchar column?
[ "", "sql", "mysql", "statistics", "" ]
How do I properly convert two columns from SQL (2008) using Linq into a `Dictionary` (for caching)? I currently loop through the `IQueryable` b/c I can't get the `ToDictionary` method to work. Any ideas? This works: ``` var query = from p in db.Table select p; Dictionary<string, string> dic = new Dictionary<string, string>(); foreach (var p in query) { dic.Add(sub.Key, sub.Value); } ``` What I'd really like to do is something like this, which doesn't seem to work: ``` var dic = (from p in db.Table select new {p.Key, p.Value }) .ToDictionary<string, string>(p => p.Key); ``` But I get this error: > Cannot convert from 'System.Linq.IQueryable<AnonymousType#1>' to > 'System.Collections.Generic.IEnumerable'
``` var dictionary = db .Table .Select(p => new { p.Key, p.Value }) .AsEnumerable() .ToDictionary(kvp => kvp.Key, kvp => kvp.Value) ; ```
You are only defining the key, but you need to include the value also: ``` var dic = (from p in db.Table select new {p.Key, p.Value }) .ToDictionary(p => p.Key, p=> p.Value); ```
Linq-to-SQL ToDictionary()
[ "", "c#", "linq", "linq-to-sql", "" ]
Is there any way to determine if an object is a generic list? I'm not going to know the type of the list, I just know it's a list. How can I determine that?
This will return "True" ``` List<int> myList = new List<int>(); Console.Write(myList.GetType().IsGenericType && myList is IEnumerable); ``` Do you care to know if it's exactly a "List"... or are you ok with it being IEnumerable, and Generic?
The following method will return the item type of a generic collection type. If the type does not implement ICollection<> then null is returned. ``` static Type GetGenericCollectionItemType(Type type) { if (type.IsGenericType) { var args = type.GetGenericArguments(); if (args.Length == 1 && typeof(ICollection<>).MakeGenericType(args).IsAssignableFrom(type)) { return args[0]; } } return null; } ``` **Edit:** The above solution assumes that the specified type has a generic parameter of its own. This will not work for types that implement ICollection<> with a hard coded generic parameter, for example: ``` class PersonCollection : List<Person> {} ``` Here is a new implementation that will handle this case. ``` static Type GetGenericCollectionItemType(Type type) { return type.GetInterfaces() .Where(face => face.IsGenericType && face.GetGenericTypeDefinition() == typeof(ICollection<>)) .Select(face => face.GetGenericArguments()[0]) .FirstOrDefault(); } ```
If object is Generic List
[ "", "c#", ".net", "vb.net", "list", "generics", "" ]
I've declared Javascript arrays in such a way that I could then access them by a key, but it was a long time ago, and I've forgotten how I did it. Basically, I have two fields I want to store, a unique key, and its value. I know there is a way to do it.. something like: ``` var jsArray = new {key: 'test test', value: 'value value'}, new {key: 'test 2', value: 'value 2'}; ``` and accessed like: ``` value = jsArray[key] ``` Can someone remind me?
You can do it in different ways: ``` var a = {'a':0, 'b':1, 'c':2}; var b = new Array(); b['a'] = 0; b['b'] = 1; b['c'] = 2; var c = new Object(); c.a = 0; c.b = 1; c.c = 2; ```
``` var myFancyDictionary = { key: 'value', anotherKey: 'anotherValue', youGet: 'the idea' } ```
JavaScript fake dictionaries
[ "", "javascript", "arrays", "dictionary", "associative-array", "" ]
After I read a bunch of LINQ related stuff, I suddenly realized that no articles introduce how to write asynchronous LINQ query. Suppose we use LINQ to SQL, below statement is clear. However, if the SQL database responds slowly, then the thread using this block of code would be hindered. ``` var result = from item in Products where item.Price > 3 select item.Name; foreach (var name in result) { Console.WriteLine(name); } ``` Seems that current LINQ query spec doesn't provide support to this. Is there any way to do asynchronous programming LINQ? It works like there is a callback notification when results are ready to use without any blocking delay on I/O.
While LINQ doesn't really have this per se, the framework itself does... You can easily roll your own asynchronous query executor in 30 lines or so... In fact, I just threw this together for you :) **EDIT: Through writing this, I've discovered why they didn't implement it. It cannot handle anonymous types since they are scoped local. Thus, you have no way of defining your callback function.** This is a pretty major thing since a lot of linq to sql stuff creates them in the select clause. Any of the below suggestions suffer the same fate, so I still think this one is the easiest to use! EDIT: The only solution is to not use anonymous types. You can declare the callback as just taking IEnumerable (no type args), and use reflection to access the fields (ICK!!). Another way would be to declare the callback as "dynamic"... oh... wait... That's not out yet. :) This is another decent example of how dynamic could be used. Some may call it abuse. Throw this in your utilities library: ``` public static class AsynchronousQueryExecutor { public static void Call<T>(IEnumerable<T> query, Action<IEnumerable<T>> callback, Action<Exception> errorCallback) { Func<IEnumerable<T>, IEnumerable<T>> func = new Func<IEnumerable<T>, IEnumerable<T>>(InnerEnumerate<T>); IEnumerable<T> result = null; IAsyncResult ar = func.BeginInvoke( query, new AsyncCallback(delegate(IAsyncResult arr) { try { result = ((Func<IEnumerable<T>, IEnumerable<T>>)((AsyncResult)arr).AsyncDelegate).EndInvoke(arr); } catch (Exception ex) { if (errorCallback != null) { errorCallback(ex); } return; } //errors from inside here are the callbacks problem //I think it would be confusing to report them callback(result); }), null); } private static IEnumerable<T> InnerEnumerate<T>(IEnumerable<T> query) { foreach (var item in query) //the method hangs here while the query executes { yield return item; } } } ``` And you could use it like this: ``` class Program { public static void Main(string[] args) { //this could be your linq query var qry = TestSlowLoadingEnumerable(); //We begin the call and give it our callback delegate //and a delegate to an error handler AsynchronousQueryExecutor.Call(qry, HandleResults, HandleError); Console.WriteLine("Call began on seperate thread, execution continued"); Console.ReadLine(); } public static void HandleResults(IEnumerable<int> results) { //the results are available in here foreach (var item in results) { Console.WriteLine(item); } } public static void HandleError(Exception ex) { Console.WriteLine("error"); } //just a sample lazy loading enumerable public static IEnumerable<int> TestSlowLoadingEnumerable() { Thread.Sleep(5000); foreach (var i in new int[] { 1, 2, 3, 4, 5, 6 }) { yield return i; } } } ``` Going to go put this up on my blog now, pretty handy.
TheSoftwareJedi's and [ulrikb](http://ulrikb.wordpress.com/2010/04/14/executing-a-linq-query-asynchronously/)'s(aka user316318) solutions are good for any LINQ type, but (as pointed by [Chris Moschini](https://stackoverflow.com/users/176877/chris-moschini)) do NOT delegating to underlying asynchronous calls that leverage Windows I/O Completion Ports. Wesley Bakker's [Asynchronous DataContext](http://weblogs.asp.net/wesleybakker/archive/2010/03/03/asynchronous-datacontext.aspx) post (triggered by [a blog post of Scott Hanselman](http://www.hanselman.com/blog/TheWeeklySourceCode51AsynchronousDatabaseAccessAndLINQToSQLFun.aspx) ) describe class for LINQ to SQL that uses sqlCommand.BeginExecuteReader/sqlCommand.EndExecuteReader, which leverage Windows I/O Completion Ports. [I/O completion ports](http://msdn.microsoft.com/en-us/library/aa365198%28v=vs.85%29.aspx) provide an efficient threading model for processing multiple asynchronous I/O requests on a multiprocessor system.
How to write Asynchronous LINQ query?
[ "", "c#", "linq", "linq-to-sql", "asynchronous", "" ]
I am looking to parse a URL to obtain a collection of the querystring parameters in Java. To be clear, I need to parse a given URL(or string value of a URL object), not the URL from a servlet request. It looks as if the `javax.servlet.http.HttpUtils.parseQueryString` method would be the obvious choice, but it has been deprecated. Is there an alternative method that I am missing, or has it just been deprecated without an equivalent replacement/enhanced function?
Well, as you mention that the URL does not come from a servlet request, the right answer is, as usual, **it depends**. The problem with query part of an url is that there is no clear specification about how to handle parameters duplication. For example, consider an url like this one: ``` http://www.example.com?param1=value1&param2=value2&param1=value3 ``` What do you expect as a value for param1? the first value, the last one, an array? The issue is that, according to the specs, all these answers are valid and server vendor are free to support one of these or another. Some use the param1[] notation to indicate that it has to be treated as an array, but again, this is not a unified solution. So the "best" solution is to know how your destination handle parameters, and mimic the behaviour with a self-made utility class.
I think the idea is to use the HttpServletRequest instead. There is the getParameterMap(), getParameterNames() and getParameterValues() methods to start. There is also the getParameter(String paramname) method to get the value of a specific method. These make no distinction between querystring parameters and form parameters though so if your intention was to look for a querystring in aparticular then I guess this wouldn't help.
Alternative to deprecated javax.servlet.http.HttpUtils.parseQueryString?
[ "", "java", "url", "parsing", "query-string", "" ]
Is it good practice to have a class constructor that uses default parameters, or should I use separate overloaded constructors? For example: ``` // Use this... class foo { private: std::string name_; unsigned int age_; public: foo(const std::string& name = "", const unsigned int age = 0) : name_(name), age_(age) { ... } }; // Or this? class foo { private: std::string name_; unsigned int age_; public: foo() : name_(""), age_(0) { } foo(const std::string& name, const unsigned int age) : name_(name), age_(age) { ... } }; ``` Either version seems to work, e.g.: ``` foo f1; foo f2("Name", 30); ``` Which style do you prefer or recommend and why?
Definitely a matter of style. I prefer constructors with default parameters, so long as the parameters make sense. Classes in the standard use them as well, which speaks in their favor. One thing to watch out for is if you have defaults for all but one parameter, your class can be implicitly converted from that parameter type. Check out [this thread](https://stackoverflow.com/questions/174349/forcing-single-argument-constructors-to-be-explicit-in-c) for more info.
I'd go with the default arguments, especially since C++ doesn't let you chain constructors (so you end up having to duplicate the initialiser list, and possibly more, for each overload). That said, there are some gotchas with default arguments, including the fact that constants may be inlined (and thereby become part of your class' binary interface). Another to watch out for is that adding default arguments can turn an explicit multi-argument constructor into an implicit one-argument constructor: ``` class Vehicle { public: Vehicle(int wheels, std::string name = "Mini"); }; Vehicle x = 5; // this compiles just fine... did you really want it to? ```
Default parameters with C++ constructors
[ "", "c++", "constructor", "coding-style", "overloading", "" ]
I use Visual Studio's "Code Snippet" feature pretty heavily while editing c# code. I always wished I could use them while typing out my aspx markup. Is there a way to enable code snippet use in an aspx file editor window? Are there any third party tools that perform this? If you're familiar with code snippet definitions, this is exactly the type of thing I want to do: ``` <asp:TextBox ID="$var$TextBox" Text="$text$" OnClick="$var$_Click" runat="server" /> ``` *I could activate the snippet, tab twice, and move on!*
Perhaps you might think of trying [Coderush](http://devexpress.com/coderush) which has a lot more to offer than the basic snippets found in VS. It's template facility can operate in vb, cs, aspx, html, xml and sql files.
That would be brilliant! I'd recommend the [world's simplest code generato](http://secretgeek.net/wscg.htm)r, or CodeSmith, or maybe [T4](http://www.hanselman.com/blog/T4TextTemplateTransformationToolkitCodeGenerationBestKeptVisualStudioSecret.aspx) (although I haven't tried it yet). Doesn't quite do what you'd like, but it does make it a little easier
How can I use Visual Studio's "Code Snippet" feature while editing a .aspx file?
[ "", "c#", "asp.net", "visual-studio", "" ]
I am just looking at the using statement, I have always known what it does but until now not tried using it, I have come up with the below code: ``` using (SqlCommand cmd = new SqlCommand(reportDataSource, new SqlConnection(Settings.Default.qlsdat_extensionsConnectionString))) { cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.Add("@Year", SqlDbType.Char, 4).Value = year; cmd.Parameters.Add("@startDate", SqlDbType.DateTime).Value = start; cmd.Parameters.Add("@endDate", SqlDbType.DateTime).Value = end; cmd.Connection.Open(); DataSet dset = new DataSet(); new SqlDataAdapter(cmd).Fill(dset); this.gridDataSource.DataSource = dset.Tables[0]; } ``` This seems to work but is there any point in this since as far as I can tell I would still need to enclose this in a try catch block to catch unforseen errors e.g. sql server down. Am I missing something? As far as I can currently see it just stops me closing and disposing of cmd but there will be more lines of code due to the try catch still being needed.
This code should be as follows to ensure timely closing of the connection. Closing just the command doesn't close the connection: ``` using (SqlConnection con = new SqlConnection(Settings.Default.qlsdat_extensionsConnectionString)) using (SqlCommand cmd = new SqlCommand(reportDataSource, con)) { cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.Add("@Year", SqlDbType.Char, 4).Value = year; cmd.Parameters.Add("@startDate", SqlDbType.DateTime).Value = start; cmd.Parameters.Add("@endDate", SqlDbType.DateTime).Value = end; cmd.Connection.Open(); DataSet dset = new DataSet(); new SqlDataAdapter(cmd).Fill(dset); this.gridDataSource.DataSource = dset.Tables[0]; } ``` To answer your question, you can do the same in a finally block, but this scopes the code nicely and ensures that you remember to clean up.
When doing IO work I code to *expect* an exception. ``` SqlConnection conn = null; SqlCommand cmd = null; try { conn = new SqlConnection(Settings.Default.qlsdat_extensionsConnectionString) cmd = new SqlCommand(reportDataSource, conn); cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.Add("@Year", SqlDbType.Char, 4).Value = year; cmd.Parameters.Add("@startDate", SqlDbType.DateTime).Value = start; cmd.Parameters.Add("@endDate", SqlDbType.DateTime).Value = end; conn.Open(); //opens connection DataSet dset = new DataSet(); new SqlDataAdapter(cmd).Fill(dset); this.gridDataSource.DataSource = dset.Tables[0]; } catch(Exception ex) { Logger.Log(ex); throw; } finally { if(conn != null) conn.Dispose(); if(cmd != null) cmd.Dispose(); } ``` **Edit:** To be explicit, I avoid the *using* block here because I believe it to be important to log in situations like this. Experience has taught me that you never know what kind of weird exception might pop up. Logging in this situation might help you detect a deadlock, or find where a schema change is impacting a little used and little tested part of you code base, or any number of other problems. **Edit 2:** One can argue that a using block could wrap a try/catch in this situation, and this is completely valid and functionally equivalent. This really boils down to preference. Do you want to avoid the extra nesting at the cost of handling your own disposal? Or do you incur the extra nesting to have auto-disposal. I feel that the former is cleaner so I do it that way. However, I don't rewrite the latter if I find it in the code base in which I am working. **Edit 3:** I really, really wish MS had created a more explicit version of using() that made it more intuitive what was really happening and given more flexibility in this case. Consider the following, imaginary code: ``` SqlConnection conn = null; SqlCommand cmd = null; using(conn = new SqlConnection(Settings.Default.qlsdat_extensionsConnectionString), cmd = new SqlCommand(reportDataSource, conn) { conn = new SqlConnection(Settings.Default.qlsdat_extensionsConnectionString); cmd = new SqlCommand(reportDataSource, conn); cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.Add("@Year", SqlDbType.Char, 4).Value = year; cmd.Parameters.Add("@startDate", SqlDbType.DateTime).Value = start; cmd.Parameters.Add("@endDate", SqlDbType.DateTime).Value = end; cmd.Open(); DataSet dset = new DataSet(); new SqlDataAdapter(cmd).Fill(dset); this.gridDataSource.DataSource = dset.Tables[0]; } catch(Exception ex) { Logger.Log(ex); throw; } ``` A using statement just creates a try/finally with Dispose() calls in the finally. Why not give the developer a unified way of doing disposal and exception handling?
C# using statement catch error
[ "", "c#", "using", "using-statement", "" ]
I want your suggestion on the following pseudo-code. Please suggest how could I improve it, whether or not I could use some design patterns. ``` // i'm receiving a string containing : id operation arguments data = read(socket); tokens = tokenize(data," "); // tokenize the string based on spaces if(tokens[0] == "A") { if(tokens[1] == "some_operation") { // here goes code for some_operation , will use the remaining tokens as arguments for function calls } else if(tokens[1] == "some_other_operation") { // here goes code for some_other_operation , will use the remaining tokens } ... else { // unknown operation } } else if(tokens[0] == "B") { if(tokens[1] == "some_operation_for_B") { // do some operation for B } else if(tokens[1] == "yet_another_operation") { // do yet_another_operation for B } ... else { // unknown operation } } ``` I hope you get the point . The thing is I have a large number of **id's** and each has it's own **operations** , and I think it's kinda ugly to have 10 screens of code containing a lot of **if's** and **else if's**.
Have a class for each ID which implements a common interface. Basically the [Strategy pattern](http://en.wikipedia.org/wiki/Strategy_pattern) IIRC. So you'd call (pseudo)code like: `StrategyFactory.GetStrategy(tokens[0]).parse(tokens[1..n])`
First write down the syntax of what you support, then write the code to support it. Using BNF notation is great for that. And using the Spirit library for the code-part is quite straightforward. ``` Command := ACommand | BCommand ACommand := 'A' AOperation AOperation := 'some_operation' | 'some_other_operation' BCommand := 'B' BOperation BOperation := 'some_operation_for_B' | 'some_other_operation_for_B' ``` This easily translates into a Spirit parser. Every production rule would become a one-liner, every end-symbol would be translated into a function. ``` #include "stdafx.h" #include <boost/spirit/core.hpp> #include <iostream> #include <string> using namespace std; using namespace boost::spirit; namespace { void AOperation(char const*, char const*) { cout << "AOperation\n"; } void AOtherOperation(char const*, char const*) { cout << "AOtherOperation\n"; } void BOperation(char const*, char const*) { cout << "BOperation\n"; } void BOtherOperation(char const*, char const*) { cout << "BOtherOperation\n"; } } struct arguments : public grammar<arguments> { template <typename ScannerT> struct definition { definition(arguments const& /*self*/) { command = acommand | bcommand; acommand = chlit<char>('A') >> ( a_someoperation | a_someotheroperation ); a_someoperation = str_p( "some_operation" ) [ &AOperation ]; a_someotheroperation = str_p( "some_other_operation" )[ &AOtherOperation ]; bcommand = chlit<char>('B') >> ( b_someoperation | b_someotheroperation ); b_someoperation = str_p( "some_operation_for_B" ) [ &BOperation ]; b_someotheroperation = str_p( "some_other_operation_for_B" )[ &BOtherOperation ]; } rule<ScannerT> command; rule<ScannerT> acommand, bcommand; rule<ScannerT> a_someoperation, a_someotheroperation; rule<ScannerT> b_someoperation, b_someotheroperation; rule<ScannerT> const& start() const { return command; } }; }; template<typename parse_info > bool test( parse_info pi ) { if( pi.full ) { cout << "success" << endl; return true; } else { cout << "fail" << endl; return false; } } int _tmain(int argc, _TCHAR* argv[]) { arguments args; test( parse( "A some_operation", args, space_p ) ); test( parse( "A some_other_operation", args, space_p ) ); test( parse( "B some_operation_for_B", args, space_p ) ); test( parse( "B some_other_operation_for_B", args, space_p ) ); test( parse( "A some_other_operation_for_B", args, space_p ) ); return 0; } ```
How could I improve this C++ code
[ "", "c++", "design-patterns", "refactoring", "" ]
I've always struggled with how to best include classes into my php code. Pathing is usually an issue but a few minutes ago i found [this question](https://stackoverflow.com/questions/4369/how-to-include-php-files-that-require-an-absolute-path) which dramatically helps that. Now I'm reading about \_\_autoload and thinking that it could make the process of developing my applications much easier. The problem is i like to maintain folder structure to separate areas of functionality as opposed to throwing everything into a general /lib folder. So if i override autoload to do a deep search of a class folder including all subfolders, what performance hits can i expect? Obviously this will depend on scale, depth of the folder structure and number of classes but generally I'm asking on a medium scale project will it cause problems.
\_\_autoload is great, but the cost of stating all the files in a recursive search function is expensive. You might want to look at building a tree of files to use for autoloading. In my framework, I consistently name files for their classes and use a map that is cached for the data. Check out <http://trac.framewerk.org/cgi-bin/trac.fcgi/browser/trunk/index.php> [**dead link**] starting at line 68 for an idea of how this can be done. Edit: And to more directly answer your question, without caching, you can expect a performance hit on a site with medium to heavy traffic.
A common pattern (Pear, Zend Framework as examples...) is to make the classname reflect the path, so Db\_Adapter\_Mysql will be in at /Db/Adapter/Mysql.php, from somewhere that's added to the include-path.
Would performance suffer using autoload in php and searching for the class file?
[ "", "php", "performance", "" ]