Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
I have the following query, which is trying to figure out the percentage of a certain product compared to the total number of products. IE: [Product Count] / [Total Products] = Percent ``` ;WITH totalCount AS( SELECT CAST(COUNT(id) as Integer)as totalCount FROM TABLE_NAME ) SELECT ((CAST(COUNT(DISTINCT id) as Integer)/(SELECT * FROM totalCount))*100) as 'Percent' FROM TABLE_NAME ``` However, the percent column always returns "0" unless there is only one record. In addition, is there a way to add the totalCount and Select query into one? Basically, how do you divide two Count() fields?
Cast your total count as a number besides integer (DECIMAL?) - the math rounds off.
Cast as something with decimal precision, not Integer. A float or real. ``` select cast(distinctCount as real)/cast(totalCount as real) * 100.00 , distinctCount , totalCount from ( select count(distinct id) as distinctCount , count(id) as totalCount from Table) as aggregatedTable ```
SQL Divide by Two Count()
[ "", "sql", "sql-server", "count", "" ]
My test file has data like this: ``` 1 2 3 0 1, 2 3, 4 0, 0 4, 3 2, 1 0, 0 ``` How would I separate the data by line but also separate each section of data by the zeros. ``` ifstream data("testData.txt"); string line, a, b; while(getline(data,line)) { stringstream str(line); istringstream ins; ins.str(line); ins >> a >> b; hold.push_back(a); hold.push_back(b); } ``` How do I separate them by the zeros?
So the lines are significant, and the zero-delimited lists of numbers are also significant? Try something like this: ``` std::ifstream data("testData.txt"); std::vector<int> hold; std::string line; std::vector<std::string> lines; while(std::getline(data,line)) { lines.push_back(line); std::stringstream str(line); // Read an int and the next character as long as there is one while (str.good()) { int val; char c; str >> val >> c; if (val == 0) { do_something(hold); hold.clear(); } else hold.push_back(val); } } ``` This isn't very fault-tolerant, but it works. It relies on a single character (a comma) to be present after every number except the last one on each line.
First of all, I would try to improve the problem definition ☺
c++ Input from text file help
[ "", "c++", "" ]
I have a simple if-else statement--if true, I'd like it to echo this content: ``` <div id="login"> <h2>Login</h2> <div class="box"> <form method="POST" action="index.php/login"> Username/Email:<br /> <input type="text" name="username" value="<?php echo set_value("username"); ?>" size="50" class="form" /> <?php echo form_error("username"); ?> Password:<br /> <input type="password" name="password" value="<?php echo set_value("password"); ?>" size="50" class="form" /> <?php echo form_error("password"); ?> <input type="submit" value="Login" name="login" /> </form> </div> </div> ``` and if false do something similar. How should I approach this? I'm a PHP noob (and I've been annoying the community here!)--so I'm standing at the echo function right now--I think I can set variables, but that's about it. Thanks so much!
Same thing as you have been doing: ``` <?php if some_condition { ?> <p> I am inside the true condition due : <?php echo "true on condition" ?> </p> <? } else { ?> <p> I am inside the false condition due : <?php echo "false on condition" ?> </p> <? } ?> ```
You can simply break out of PHP in the if/else statement. ``` if(true) { ?> Regular HTML Here <?php } else { ?> Regular HTML Here <?php } ``` You can break out of PHP at any time using the '?>' operator, and with any control structure, it should show the code just as if you echo'd it. Another option would be to use output buffering. ``` if(true) { ob_start(); ?> Regular Code Here <?php $contents = ob_get_contents(); ob_end_clean(); } ``` This will leave the contents of what outputted between the start and end in $contents. Finally, you could use an include() to only include your login form when you actually need it. (I prefer this method because I can put login forms almost anywhere on the site very easily) ``` if(true) { include('loginform.php'); } ```
Echo block of HTML that contains PHP functions
[ "", "php", "echo", "" ]
When using Python's textwrap library, how can I turn this: ``` short line, long line xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx ``` into this: ``` short line, long line xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx xxxxxxxxxxxxxxxxxxx ``` I tried: ``` w = textwrap.TextWrapper(width=90,break_long_words=False) body = '\n'.join(w.wrap(body)) ``` But I get: ``` short line, long line xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx ``` (spacing not exact in my examples)
try ``` w = textwrap.TextWrapper(width=90,break_long_words=False,replace_whitespace=False) ``` that seemed to fix the problem for me I worked that out from what I read [here](http://docs.python.org/library/textwrap.html#textwrap.TextWrapper) (I've never used textwrap before)
``` body = '\n'.join(['\n'.join(textwrap.wrap(line, 90, break_long_words=False, replace_whitespace=False)) for line in body.splitlines() if line.strip() != '']) ```
Python textwrap Library - How to Preserve Line Breaks?
[ "", "python", "newline", "word-wrap", "" ]
I'm trying to somehow override the constructor of HTMLElement (specifically HTMLDivElement), so that whenever any are created by whatever means, I can run some custom logic. Obviously this doesn't work: ```` ``` HTMLDivElement.prototype.constructor = function() { alert('div created!'); } ``` ```` Is there a way to pull this off? Even if there was a way to get some sort of event/trigger when new elements where created (ones not part of the page's source HTML), that would be helpful. EDIT: Maybe there is something we could do with Mozilla's watch/unwatch methods to watch for a change?
I’m going to Hell for this: ``` document.createElement = (function (fn) { return function (tagName) { var elem = fn.call(document, tagName); alert('just created a new ' + elem.tagName); return elem; }; })(document.createElement); ```
If you could consider using jQuery there is a plugin called [Livequery](http://docs.jquery.com/Plugins/livequery) which lets you trigger events on not yet created elements. So your example above could be written like this: ``` $("div").livequery('load', function(event) { alert('div created!'); }); ``` Note that I have not tried livequery myself, but I'm guessing since there are no answers to this question. Hope it helps!
A way to override the constructor on HTMLElement so I can add custom code
[ "", "javascript", "" ]
``` public class TestClass { public TestClass(int id, string name) { Name = name; Id = id; } public string Name { get; private set; } public int Id { get; private set; } public string Tag { get; set; } public DateTime Time { get; set; } } private static void Main(string[] args) { List<TestClass> list = new List<TestClass>(); for (int i = 0; i < 5; i++ ) { TestClass t = new TestClass(i, Guid.NewGuid().ToString()); t.Tag = i%2 == 0?"Hello":"World"; list.Add(t); } var query = list .GroupBy(l=>l.Tag); Func<IEnumerable<IGrouping<string, TestClass>>, int[]> func = GetIds<string,TestClass>; func.BeginInvoke(query, null, null); Console.Read(); } private static int[] GetIds<T, U>(IEnumerable<IGrouping<T, U>> query) { List<int> ints = new List<int>(); foreach(var y in query) ints.Add(y.Count()); return ints.ToArray(); } } ``` I know LINQ doesnt execute until the collection is iterated, but i just want to make sure that I can assume that it still holds true even if the query is passed to another method async.
Yes, query execution is still deferred. The query is just a reference to an implementation of `IEnumerable<T>` which in turn knows about another `IEnumerable<T>` (along with appropriate delegates for filtering, grouping etc). Note that if you iterate over it a second time (in whatever thread) that will execute the query again. The query reference knows *how to get the data* - it doesn't know the data itself.
As I understand it, it will still hold true asynchronously, however the execution may not be threadsafe. LINQ to SQL's DataContexts for example aren't threadsafe, and therefore LINQ to SQL queries should not be executed in another thread in that manner.
When is this LINQ query executed?
[ "", "c#", "linq", "" ]
I want my php to open a new html page. I have a html page, where a member can login by typing her username and password and then click on button. if the username password is correct, i want my php to open a different html page in the same window. how can i do this?? Zeeshan
Or, the 'techless' solution: ``` <html> <head> <title>Redirecting...</title> <meta http-equiv="refresh" content="0;URL=newpage.php"> </head> <body> You are being automatically redirected to a new location.<br /> If your browser does not redirect you in few seconds, or you do not wish to wait, <a href="newpage.php">click here</a>. </body> </html> ``` See [Here.](https://stackoverflow.com/questions/736989/php-redirect-pause/737003#737003 "Here.")
Try using the header function. ``` header("Location: $url"); ```
open a new html page through php
[ "", "php", "html", "" ]
I am working on my MacBook at home, running Leopard, with the latest JDK 1.6 from Apple installed. In IDE, I'd like to browse source code for com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel, but IDE cannot find it. Another example I'd like to browse is com.sun.java.swing.plaf.nimbus.ButtonPainter. What JAR or ZIP do I need to add to my IDEA project in order to browse com.sun.*.nimbus.* classes inside IDE I'm only interested in Leopard, because this works fine on Windows with Sun's JDk. I know the Nimbus classes are available, because my app runs with the Nimbus Look and Feel.
The Nimbus classes are here in my 1.6 Mac installation: /System/Library/Frameworks/JavaVM.framework/Versions/1.6/Classes/classes.jar and I would jad them if you need the source. I use JadClipse to view jad'ed source inside Eclipse. It's not perfect of course, but serves in a pinch. You can also get JDK 1.6 source here: * <http://download.java.net/jdk6/source/> If you extract it, you can find the Nimbus source down under Work/j2se/src/share/classes/com/sun/java/swing/plaf/nimbus So could theoretically hook that up to the classes.jar and maybe get something to work too.
Unfortunately, the source for these libraries is not often distributed. If you want to inspect the code, you could download a decompiler and decompile the jars in your install. [Here is a link to wikipedia](http://en.wikipedia.org/wiki/JAD_(JAva_Decompiler)) that has a few follow-up links for download sites for JAD, a decompiler that will do the job.
Where is Java source code for various com.sun.* packages on Leopard?
[ "", "java", "intellij-idea", "osx-leopard", "nimbus", "" ]
There's a stored procedure called "cnt\_insertContestEntry" in my company's database. I'm new to database naming conventions. What could CNT possibly mean? Contest? i could ask my co-workers but i don't want to look dumb :p.
I had a hard time making this sound nice, and I'm not sure if I succeeded. It is rather strange to ask people who are unlikely to know the answer when you have people much nearer who are quite likely to know the answer. In general, if you want to know the answer, ask the person most likely to have it. In my opinion, that is never going to make you look dumb!
"cnt" is commonly used as an abbreviation for "count", often in variable names as a part of Hungarian notation. I don't think that's how it's being used here, though. Your guess sounds reasonable. I'd ask.
What does CNT stand for in naming stored procedures?
[ "", "sql", "database", "" ]
Is there a way in python to increment int object in place, int doesn't seem to implement `__iadd__` so += 1 actually returns a new object ``` >>> n=1 >>> id(n) 9788024 >>> n+=1 >>> id(n) 9788012 ``` What I want is n to remain pointing to same object. Purpose: I have class derived from int and I want to implement C type '++n' operator for that class Conclusion: ok as int is immutable there is no way, looks like i will have to write my own class something like this ``` class Int(object): def __init__(self, value): self._decr = False self.value = value def __neg__(self): if self._decr: self.value -= 1 self._decr = not self._decr return self def __str__(self): return str(self.value) def __cmp__(self, n): return cmp(self.value, n) def __nonzero__(self): return self.value n = Int(10) while --n: print n ```
ints are immutable, so you'll have to build your own class with all the int's methods if you want a "mutable int"
You can use ctypes as mutable integers. Choosing the right ctype will be important though, as they limit the size of integer they can carry. ``` >>> from ctypes import c_int64 >>> num = c_int64(0) >>> id(num) 4447709232 >>> def increment(number): ... number.value += 1 ... >>> increment(num) >>> increment(num) >>> increment(num) >>> num.value 3 >>> id(num) 4447709232 >>> ``` More info: <https://docs.python.org/2/library/ctypes.html#fundamental-data-types>
increment int object
[ "", "python", "int", "" ]
``` function validation(reg) { str = document.reg; if (str.name.value == "") { alert("Enter your name"); str.name.focus(); return false; } ``` Validation will working fine if input is empty. Problem 1. User can enter a blank space on the first. 2. Also user can enter space only on the name. How to prevent it?
Here are some trim functions. <http://www.somacon.com/p355.php> and using it ``` function validation(reg) { str = document.reg; if (str.name.value.trim() == "") { alert("Enter your name"); str.name.focus(); return false; } ```
Test the length of the value with all spaces removed. ``` if (str.name.value.replace(/\s+/g, '').length == 0) { ```
javascript - blank space validation
[ "", "javascript", "" ]
With a `GridView` control in .NET is there any way to change the `Select` option in a `GridView` to a `Checkbox`, how do you select multiple rows? I tried adding a `CheckBoxField` into my `GridView` but when I ran it it didn't show up.
Adding checkbox to Gridview is as simple as adding TemplateField of any control. > I tried adding a CheckBoxField into my > gridview but when I ran it it didn't > show up. There should be other columns binding data to the grid. Also, check visible property of checkbox. Refer to this link for more on this. [link text](http://www.asp.net/learn/data-access/tutorial-52-cs.aspx)
I always just add a column to the DataTable that I am binding to. ``` dt.Columns.Add(new DataColumn("Include", typeof(Boolean))); ``` Or in my SQL I will have: ``` declare @include bit set @include = 0 select @include Include, .... ``` More can be found on my blog [here](http://blog.digitaltools.com/post/2009/07/14/Multiple-Row-Selections-in-a-GridView-with-checkboxes.aspx "GridViewCheckBoxes")
Using a CheckBox to Select Rows in an ASP.NET GridView
[ "", "c#", ".net", "asp.net", "gridview", "webforms", "" ]
this snippet of code is given me headache. Personally, I would like to use reference as they are neater compared to pointer, so I tried this: ``` include "SomeClass.h" class FooBar { private: SomeClass& member_; public: FooBar() : member_(SomeClass()) { }; } ``` I have read that you need to assign a temp variable to a class member reference, so in this case I create a dummy SomeClass() (I'm not sure if I am doing it right here. I tried it with and without specifying a default constructor). However, it does not compile in VS 2005, saying that member\_ cannot be initialised. How should I be doing this? Thanks in advance!
1) References can not be changed to point to another object after it is initialized. Do you really need this behavior? 2) When you initialize reference with temporary object, after this temp. object is out of scope your reference is invalid. That's why your code is incorrect. And you have useless member now. I'd recommend to think about two alternatives a) Consider using pointer instead of reference. b) Change you constructor to something like this: ``` MyClass(type & a):membmer_(a){...} ```
You can only bind a temp to a const reference. So if you change it to ``` const SomeClass& member_; ``` you'll be fine. You probably don't want this, though; you either should just declare `member_` as a value, not reference, or, if you want it as a reference, you probably want to pass in a reference to your constructor, like ``` FooBar(SomeClass& sc) : member_(sc) { }; ```
Custom-typed Reference members in C++ - initialising them
[ "", "c++", "reference", "" ]
I'm trying to use SQLite3 in C#.NET. I've googled around and found some different API's. I also checked SQLite's website for wrappers. I like them, but want to write my own wrapper without using an added dependency. All wrappers I find that don't require an added dependency aren't free. **I'm wondering how one would read from, execute, and write to a sqlite3 database. Is it a socket connection(tcp? udp? etc?)?** I've tried searching this answer on google and all I get are library-specific answers. :/ SQLite's website docs aren't much help either. **EDIT:** I also found a [COM interface](http://blog.gobansaor.com/2007/06/01/dhsqlite-new-sqlite-com-wrapper/) while googling, but is that library specific? Thanks SO! :)
Have you looked at the [System.Data.SQLite](http://system.data.sqlite.org/) library? It's a free ADO.NET library to interact with SQLite and requires nothing else in order to run, since it has the engine built into it. I've been using it for a while now and find it really easy to work with. It even has a plugin for Visual Studio should you decide to use some strongly-typed tables with it or want to use it to add/create tables.
(Answering the "socket connection" question.) Part of the point of SQLite is that it's an embedded database - there's no server to talk to, you load the library directly into your process and it talks to the file system directly.
SQLite3 in C#.NET
[ "", "c#", ".net", "sqlite", "wrapper", "" ]
I am in the process of writing a small javascript library to make form creation/validation easier. This is mostly an excuse to get better with javascript. I am debating about how to take in user input for form element creation. I am looking at two approaches. One is to take in a few pre-determined parameters such as id, label, value The other is to take in a single object which will be used to write properties straight into the form element. So for example if I wanted to pass in id label and value, I would simply pass in {id : 'my\_id', label : 'my\_label', value : 'my\_value} The third option is to take in id, label, options where options is an object which does what I have described above. Right now the passing an object in seems the most flexible, but I wonder if there are any serious downsides to this? I would like this to be easy to use for most javascript users. Any thoughts on the best way to do this?
The usual way of handling this is with an options object as in your second choice. Most plugins (and jQuery methods) that require options use that pattern. As far as I'm aware there are no downsides to this and as its a very common way of handling options, I don not see it being hard to use for others. Option 3, is also acceptable if you have something that absolutely must be passed in eg. id. Just in that case the options object is most commonly found as the final parameter of the function. Hope this helps
Using objects seems to be the "standard" way to do that in the JS code that I've studied. Using a list of specific parameters, which adds an ordering requirement, quickly gets out of hand when you have more than a few parameters. If you have a "dependent" parameters, e.g., ones that only appear for certain values of another parameter, then that's especially ugly when using a simple parameter list. Be careful when iterating over the properties of an object, however. It's easy to get inherited elements that aren't intended. Douglas Crockford [recommends](http://javascript.crockford.com/code.html) using hasOwnProperty() to check for this case.
hash vs specific parameters
[ "", "javascript", "forms", "object", "creation", "" ]
I have a situaion in which I want to declare a class member function returning a type that depends on the class itself. Let me give you an example: ``` class Substring { private: string the_substring_; public: // (...) static SubstringTree getAllSubstring(string main_string, int min_size); }; ``` And SubstringTree is defined as follows: ``` typedef set<Substring, Substring::Comparator> SubstringTree; ``` My problem is that if I put the SubstringTree definition after the Substring definition, the static method says it doesn't know SubstringTree. If I reverse the declarations, then the typedef says it doesn't know Substring. How can I do it? Thanks in advance.
You could define it inside the class: ``` class Substring { private: string the_substring_; public: // (...) typedef set<Substring, Substring::Comparator> SubstringTree; static SubstringTree getAllSubstring(string main_string, int min_size); }; ```
As you've written it, the short answer is you can't. You do have a few close alternatives: 1) Declare SubstringTree in Substring ``` class Substring { public: class Comparator; typedef set< Substring, Comparator> Tree; private: string the_substring_; public: // (...) static Tree getAllSubstring(string main_string, int min_size); }; typedef Substring::Tree SubstringTree; ``` 2) Define the Comparator outside of Substring: ``` class Substring; class SubstringComparator; typedef set< Substring, SubstringComparator> SubstringTree; class Substring { public: private: string the_substring_; public: // (...) static SubstringTree getAllSubstring(string main_string, int min_size); }; ``` 3) You can use a template to delay the lookup until you have more declarations: ``` template <typename String> struct TreeHelper { typedef set< String, typename String::Comparator> Tree; }; class Substring { public: class Comparator; private: string the_substring_; public: // (...) static TreeHelper<Substring>::Tree getAllSubstring(string main_string , int min_size); }; typedef TreeHelper<Substring>::Tree SubstringTree; ```
Forward "Pre-declaring" a Class in C++
[ "", "c++", "class", "substring", "" ]
I'm looking for some sort of TimeRange widget in Javascript/CSS/jQuery. I'm not looking for a time/date picker, which are widely available. I need it for a website to allow businesses to select their openinghours by clicking and hovering over the hours they're open. ``` +-----------------------------+ | 0h 0h15m 0h30m ... 23:45 | +-----------------------------+ ``` Anybody has seen such a nice looking customizable timerange selector widget? Cheers
I'd look for a slider widget.. then set the times you need as the intervals. The jQuery UI has one: [jQuery UI Slider](http://docs.jquery.com/UI/Slider). **Update:** based on the comment below about (single vs. double slider)... 1.) Theres a post already (just found) about making a [2 handled slider using the jQuery UI slider here](https://stackoverflow.com/questions/348187/jquery-slider-range). Or if you have 2 sliders... one for opening time and one for closing... where each is broken down into 15min segments, but only for half a day each, would this work? e.g. (ignore the ASCII-graphic uglyness) ``` Open Time (AM): 12 1 2 3 4 5 6 7 8 | 9 10 11 12 ^ 8:15am Close Time (PM): 12 1 2 3 4 5 6 | 7 8 9 10 11 12 ^6:30pm ``` Furthermore, if this is for "typical" businesses... you could likely chop from 11pm <-> 5am from the sliders. Or, I'm not a big fan of scriptaculous, but they seem to have a [double slider](http://wiki.github.com/madrobby/scriptaculous/slider):
Google Calendar has nice one (you can see it when you click "Check guest and resource availability" link on the event details form). But I can imagine it would be hard to clone. [![Google Calendar Time Ranage](https://i.stack.imgur.com/vHdEW.jpg)](https://i.stack.imgur.com/vHdEW.jpg) (source: [rajchel.pl](http://stuff.rajchel.pl/stackoverflow/GoogleCalendarTimeRange.jpg))
Where can I find a time range widget in Javascript/jQuery?
[ "", "javascript", "jquery", "time", "widget", "" ]
I've been learning C++ for about a month now, and as I've written programs I've noticed that enabling the user to cancel their input (during a cin loop) is a pain. For example, a program that takes user input and stores it in a vector would have a cin loop like this. ``` vector<int>reftest; int number; cout << "Input numbers for your vector.\n"; while(cin >> number) reftest.push_back(number); ``` The ideal would be for the user to simply press enter, and for the program to exit the loop, but since whitespace isn't read I'm not sure how this would be handled. Instead, something ugly usually ends up being the case like telling the user to input a certain character to cancel their input. Are there any certain methods that any of you use to handle user input?
There are several ways to approach your problem. The easiest is probably to move out of a direct cin/cout loop and to use std::getline instead. Specifically, you could write something like: ``` #include <iostream> #include <vector> #include <sstream> using namespace std; int main( int argc, char **argv ) { vector<int> reftest; while ( true ) { string input; getline( cin, input ); // You can do whatever processing you need to do // including checking for special values or whatever // right here. if ( input.size() == 0 ) // empty input string { cout << "Assuming you're bored with the Entering Numbers game." << endl; break; } else { int value; // Instead of using the input stream to get integers, we // used the input stream to get strings, which we turn // into integers like this: istringstream iss ( input ); while ( iss >> value ) { reftest.push_back( value ); cout << "Inserting value: " << value << endl; } } } } ``` Other approaches include cin.getline() (which I'm not a big fan of because it works on char\* instead of strings), using the cin.fail() bit to figure out whether or not the incoming value was any good, etc. And depending on your environment, there are probably many richer ways of getting user input than through iostreams. But this should point you towards the information you need.
How about making a second loop like this: ``` char option; do { cout << "do you want to input another number? (y)es/(n)o..." << endl; cin >> option; if ( option == 'y' ) acceptInput(); // here enter whatever code you need } while ( option != 'n' ); ```
What are some effective methods for handling user keyboard input
[ "", "c++", "" ]
I am looking for ideas on the best way to persist an array of values from one web session to the next. I will be populating a Checkbox list and would like to persist the last set of selected checkboxes to the next session. (this is meant to save time for the user since they will likely always select the same subset of checkboxes.) I will be iterating through the checkbox list and putting the selected values into an arraylist. Where would be a good place to presist this set of data? I looked at storing the object to database or possibly an XML file on the server. I also considered pushing the data to the web.config but would like to avoid an application restart. Any opinions or suggestions? TIA J
If you already are using a database for your application, I would be inclined to save the state of the check boxes in the database. Reason is because databases are already equipped to handle multiple instances of people accessing the application and concurrency issues are easier to handle. Not to mention more scalable. I would create a table that has enough columns to capture all the information about each check box. For Example: ``` CREATE TABLE [CheckBoxStatus] ( [CheckBoxID] nvarchar(50), [bool] bit NULL DEFAULT 0, [SessionID] nvarchar(50)); ``` On load of your page, you can interate through all of the check-boxes that are in your page, querying for their ID's inside this table. If there is no record of it, it means no one has selected the checkbox yet. If there is, then load the boolean checked status and update the checkbox on the page. Same goes if you save, just insert Boolean values with the corresponding checkboxID and SessionID. This should also work if your checkboxID's are created dynamically somehow. You only have to be careful that whatever generates your checkboxID's to be sure that it always generates the same ID for a particular kind of a checkbox. So, if it is something like "Red Car" then every where that "Red Car" is displayed in the same context, the same ID needs to be generated.
There are really only two ways to do what you are talking about. 1. Have a variable at the application level which stores this information. Downside is that it gets cleared whenever the web app recycles. 2. Store it in a database table. Downside is that it requires a database call to get the data. Allowing the site to write to the web.config is bad because it's a potential security risk. Same goes for allowing the site to write anything to disk. Sometimes we can't avoid it (file uploads), but we can at least contain it to non-executable areas. Personally, for a site wide semi-permanent item I'd go with a combination of the two. I'd store it in a database table, but cache the results of the db call in an application level variable. If my backend was sql 2005 or 2008, I might even take it a step further and use the SqlCacheDependency object so that the cache get's invalidated as soon as an update occurs on that db table.
Best practice for saving and recalling selected checkboxes on an asp.net page
[ "", "c#", "asp.net", "configuration", "" ]
I’m programming one easy C# application, and i need onScroll event on Listview. So i created class ListviewEx witch inherits original ListView. I found how to detect scroll message from WinAPI and i modified WndProc method. Now i have this WndProc: ``` protected override void WndProc(ref Message m) { base.WndProc(ref m); if (m.Msg == WM_VSCROLL) { onScroll(this, new EventArgs()); } } ``` But problem is, that I dont know how to detect information about scrolling. This data should be in WParam, but in C# is no LOWORD macro like in C++ and i need switch to detect parameters like SB\_ BOTTOM, SB\_ ENDSCROLL, SB\_PAGEUP etc. Is there any way how to replace LOWORD macro in C# ? Or other way how to detect necessary parameters about scrolling?
You can define WParam constants as followed: ``` private const int WM_HSCROLL = 0x114; private const int WM_VSCROLL = 0x115; private const int SB_HORZ = 0; private const int SB_VERT = 1; private const int SB_LINELEFT = 0; private const int SB_LINERIGHT = 1; private const int SB_PAGELEFT = 2; private const int SB_PAGERIGHT = 3; private const int SB_THUMBPOSITION = 4; private const int SB_THUMBTRACK = 5; private const int SB_LEFT = 6; private const int SB_RIGHT = 7; private const int SB_ENDSCROLL = 8; private const int SIF_TRACKPOS = 0x10; private const int SIF_RANGE = 0x1; private const int SIF_POS = 0x4; private const int SIF_PAGE = 0x2; private const int SIF_ALL = SIF_RANGE | SIF_PAGE | SIF_POS | SIF_TRACKPOS; ``` The actual code to inspect the WParam would be something like this: ``` if (m.Msg == WM_VSCROLL) { ScrollInfoStruct si = new ScrollInfoStruct(); si.fMask = SIF_ALL; si.cbSize = (uint)Marshal.SizeOf(si); GetScrollInfo(msg.HWnd, SB_VERT, ref si); if (msg.WParam.ToInt32() == SB_ENDSCROLL) { ScrollEventArgs sargs = new ScrollEventArgs(ScrollEventType.EndScroll, si.nPos); onScroll(this, sargs); } } ``` pinvoke.net is a great site to get the constant values used in windows32 API without having to inspect header files yourself. [See this example](http://www.pinvoke.net/default.aspx/Enums/ScrollBarCommands.html)
Thanks for your answers. It really helped me :) Now I have what I wanted... Here is code: ``` using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using System.Runtime.InteropServices; using Microsoft.Win32; using System.Reflection; namespace ControlsEx { public class ListViewEx : ListView { // Windows messages private const int WM_PAINT = 0x000F; private const int WM_HSCROLL = 0x0114; private const int WM_VSCROLL = 0x0115; private const int WM_MOUSEWHEEL = 0x020A; private const int WM_KEYDOWN = 0x0100; private const int WM_LBUTTONUP = 0x0202; // ScrollBar types private const int SB_HORZ = 0; private const int SB_VERT = 1; // ScrollBar interfaces private const int SIF_TRACKPOS = 0x10; private const int SIF_RANGE = 0x01; private const int SIF_POS = 0x04; private const int SIF_PAGE = 0x02; private const int SIF_ALL = SIF_RANGE | SIF_PAGE | SIF_POS | SIF_TRACKPOS; // ListView messages private const uint LVM_SCROLL = 0x1014; private const int LVM_FIRST = 0x1000; private const int LVM_SETGROUPINFO = (LVM_FIRST + 147); public enum ScrollBarCommands : int { SB_LINEUP = 0, SB_LINELEFT = 0, SB_LINEDOWN = 1, SB_LINERIGHT = 1, SB_PAGEUP = 2, SB_PAGELEFT = 2, SB_PAGEDOWN = 3, SB_PAGERIGHT = 3, SB_THUMBPOSITION = 4, SB_THUMBTRACK = 5, SB_TOP = 6, SB_LEFT = 6, SB_BOTTOM = 7, SB_RIGHT = 7, SB_ENDSCROLL = 8 } protected override void WndProc(ref Message m) { base.WndProc(ref m); switch(m.Msg) { case WM_VSCROLL: ScrollEventArgs sargs = new ScrollEventArgs(ScrollEventType.EndScroll, GetScrollPos(this.Handle, SB_VERT)); onScroll(this, sargs); break; case WM_MOUSEWHEEL: ScrollEventArgs sarg = new ScrollEventArgs(ScrollEventType.EndScroll, GetScrollPos(this.Handle, SB_VERT)); onScroll(this, sarg); break; case WM_KEYDOWN: switch (m.WParam.ToInt32()) { case (int)Keys.Down: onScroll(this, new ScrollEventArgs(ScrollEventType.SmallDecrement, GetScrollPos(this.Handle, SB_VERT))); break; case (int)Keys.Up: onScroll(this, new ScrollEventArgs(ScrollEventType.SmallIncrement, GetScrollPos(this.Handle, SB_VERT))); break; case (int)Keys.PageDown: onScroll(this, new ScrollEventArgs(ScrollEventType.LargeDecrement, GetScrollPos(this.Handle, SB_VERT))); break; case (int)Keys.PageUp: onScroll(this, new ScrollEventArgs(ScrollEventType.LargeIncrement, GetScrollPos(this.Handle, SB_VERT))); break; case (int)Keys.Home: onScroll(this, new ScrollEventArgs(ScrollEventType.First, GetScrollPos(this.Handle, SB_VERT))); break; case (int)Keys.End: onScroll(this, new ScrollEventArgs(ScrollEventType.Last, GetScrollPos(this.Handle, SB_VERT))); break; } break; } } public int ScrollPosition { get { return GetScrollPos(this.Handle, SB_VERT); } set { int prevPos; int scrollVal; if (ShowGroups == true) { prevPos = GetScrollPos(this.Handle, SB_VERT); scrollVal = -(prevPos - value); } else { // TODO: Add setScrollPosition if ShowGroups == false } SendMessage(this.Handle, LVM_SCROLL, (IntPtr)0, (IntPtr)scrollVal); } } public event ScrollEventHandler onScroll; [DllImport("user32.dll")] [return: MarshalAs(UnmanagedType.Bool)] private static extern bool GetScrollInfo(IntPtr hwnd, int fnBar, ref SCROLLINFO lpsi); [DllImport("user32.dll")] public static extern int SendMessage( int hWnd, // handle to destination window uint Msg, // message long wParam, // first message parameter long lParam // second message parameter ); [DllImport("user32.dll")] static extern int SendMessage(IntPtr hWnd, int wMsg, int wParam, int lParam); [DllImport("user32.dll")] static extern int SendMessage(IntPtr hWnd, uint wMsg, IntPtr wParam, IntPtr lParam); [DllImport("user32.dll")] static extern int SetScrollPos(IntPtr hWnd, int nBar, int nPos, bool bRedraw); [DllImport("user32.dll", CharSet = CharSet.Auto)] static extern int GetScrollPos(IntPtr hWnd, int nBar); [StructLayout(LayoutKind.Sequential)] struct SCROLLINFO { public uint cbSize; public uint fMask; public int nMin; public int nMax; public uint nPage; public int nPos; public int nTrackPos; } } } ```
ListView onScroll event
[ "", "c#", ".net", "winforms", "listview", "" ]
Is it possible get the last visited pages by user using C# / ASP.NET (without using javascript)
You can get in some cases the page from which the user came with [Referer](http://msdn.microsoft.com/en-us/library/system.net.httpwebrequest.referer.aspx).
This may be what you are looking for. This'll add the last page's url to a string. [ C# ] ``` string MyReferrer = Request.UrlReferrer.ToString(); ``` [ VB.NET ] ``` Dim MyReferrer As String = Request.UrlReferrer.ToString() ```
Get the last visited pages of a User of our ASP.NET Site?
[ "", "c#", "asp.net", "" ]
I've run across something that's bugging me just enough that I wanted to come here and seek out a sort of "best practice" type of advice from you guys (et gals) I have a table in my model, let's call it `prospect`. Two separate external systems can provide an update for rows in this table, but only as a "status" of that record in those respective systems. I need to store those statuses locally. Initial idea, of course, it just to make two nullable foreign keys. Something like this. ``` +-----------------+--------------+------+-----+---------+----------------+ | Field | Type | Null | Key | Default | Extra | +-----------------+--------------+------+-----+---------+----------------+ | prospect_id | int(11) | NO | PRI | NULL | auto_increment | | ext_status_1_id | int(11) | YES | | NULL | | | ext_status_2_id | int(11) | YES | | NULL | | +-----------------+--------------+------+-----+---------+----------------+ ``` In this example there would be, of course, two tables that hold id/value pairs for statuses. Here's the catch - `ext_status_2_id` will *always* be NULL unless `ext_status_1_id` is `1` (this is just how the business rules work). Have I modeled this correctly? I just have this nagging voice in the back of my brain telling me that "not every row in prospect will need an `ext_status_2_id` so this might not be right". If it matters, this is MySQL 5.0.45 and I'm using InnoDB
Since there is an in-built dependency for Status2 on Status1, why not just have a single status field on the prospect table, and create Status2 as a property on the Status1 table? It is certainly normalized heavily in this fashion but having the data structure this way speaks about the dependency of Status2 on Status1.
This is probably fine. But since you'll always only use 1 of the 2, you could model it as : ext\_status\_type (either 1 or 2) and ext\_status for the actual id. I would probably do the same as you did, because it might be easier to build indexes around this and both numbers appear to have a true different meaning. If there will be more statuses (3,4,5,6) I would consider the first approach in my answer.
Data Modeling - how to handle two, dependent "status" columns?
[ "", "sql", "mysql", "data-modeling", "" ]
I want to use Eclipse to develop C++ projects on Linux. Particularly I want to modify stable and widely used open source projects using the Eclipse CDT. One of them is Intel Opencv. There are tutorials to create simple c++ projects like here: * <http://www.ibm.com/developerworks/opensource/library/os-eclipse-stlcdt/> . I have seen plenty of tutorials for using Eclipse CDT to write programs in OpenCv like here: * <http://opencv.willowgarage.com/wiki/Eclipse> * <http://tommy.chheng.com/development/windows_development_setup.html> * <http://tommy.chheng.com/index.php/2009/05/opencv-with-eclipse-on-windows/> However I want to use Eclipse to make changes to the OpenCv platform itself and compile it from there. I really like many of Eclipse's features like: * Syntax highlighting * Outline * Code assist * Code templates * Code history * etc. Would someone write a small tutorial on how one can make a project in Eclipse from the OpenCv tarball? I would use Eclipse CDT on Linux. Can Eclipse CDT recognize Makefile as it can do for Ant scripts?
I made the experience that for OpenCV using [cmake](http://www.cmake.org/) is the way to go. You can unzip the cmake source code and use cmake to compile it. Even after your changes. There are some tools to integrate cmake into eclipse but I found them unstable or not very mature so I use cmake from a terminal to compile and eclipse for editing the source files.
If you follow Janusz's advice about using cmake you can find here a good [tutorial](http://www.vtk.org/Wiki/CMake:Eclipse) about using cmake and its eclipse projects generator (I actually followed it no long time ago :-) ). In this [link](http://www.vtk.org/Wiki/Eclipse_CDT4_Generator) you will find more information about that generator (Eclipse CDT4 Generator)
Using Eclipse C++ CDT in Linux
[ "", "c++", "linux", "eclipse", "opencv", "" ]
I'm coding a simple text editor using Windows Forms. As in many editors, when the text changes the title bar displays an asterisk next to the title, showing that there is unsaved work. When the user saves, this goes away. However, there is a problem. This is handled in the change event of the main text box. But this gets called too when a file is opened or the user selects "New file", so that if you open the editor and then open a file, the program says that there are unsaved changes. What is a possible solution? I thought of having a global variable that says whether the text changed in a way that shouldn't trigger the asterisk, but there has to be a better way.
before loading data to a textbox, unassociate first the eventhandler for change ``` uxName.TextChanged -= uxName_TextChanged; uxName.Text = File.ReadAllText("something.txt"); uxName.TextChanged += uxName_TextChanged; ```
This is a horrible solution, but every time the text change event fires, compare the value of the textbox to some variable, and if they are different store the contents on the textbox in a variable and add the asterisk. When the method is invoked via the New File dialog or any other such event that is NOT changing the text, the asterisk won't appear. This is not a viable solution for a real text editor since the memory would quickly get out of hand on even medium-sized files. Using a finger tree or whatever data structure text editors use to compare "versions" of the text is the only real efficient solution, but the premise is the same. <http://scienceblogs.com/goodmath/2009/05/finally_finger_trees.php> Below the second picture he mentions the use of finger trees in text editors to implement an extremely cheap "undo" feature, but I'm sure you can see the validity of the tree for your problem as well.
How to detect previous state of text field in C#?
[ "", "c#", "winforms", "text-editor", "" ]
I have some places where implementing some sort of cache might be useful. For example in cases of doing resource lookups based on custom strings, finding names of properties using reflection, or to have only one `PropertyChangedEventArgs` per property name. A simple example of the last one: ``` public static class Cache { private static Dictionary<string, PropertyChangedEventArgs> cache; static Cache() { cache = new Dictionary<string, PropertyChangedEventArgs>(); } public static PropertyChangedEventArgs GetPropertyChangedEventArgs( string propertyName) { if (cache.ContainsKey(propertyName)) return cache[propertyName]; return cache[propertyName] = new PropertyChangedEventArgs(propertyName); } } ``` But, will this work well? For example if we had a whole load of different propertyNames, that would mean we would end up with a huge cache sitting there never being garbage collected or anything. I'm imagining if what is cached are larger values and if the application is a long-running one, this might end up as kind of a problem... or what do you think? How should a good cache be implemented? Is this one good enough for most purposes? Any examples of some nice cache implementations that are not too hard to understand or way too complex to implement?
You could wrap each of your cached items in a [`WeakReference`](http://msdn.microsoft.com/en-us/library/system.weakreference.aspx). This would allow the GC to reclaim items if-and-when required, however it doesn't give you any granular control of when items will disappear from the cache, or allow you to implement explicit expiration policies etc. (Ha! I just noticed that the example given on the [MSDN page](http://msdn.microsoft.com/en-us/library/system.weakreference.aspx) is a simple caching class.)
This is a large problem, you need to determine the domain of the problem and apply the correct techniques. For instance, how would you describe the expiration of the objects? Do they become stale over a fixed interval of time? Do they become stale from an external event? How frequently does this happen? Additionally, how many objects do you have? Finally, how much does it cost to generate the object? The simplest strategy would be to do straight memoization, as you have above. This assumes that objects never expire, and that there are not so many as to run your memory dry *and* that you think the cost to create these objects warrants the use of a cache to begin with. The next layer might be to limit the number of objects, and use an implicit expiration policy, such as LRU (least recently used). To do this you'd typically use a doubly linked list in addition to your dictionary, and every time an objects is accessed it is moved to the front of the list. Then, if you need to add a new object, but it is over your limit of total objects, you'd remove from the back of the list. Next, you might need to enforce explicit expiration, either based on time, or some external stimulus. This would require you to have some sort of expiration event that could be called. As you can see there is alot of design in caching, so you need to understand your domain and engineer appropriately. You did not provide enough detail for me to discuss specifics, I felt. P.S. Please consider using Generics when defining your class so that many types of objects can be stored, thus allowing your caching code to be reused.
C#: How to implement a smart cache
[ "", "c#", "performance", "caching", "resources", "memory-management", "" ]
Which packages of [Felix](http://felix.apache.org/site/index.html) do I need to get started? There are a zillion of them on the [downloads page](http://felix.apache.org/site/downloads.cgi). (p.s. is the name a reference to the Odd Couple + in contrast to OSGI's "Oscar" reference framework? this occurred to me after reading one of the tutorial pages & I got a chuckle out of it.)
You just need to download the "main" distribution at: <http://apache.mirror.clusters.cc/felix/felix-1.8.0.tar.gz> (it is the first download link) Unzip it, enter in the felix-1.8.0 directory and type $ java -jar bin/felix.jar The Felix console will appear, type "help" to get started
My answer is not really about "how to", but about "where" to look. I highly recommend OSGi and Apache Felix 3.0 Beginner's Guide by Walid Joseph Gédéon. I was using Equinox but after this book switched to Felix, it is just so well written. Regarding felix bundles I am most commonly running Gogo Comman+Runtime+Shell, iPOJO, Log and Http (jetty/whiteboard). P.S.: Just to add another book, that I think will become a classic - [OSGI in Action](http://www.manning.com/hall/). You can buy early access from manning. In combination with the Official OSGI Specs this will lay a solid foundation.
getting started with osgi + felix
[ "", "java", "osgi", "apache-felix", "" ]
Currently, I've created a class with ~30 properties to be set. This is done to build up a URL request later on(ie, "<http://www.domain.com/test.htm?var1=a&var2=b...&var30=dd>"). The issue I'm facing is the property names don't necessarily match the query variable names(this is intended to be different). For example, I may have a variable titled "BillAddress", whereas the query variable will need to be "as\_billaddress". I have no control over the query variable naming scheme as these are set at an external source. One possible solution I've used is creating a custom attribute and decorating the properties with their respective query counterparts: ``` [CustomQueryAttribute("as_billaddress")] string BillAddress{get;set;} ``` To retrieve the attribute though, requires a little reflection and due to the larger number of properties, I was curious if there is a neater way to accomplish this functionality. Not so much as setting/retrieving custom attributes without reflection, but being able to tie an alternate string variable to any property. I've also pondered about setting each variable up as a sort of KeyValuePair, with each key representing the query counterpart, but I didn't get too far in that thought. To summarize/clarify my above backstory, what would you do to associate a string with a property(not the value of the property)? As always, any comments are greatly appreciated.
I would probably stick with a custom attribute, but the other potential option would be to do something like hold a static Dictionary that had string and property info (or property name), so you could get/set the property directly via this. Something like: ``` static Dictionary<string, PropertyInfo> propertyMap = new Dictionary<string, PropertyInfo>(); static MyClass() { Type myClass = typeof(MyClass); // For each property you want to support: propertyMap.Add("as_billaddress", MyClass.GetProperty("BillAddress")); // ... } ``` You could then just do a dictionary lookup instead of using reflection in each call... This could also be setup fairly easy using configuration, so you could reconfigure the mappings at runtime.
A custom attribute seems like the best option to me - the framework seems to do this a lot as well (specifically with serialization).
C# Custom Attribute Alternatives
[ "", "c#", "" ]
I know how to launch a process with Admin privileges from a process using: ``` proc.StartInfo.UseShellExecute = true; proc.StartInfo.Verb = "runas"; ``` where proc is a System.Diagnostics.Process. But how does one do the opposite? If the process you're in is already elevated, how do you launch the new process without admin privileges? More accurately, we need to launch the new process with the same permission level as Windows Explorer, so no change if UAC is disabled, but if UAC is enabled, but our process is running elevated, we need to perform a certain operation un-elevated because we're creating a virtual drive and if it's created with elevated permissions and Windows explorer is running unelevated it won't show up. Feel free to change the title to something better, I couldn't come up with a good description.
We ended up using the sample from this Code Project article: [High elevation can be bad for your application: How to start a non-elevated process at the end of the installation](http://www.codeproject.com/KB/vista-security/RunNonElevated.aspx) It seems to work so far, I gather it injects into RunDll32.exe, my C++/Win32 is fairly weak so I didn't look too much into the actual implementation, just it's use. Confirmed that it works in Vista and Win7 both x86 and x64 (at least for us, x86 and x64 require different dll's which is checked for at install time and the proper one is used).
The solution for you is to use EXPLORER.exe process. The idea is to run the process in UN-ELEVATED mode, using windows's file explorer process `explorer.exe` ([info](http://en.wikipedia.org/wiki/File_Explorer_%28Windows%29)). Lets say the process that we want to launch is on `$TEMP\MyUnElevatedProcess.exe`. So, for NSIS code, I will just write: (but can be run in ANY language) ``` Exec '"$WINDIR\explorer.exe" "$TEMP\MyUnElevatedProcess.exe"' ``` Example code (**using NSIS installer**) ``` Exec '"$WINDIR\explorer.exe" "$TEMP\MyUnElevatedProcess.exe"' ``` \*\*\*code taken from <http://mdb-blog.blogspot.com/2013/01/nsis-lunch-program-as-user-from-uac.html>
How do you de-elevate privileges for a child process
[ "", "c#", "process", "uac", "elevation", "" ]
``` HttpGet httpget = new HttpGet("http://www.google.com/"); System.out.println("executing request " + httpget.getURI()); // Create a response handler ResponseHandler<String> responseHandler = new BasicResponseHandler(); String responseBody = httpclient.execute(httpget, responseHandler); ``` this will get responseBody as "string" , how to get btye[] with httpclient.execute(..) ? the reason i want to get byte[] is because i want to write to some other outputstream
``` public byte[] executeBinary(URI uri) throws IOException, ClientProtocolException { HttpGet httpget = new HttpGet(uri); HttpResponse response = httpclient.execute(httpget); HttpEntity entity = response.getEntity(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); entity.writeTo(baos); return baos.toByteArray(); } ```
You can use the responseBody.getBytes() to get byte[].
httpclient 4 how to get bytes
[ "", "java", "http", "servlets", "" ]
In my application I am creating an object pretty much like this : ``` connect() { mVHTGlove = new vhtGlove(params); } ``` and once I am about to close application I call this one : ``` disconnect() { if (mVHTGlove) delete mVHTGlove; } ``` This call always triggers a breakpoint with the following message : > Windows has triggered a breakpoint in > DesignerDynD.exe. > > This may be due to a corruption of the > heap, which indicates a bug in > DesignerDynD.exe or any of the DLLs it > has loaded. > > This may also be due to the user > pressing F12 while DesignerDynD.exe > has focus. > > The output window may have more > diagnostic information. I cannot modify the vhtGlove class to fix the corruption of the stack as it is an external library provided only in the form of header files, lib files and dlls. Is there any way to use this class in a clean way ? --- \*\*\*\* EDIT ::: I tried to strip things down to a bare minimum, however I get the same results... here you have the ENTIRE code. ``` #include "vhandtk/vhtCyberGlove.h" #include "vhandtk/vhtIOConn.h" #include "vhandtk/vhtBaseException.h" using namespace std; int main(int argc, char* argv[]) { vhtCyberGlove* testGlove = NULL; vhtIOConn gloveAddress("cyberglove", "localhost", "12345", "com1", "115200"); try { testGlove = new vhtCyberGlove(&gloveAddress,false); if (testGlove->connect()) cout << "Glove connected successfully" << endl; else { throw vhtBaseException("testGlove()->connect() returned false."); } if (testGlove->disconnect()) { cout << "Glove disconnected successfully" << endl; } else { throw vhtBaseException("testGlove()->disconnect() returned false."); } } catch (vhtBaseException *e) { cout << "Error with gloves: " << e << endl; system("pause"); exit(0); } delete testGlove; return 0; } ``` Still crashes on deletion of the glove. --- EDIT #2 :: If I just allocate and delete an instance of vhtCyberGlove it also crashes. ``` int main(int argc, char* argv[]) { vhtCyberGlove* testGlove = NULL; vhtIOConn gloveAddress("cyberglove", "localhost", "12345", "com1", "115200"); testGlove = new vhtCyberGlove(&gloveAddress,false); delete testGlove; //<<crash! return 0; } ``` Any ideas? thanks! JC
One possiblity is that mVHTGlove isn't being initialized to 0. If disconnect was then called without a connect ever being called, then you'd be attempting to deallocate a garbage pointer. Boom. Another possibility is that you are actually corrupting the stack a bit before that point, but that is where the corruption actually causes the crash. A good way to check that would be to comment out as much code as you can and still get the program to run, then see if you still get the corruption. If you don't, slowly bring back in bits of code until you see it come back. --- Some further thoughts (after your edits). You might check and see if the API doesn't have its own calls for memory management, rather than expecting you to "new" and "delete" objects manually. The reason I say this is that I've seen some DLLs have issues that looked a lot like this when some memory was managed inside the DLL and some outside.
The heap corruption error is reported when the `vhtGlove` is deleted. However, it may just as well be your own code that causes the corruption. This often happens as a result of overwriting a buffer allocated on the heap, perhaps from a call to `malloc`. Or you are perhaps deleting the same object twice. You can avoid this by using a smart pointer like `std::auto_ptr` to store the pointer to the object.
Dealing with an object corrupting the heap
[ "", "c++", "heap-memory", "heap-corruption", "fault-tolerant-heap", "" ]
Do you think VB is a good language for AI? I originally did AI using mainly Lisp and C/C++ when performance was needed, but recently have been doing some VB programming. VB has the following advantages: 1. Good debugger (essential!) 2. Good inspector (watch facility) 3. Easy syntax (Intellisense comparable to structure editors of late 80's Lisp environments). 4. Easy to integrate with 3rd party software. 5. Compiles to fast code (CLR performance pretty good) 6. Fast development. By the way, thanks for all the useful replies. I've upvoted everyone who contributed.
Which VB are you talking about here? If you're talking VB.NET then yes, and no.. I would suggest C# or maybe F#.. F# is a functional language and hence is generally better suited for many of the patterns you'll be dealing with when programming AI. The newer versions of C# also have support for language features such as lambda expressions, anonymous delagates et al which may also benefit you!
I would suggest you go with C# rather than VB.Net. You get all the nice features that you discuss but a better (and more familiar) syntax.
Using VB for Artificial Intelligence
[ "", "c++", "vb.net", "" ]
I am recently working in a project. There I need to convert language from English to Japanese by button click event. The text is in a div. Like this: ``` "<div id="sampletext"> here is the text </div>" "<div id="normaltext"> here is the text </div>" ``` The text is come from database. How can I convert this text easily?
A combination of AJAX and JQuery should do the trick. * AJAX - Go to the database and get the relevant text string * JQuery - Change the text in the div, identifying it by class.
Easily? I think not. You'd need some kind of Javascript to grab the value of the div, then send it to a server-side script where it can be translated.
convert language of a div
[ "", "php", "" ]
I am confused by C# right now. I have a bunch of classes, say A, B, and C, which all derive from class "Parent". I have a function which takes an argument of type Parent, and depending on which child class the object it is called with is, I want it to call a different method. Currently, I am thinking using a dictionary mapping types to delegates, but that seems silly, though it is all I can come up with at the moment. The problem is that when I am in the function, I only know that it is of type Parent, and I can use GetType to get which child class I have, which would allow the dictionary. Otherwise I would probably use function overloading. Really typecasting seems like the best method, allowing me to use function overloading, which would be much less verbose, but I don't know how I could do it or if it would work at all. Any reccomendations?
Overloading is the correct way ``` public void DoWork(Parent obj) { if(obj is A) Foo((A)obj); else if(obj is B) Foo((B)obj); else Foo(obj); } public void Foo(Parent obj) { //Do something for parent } public void Foo(A obj) { //Do something for A } public void Foo(B obj) { //Do something for B } ``` or if you don't want to explicitly cast the object for each type you could use reflection like this: ``` Bar methodObject = new Bar(); MethodInfo method = methodObject.GetType().GetMethod( "Foo", new Type[] { obj.GetType()}); method.Invoke(methodObject, new object[]{obj}); ```
Do the methods all share the same signature? If so, make it a virtual (potentially abstract) method in the parent class: ``` using System; public abstract class Parent { public abstract void DoSomething(); } public class A : Parent { public override void DoSomething() { Console.WriteLine("A.DoSomething()"); } } public class B : Parent { public override void DoSomething() { Console.WriteLine("B.DoSomething()"); } } public class Test { static void Main() { Parent a = new A(); Parent b = new B(); a.DoSomething(); b.DoSomething(); } } ``` If this isn't suitable then [double dispatch](http://en.wikipedia.org/wiki/Double_dispatch) *may* be suitable, but I'd really need to know more about the situation... it could be that changing some part of the existing design would work better.
C# call function based on subType of object
[ "", "c#", "oop", "" ]
Example: It's really annoying to type a list of strings in python: ``` ["January", "February", "March", "April", ...] ``` I often do something like this to save me having to type quotation marks all over the place: ``` "January February March April May June July August ...".split() ``` Those took the same amount of time, and I got 2x the # of months typed in. Another example: ``` [('a', '9'), ('4', '3'), ('z', 'x')...] ``` instead of: ``` map(tuple, "a9 43 zx".split()) ``` which took much less time.
Code is usually read many times, and it is written only once. Saving writing time at the expense of readability is not usually a good choice, unless you are doing some throw-away code. The second version is less explicit, and you need some time to understand what the code is doing. And we are simply talking about variable instantiation, not about algorithms!
A good text editor can make these things a non-issue. For example, I can type the following line in my code: ``` print `"January February March April May June July August September October November December".split()` ``` And then using the key sequence `V:!python<ENTER>` I can run the line through the python interpreter, and the output is the following: ``` ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'] ``` I'm using Vim for my example, but I'm sure this is just as easy with Emacs, TextMate, etc.
Is it acceptable to use tricks to save programmer when putting data in your code?
[ "", "python", "coding-style", "" ]
I want to make an intellisense code snippet using Ctl K + Ctl X that actually executes code when it runs... for example, I would like to do the following: ``` <![CDATA[string.Format("{MM/dd/yyyy}", System.DateTime.Now);]]> ``` But rather than giving me that string value, I want the date in the format specified. Another example of what I want is to create a new Guid but truncate to the first octet, so I would want to use a create a new Guid using System.Guid.NewGuid(); to give me {798400D6-7CEC-41f9-B6AA-116B926802FE} for example but I want the value: 798400D6 from the code snippet. I'm open to not using an Intellisense Code Snippet.. I just thought that would be easy.
This is what I did instead with a VS Macro ``` Public Sub InsertPartialGuid() Dim objSel As TextSelection = DTE.ActiveDocument.Selection Dim NewGUID As String = String.Format("{0}", (System.Guid.NewGuid().ToString().ToUpper().Split("-")(0))) objSel.Insert(NewGUID, vsInsertFlags.vsInsertFlagsContainNewText) objSel = Nothing End Sub ```
For the GUID, you can use: ``` string firstOctet = System.Guid.NewGuid().ToString().Split('-')[0]; ```
Creating a new Guid inside a code snippet using c#
[ "", "c#", "code-snippets", "" ]
I tried to search for this, but I was not sure how to describe it. If it is a duplicate, please point me to the other question. Thanks. I created a C# Windows Forms app using VS 2008. From the main form it opens a custom dialog form. When the user closes the dialog form, it does not completely disappear before the application starts into it's next task. The outline of various parts of the form remains until some additional tasks are completed. This looks very unprofessional and it makes the application appear to be broken, even though everything works great. Is there any way to avoid and/or fix this problem? FYI, the additional tasks are calculations requested after the form has been closed. Here is the form closing code. ``` private void CloseForm_Click(object sender, EventArgs e) { Properties.Settings.Default.EndDate = cmbBoxRptDate.SelectedValue.ToString(); rptDate = cmbBoxRptDate.SelectedValue.ToString(); Var1 = cmbBoxVar1.SelectedValue.ToString(); Var2 = cmbBoxVar2.SelectedValue.ToString(); this.Close(); } ``` Here is the code from the main form that opens the custom modal dialog and then disposes of it after it is closed. I think the dispose might be redundant since the form calls the close method on it's own. ``` RptSettingsForm RS = new RptSettingsForm(); DialogResult DR = RS.ShowDialog(); String var1 = RS.getVar1().ToString(); String var2 = RS.getVar2().ToString(); String rptDate = RS.getDate().ToString(); RS.Dispose(); ``` Then a connection is established to SQL Server to do some report calculations.
What you can do is to force the calling form to repaint itself after the dialog is closed, before carrying on with other stuff: ``` RptSettingsForm RS = new RptSettingsForm(); DialogResult DR = RS.ShowDialog(); this.Refresh(); // force repaint String var1 = RS.getVar1().ToString(); String var2 = RS.getVar2().ToString(); String rptDate = RS.getDate().ToString(); RS.Dispose(); ``` Note that there are two methods that will cause a form (or control) to repaint itself: [`Invalidate`](http://msdn.microsoft.com/en-us/library/598t492a.aspx) and [`Refresh`](http://msdn.microsoft.com/en-us/library/system.windows.forms.control.refresh.aspx). `Refresh` will force a full repaint immediately. `Invalidate` will not cause an immediate repaint, but rather invalidate the full control surface so that the full surface will be repainted the next time the control is updated (which may be delayed a bit if the thread is busy with other stuff, as in your case). To force a repaint after calling `Invalidate`, you can call the [`Update`](http://msdn.microsoft.com/en-us/library/system.windows.forms.control.update.aspx) method, which will force an immediate repaint of invalidated areas. So it may be, in your case, that you could simply call `Update` instead of `Refresh`, since I guess that the areas that were previously covered by the dialog should be invalidated. This might be more efficient that forcing a full repaint: ``` RptSettingsForm RS = new RptSettingsForm(); DialogResult DR = RS.ShowDialog(); this.Update(); // force repaint of invalidated areas String var1 = RS.getVar1().ToString(); String var2 = RS.getVar2().ToString(); String rptDate = RS.getDate().ToString(); RS.Dispose(); ```
I suspect the last bit is the most important: > Then a connection is established to SQL Server to do some report calculations. Is that still on the UI thread? If so, that's probably the problem - the repaint event for the main window is probably still waiting to happen, but you're busy with the database. Fredrik's suggestion of calling `Refresh` is a good one, but you've still fundamentally got the problem of doing too much on the UI thread. If for whatever reason it takes a long time to establish a connection to SQL Server, your UI will be frozen during that time - you won't be able to move it, resize it etc. Long-running operations - including just about anything to do with a database - should ideally be done on a different thread. This does make things trickier, without a doubt, but gives a much better UI in the end.
C# Forms - dialog form only partially disappears before next action taken
[ "", "c#", ".net", "winforms", "modal-dialog", "" ]
I would like to do the following: ``` [StructLayout(LayoutKind.Sequential, Pack = 1)] public struct SomeStruct { public byte SomeByte; public int SomeInt; public short SomeShort; public byte SomeByte2; } ``` Is there an alternative since Pack is not supported in the compact framework? Update: Explicitly setting up the structure and giving FieldOffset for each does not work either as it does not affect how the struct is packed Update2: If you try the following, the CF program wont even run because of how the structure is packed: ``` [StructLayout(LayoutKind.Explicit, Size=8)] public struct SomeStruct { [FieldOffset(0)] public byte SomeByte; [FieldOffset(1)] public int SomeInt; [FieldOffset(5)] public short SomeShort; [FieldOffset(7)] public byte SomeByte2; } ``` I know it seems hard to believe, but if you try it you will see. Add it to a CF project and try to run it and you will get a TypeLoadException. Changing the offsets to 0,4,8,10 respectively and it will work (but the size ends up being 12). I was hoping maybe someone had a solution using reflection maybe to marshal the size of each of the field types individually (something involving recursion to handle structs within structs or arrays of types).
This probably isn't the type of answer you're looking for, but I'll post it anyway for the hell of it: ``` public struct SomeStruct { public byte SomeByte; public int SomeInt; public short SomeShort; public byte SomeByte2; public byte[] APIStruct { get { byte[] output = new byte[8]; output[0] = this.SomeByte; Array.Copy(BitConverter.GetBytes(this.SomeInt), 0, output, 1, 4); Array.Copy(BitConverter.GetBytes(this.SomeShort), 0, output, 5, 2); output[7] = this.SomeByte2; return output; } set { byte[] input = value; this.SomeByte = input[0]; this.SomeInt = BitConverter.ToInt32(input, 1); this.SomeShort = BitConverter.ToInt16(input, 5); this.SomeByte2 = input[7]; } } } ``` Basically it does the packing/unpacking itself in the APIStruct property.
The simplest method of dealing with this type of problem is along the same lines as you might for a bit field, simply pack your data into a private member (or members if it is large) of the appropriate data type and then present public properties that unpack the data for you. The unpacking operations are extremely fast and will have little impact on performance. For your particular type the following is probably what you want: ``` public struct SomeStruct { private long data; public byte SomeByte { get { return (byte)(data & 0x0FF); } } public int SomeInt { get { return (int)((data & 0xFFFFFFFF00) << 8); } } public short SomeShort { get { return (short)((data & 0xFFFF0000000000) << 40); } } public byte SomeByte2 { get { return (byte)((data & unchecked((long)0xFF00000000000000)) << 56); } } } ``` For some structures even this method is not workable due to the unfortunate way a structure has been defined. In those cases you will generally have to use a byte array as a blob of data from which the elements can be unpacked. EDIT: To expand on what I mean about structs that can't be handled using this simple method. When you can't do simple packing/unpacking like this you need to manually marshal the irregular struct . This can be done using manual methods at the point you call the pInvoked API or by using a custom marshaler. The following is an example of a custom marhsaler that can be easily adapted to on the spot manual marshaling. ``` using System.Runtime.InteropServices; using System.Threading; public class Sample { [DllImport("sample.dll")] public static extern void TestDataMethod([MarshalAs(UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof(TestDataMarshaler))] TestDataStruct pData); } public class TestDataStruct { public byte data1; public int data2; public byte[] data3 = new byte[7]; public long data4; public byte data5; } public class TestDataMarshaler : ICustomMarshaler { //thread static since this could be called on //multiple threads at the same time. [ThreadStatic()] private static TestDataStruct m_MarshaledInstance; private static ICustomMarshaler m_Instance = new TestDataMarshaler(); public static ICustomFormatter GetInstance(string cookie) { return m_Instance; } #region ICustomMarshaler Members public void CleanUpManagedData(object ManagedObj) { //nothing to do. } public void CleanUpNativeData(IntPtr pNativeData) { Marshal.FreeHGlobal(pNativeData); } public int GetNativeDataSize() { return 21; } public IntPtr MarshalManagedToNative(object ManagedObj) { m_MarshaledInstance = (TestDataStruct)ManagedObj; IntPtr nativeData = Marshal.AllocHGlobal(GetNativeDataSize()); if (m_MarshaledInstance != null) { unsafe //unsafe is simpler but can easily be done without unsafe if necessary { byte* pData = (byte*)nativeData; *pData = m_MarshaledInstance.data1; *(int*)(pData + 1) = m_MarshaledInstance.data2; Marshal.Copy(m_MarshaledInstance.data3, 0, (IntPtr)(pData + 5), 7); *(long*)(pData + 12) = m_MarshaledInstance.data4; *(pData + 20) = m_MarshaledInstance.data5; } } return nativeData; } public object MarshalNativeToManaged(IntPtr pNativeData) { TestDataStruct data = m_MarshaledInstance; m_MarshaledInstance = null; //clear out TLS for next call. if (data == null) data = new TestDataStruct(); //if no in object then return a new one unsafe //unsafe is simpler but can easily be done without unsafe if necessary { byte* pData = (byte*)pNativeData; data.data1 = *pData; data.data2 = *(int*)(pData + 1); Marshal.Copy((IntPtr)(pData + 5), data.data3, 0, 7); data.data4 = *(long*)(pData + 12); data.data5 = *(pData + 20); } return data; } #endregion } ``` In the case of arrays of these structs you can't use custom marshaling unless the array size is fixed but it is relatively easy to manually marshal the array data as a whole using the same techniques.
Is there an alternative for StructLayout "Pack" attribute in Compact Framework?
[ "", "c#", "struct", "compact-framework", "structlayout", "" ]
Let's say I have a `List<NameValuePair>`, where NameValuePair is a simple object that has a Name property and a Value property, both strings. The list is populated with values like this: ``` name = "name1", value = "value1" name = "name1", value = "value2" name = "name2", value = "value3" name = "name3", value = "value4" ``` Note that there are two instances of the "name1" key. There can be any number of keys (since this is a List). I want to turn this List into a new list, which has just unique keys, and groups any values with the same key name as an array/list of that key. So the above should become: ``` name = "name1", value = "value1", "value2" // value is a string array or list name = "name2", value = "value3" name = "name3", value = "value4" ``` What is the easiest way to accomplish this?
Maybe with a Dictionary<string,List<string>> you could do something like ```` ``` for (var kv in mylistofnamed) { if (!dict.ContainsKey(kv.Key)) dict[kv.Key] = new List<string>(); dict[kv.Key].Add(kv.Value); } ``` ```` ?
The easiest way is with a [ILookup](http://msdn.microsoft.com/en-us/library/bb534291.aspx), which is essentially like a dictionary but can have more than one value for each key. You can do something like this to create your lookup: ``` var lookup = list.ToLookup(pair => pair.name, pair => pair.value); ``` Then you could print the name/value pairs like this: ``` foreach (var nameGroup in lookup) { var name = nameGroup.Key; foreach (string value in nameGroup) Console.WriteLine("Name: {0}, Value: {1}", name, value); } ```
Extracting unique keys from key/value pairs, and grouping the values in an array
[ "", "c#", "arrays", "" ]
Just tooling around for my own amusement, and I want to use a lambda, because I feel like it. Can I replace this function with a lambda? ``` def isodd(number): if (number%2 == 0): return False else: return True ``` Elementary, yes. But I'm interested to know...
And if you don't really need a function you can replace it even without a lambda. :) ``` (number % 2 != 0) ``` by itself is an expression that evaluates to True or False. Or even plainer, ``` bool(number % 2) ``` which you can simplify like so: ``` if number % 2: print "Odd!" else: print "Even!" ``` But if that's readable or not is probably in the eye of the beholder.
``` lambda num: num % 2 != 0 ```
Boolean evaluation in a lambda
[ "", "python", "lambda", "" ]
I have a standard ASP.NET 2.0 website. It has a webpage page. I have a webpart in my Company.Web.dll that I display on my webpart page on my website. All is good!!! I would like to use this same webpart in SharePoint 2007. I have a "site definition" project in VS2008 using Extensions for SharePoint 1.2. I have tried various ways to add the webpart from an outside assembly to my site definition. I have been able to deploy the webpart (where it is added to the webpart list of a webpart page) but I have been unsuccessful at adding the it to a page. My Glorious Failures: 1. Created a shell webpart to just display the existing web part, basically just using my part as a control. 2. Attempted to modify the X.webpart and X.xml files created by VS2008 when you create a new webpart. Both result in the following error while adding the web part to the page: > Exception > Microsoft.SharePoint.WebPartPages.WebPartPageUserException: > Cannot import XXXX Web Part. > at Microsoft.SharePoint.WebPartPages.WebPartImporter.CreateWebPart(Boolean > clearConnections) at > Microsoft.SharePoint.WebPartPages.WebPartImporter.Import(SPWebPartManager > manager, XmlReader reader, Boolean > clearConnections, Uri webPartPageUri, > SPWeb spWeb) at > Microsoft.SharePoint.WebPartPages.WebPartImporter.Import(SPWebPartManager > manager, XmlReader reader, Boolean > clearConnections, SPWeb spWeb) at > Microsoft.SharePoint.WebPartPages.WebPartQuickAdd.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String > eventArgument) Is there a special way I need to add my existing webpart to my site definition?
This sounds like a problem resolving the GUID at deployment time, as you can read about [in this SO question](https://stackoverflow.com/questions/120928/sharepoint-error-cannot-import-web-part).
To find the details of why the web part won't import, check the ULS logs. These are typically located at `%CommonProgramFiles%\Microsoft Shared\web server extensions\12\LOGS`. An entry will be logged here at the time you attempt to add the web part to the page. This should give you more detail. My guess is that it is a code access security issue. Your web part must be strongly signed and needs a SafeControl entry in the web.config of the SharePoint web application. Apart from these things you should be able to just add it to the Global Assembly Cache to test if it works (best practice is to write a CAS policy file). See [Deploying Web Parts in Windows SharePoint Services](http://msdn.microsoft.com/en-us/library/cc768621.aspx) for more details. I would try these steps before trying to integrate it as part of a site definition. Then at least you know the web part will actually run. Also, VSeWSS is really designed for developing your web part using it from the very start. If you have the original source, you could try creating a new web part with VSeWSS and then replace with your custom code and update the .webpart and feature XML files. Then it should behave a little better. If you haven't committed to VSeWSS, try [WSPBuilder](http://www.codeplex.com/wspbuilder) as it's less painful.
My existing webparts won't work in SharePoint
[ "", "c#", "asp.net", "sharepoint", "deployment", "web-parts", "" ]
Yes, this is rather subjective, but I am doing research on that matter and am curious to see if others have come to the same conclusions that I have. So, I ask, if you could only monitor 10 SQL Server 2005 counters, what would they be?
SQL Server Page Life Expectancy (prefer over Buffer Cache Hit Ratio) Memory Pages/sec % Processor Time SQL Server Memory Grants Pending (not Outstanding) Physical Disk Avg Disk Sec/Read Physical Disk Avg Disk Sec/Write (prefer over Queue Length, though both work OK) SQL Server Agent Failed Jobs SQL Server Lock Waits Avg Wait Time
Are these SQL Server specific counters or SQL Server Machine Counters? If they are machine wide counters then I recommend these: * SQLServer: Memory Manager: Memory Grants Outstanding * SQLServer: General Statistics:Logins/Sec, Logouts/Sec, User Connections * Memory: Available Bytes * Memory: Pages/Sec * Paging File: % Usage * PhysicalDisk: Avg. Disk Queue Length * Processor: % Processor Time
If you could only monitor 10 SQL Server 2005 counters, what would they be?
[ "", "sql", "sql-server", "" ]
I've always wondered why the JVM doesn't tell you *which* pointer (or more precisely, which variable) is null when a `NullPointerException` is thrown. A line number isn't specific enough because the offending line can often contain numerous variables that could have caused the error. Is there any compiler or JVM flag that would make these exception messages more useful?
It's because the dereference always happens when there is no name available. The value is loaded onto the operand stack, and is then passed to one of the JRE opcodes that dereferences it. However, the operand stack does not have a name to associate with a null value. All it has is 'null'. With some clever runtime tracking code, a name can be derived, but that would add overhead with limited value. Because of this, there is no JRE option that will turn on extra information for null pointer exceptions. In this example, the reference is stored in local slot 1, which maps to a local variable name. But the dereference happens in the invokevirtual instruction, which only sees a 'null' value on the stack, and then throws an exception: ``` 15 aload_1 16 invokevirtual #5 ``` Equally valid would be an array load followed by a dereference, but in this case there is no name to map to the 'null' value, just an index off of another value. ``` 76 aload 5 78 iconst_0 79 aaload 80 invokevirtual #5 ``` You can't allocate the names statically to each instruction either - this example produces a lot of bytecode, but you can see that the dereference instruction will receive either objA or objB, and you would need to track this dynamically to report the right one, as both variables flow to the same dereference instruction: ``` (myflag ? objA : objB).toString() ```
Once you JIT the code, it's just native pointer math, and if any pointer in the native code is null it throws the exception. It would have a devastating performance impact to reverse that assembly back to the original variable, and considering the JIT optimizes the generated code to varying levels, is often not even possible.
Why doesn't Java tell you which pointer is null?
[ "", "java", "debugging", "nullpointerexception", "" ]
I've got a class that's got a bunch of public methods, and I'd like to reflect over it to find the set of member methods that could be used as a particular delegate. For example: ``` delegate void InterestingFunc(int i); class Entity { public void F(); public void G(); public void H(int i); public void X(int i); } ``` Can I use Type.FindMembers() to pull out the set { H, X }? If so, how? Is there a better way?
There is no inherent query support in Type which will find methods based on a delegate signature. You would need to hand code a search method which loops through methods and properties manually comparing the signatures to that of the proposed delegate. This itself is a non-trivial operation as you need to take generics into account with your solution.
> This itself is a non-trivial operation > as you need to take generics into > account with your solution. 100% correct -- not to mention `ref`/`out` parameters, `param[]` modifiers, as well as unsafe pointers. One non-optimal option is to apply [`Delegate.CreateDelegate`](http://msdn.microsoft.com/en-us/library/53cz7sc6.aspx) to each method in `Entity`, taking note of when the construction fails. The failures denote the incompatible methods. Again, you will likely have to do some work to handle the case of generic methods.
How can I use reflection in C# to find all the members of a class that meet the requirements of a specific delegate?
[ "", "c#", "reflection", "delegates", "" ]
Using PHP.. I have a small app that I built that currently uses a querystring to navigate and grab data from a database. The key in the database is also in the string and that is not acceptable anymore. I need to change it. I would like to hide the db key and use a session in place of it but I'm not sure how to do that. In fact, there are also other variables in the query string that I would like to use sessions for if at all possible. page.php?var1&var2&id=1 This is what my string looks like. I am looping through the results in the database and have given each row the id so that when the user clicks the row they want, but I'm not sure how I could do this with a session. Does anyone have any ideas? Thanks EDIT: I'm developing an email type system where senders and recipients are getting and sending mail. Each piece of mail that is stored on the server will have its own unique key. Currently, I am using that number to retreive the message but the problem is that I don't want people to change the number and read other people's mail. I can probably use a GUID for this or even some sort of hash but I really hate long query strings. I was just thinking it would be so much cleaner if there was a way to "hide" the id all together.
**UPDATED (Again ... Yeah, I know.)** Allowing access to a particular set of data through a $\_GET parameter is much more accessible to any user that happens to be using the application. **UPDATED** For storing a private record key, you are probably going to want to use post data, and if you really want it to look like a link, you can always use CSS for that part. Honestly, the best way to stop people from reading other people's mail is by having a relationship table that says only X person is able to access Y email (by id). That or have a field that says who is the 'owner' of the email. The fact is that users can still get access to POST parameters, and can easily forge their own POST parameters. This means that anyone could realistically access anyone else's email if they knew the naming scheme. In an ideal system, there would be a Sender, and a Recipient (The Recipient could be comma separated values). Only the people that are on one of those columns should be allowed to access the email. --- **How To Use Sessions (From Earlier)** First start off with calling session\_start(), and then after that check for variables from previous scripts. If they aren't present, generate them. If they are, grab them and use them. ``` session_start(); if(!isset($_SESSION['db_key'])) { $_SESSION['db_key'] = // generate your database key } else { $db_key = $_SESSION['db_key']; } ``` Sessions are stored in the $\_SESSION array. Whenever you want to use $\_SESSION, you need to call session\_start() **FIRST** and then you can assign or grab anything you like from it. When you want to destroy the data, call session\_destroy(); Also check out php.net's section on [Sessions](https://www.php.net/manual/en/book.session.php)
Your question isn't too clear to me, but I understand it like this: You need some variables to decide what is being displayed on the page. These variables are being passed in the URL. So far so good, perfectly normal. Now you want to hide these variables and save them in the session? Consider this: Right now, every page has a unique URL. ``` http://mysite.com/page?var1=x&var2=y ``` displays a unique page. Whenever you visit the above URL, you'll get the same page. What you're asking for, if I understand correctly, is to use one URL like ``` http://mysite.com/page ``` without variables, yet still get different pages? That's certainly possible, but that means you'll need to keep track of what the user is doing on the server. I.e. "user clicked on 'Next Page', the last time I saw him he was on page X, so he should now be on page Y, so when he's requesting the site the next time, I'll show him page Y." That's a lot of work to do, and things can get awkward quickly if the user starts to use the back button. I don't think this is a good idea. If you need to take sensitive information out of the URL, obfuscate them somehow (hashes) or use alternative values that don't have any meaning by themselves. It completely depends on your application of course, if the user is accumulating data over several pages, Sessions are the way to go obviously. Can you be a bit more descriptive on what your app is doing? Edit: > but the problem is that I don't want people to change the number and read other people's mail If your primary concern is security, that's the wrong way to do it anyway. Security through obscurity is not gonna work. You need to explicitly check if a user is allowed to see a certain piece of info before displaying it to him, not just relying on him not guessing the right id.
How to use sessions in place of a querystring
[ "", "php", "" ]
I've too many methods that repeatedly do something like ``` Statement stmt = null; ResultSet rstmt = null; try { stmt = conn.createStatement(); rstmt = stmt.executeQuery(...); while (rstmt.next()) { //handle rows } } catch (SQLException e) { //handle errors } finally { try {rstmt.close();} catch (SQLException ex) {} try {stmt.close();} catch (SQLException ex) {} } ``` This setup/teardown/cleanup of statements and resultsets is repetive and hides the interesting pieces of code. Is there any pattern or idiom for handling this(without introducing any external framework) ?
you can create a method that receives the SQL query and an object to handle the `ResultSet`. for example: ``` private void executeSql(String sql, ResultSetHandler handler) { Statement stmt = null; ResultSet rstmt = null; try { stmt = conn.createStatement(); rstmt = stmt.executeQuery(sql); while (rstmt.next()) { handler.handle(rstmt); } } catch (SQLException e) { //handle errors } finally { try {rstmt.close();} catch (SQLException ex) {} try {stmt.close();} catch (SQLException ex) {} } } ``` with `ResultSetHandler` being an interface: ``` public interface ResultSetHandler { void handle(ResultSet rs) throws SQLException; } ``` and you can create an object of an anonymous class implementing that interface, so it won't clutter too much.
Have a look at [SimpleJDBCTemplate](http://static.springsource.org/spring/docs/2.5.x/api/org/springframework/jdbc/core/simple/SimpleJdbcTemplate.html) in Spring Framework. This does exactly what you want. If you don't want to introduce an external framework then just use it for some inspiration to implement your own.
Clean up repetitive setup and cleanup Java(JDBC) code
[ "", "java", "jdbc", "refactoring", "" ]
I have a listbox with some textblocks and a button -- in the button's codebehind it calls a method passing the currently selected listbox item, this works great. The issue is that when I select an item and then click the button on another item it doesn't update the "SelectedItem" property -- is there a way Xaml or C# that I can force a button click to select the parent ListBoxItem? **Xaml** ``` <DataTemplate> <Grid> <Button x:Name="myButton" Click="myButton_Click" Height="30" Width="30"> <Image Source="Resources\Image.png" /> </Button> <TextBlock Text="{Binding DataField}"></TextBlock> </Grid> </DataTemplate> ```
``` var curItem = ((ListBoxItem)myListBox.ContainerFromElement((Button)sender)).Content; ```
When a Button is clicked, it sets e.Handled to true, causing the routed event traversal to halt. You could add a handler to the Button which raises the routed event again, or finds the visual ancestor of type ListBoxItem and sets its IsSelected property to true. EDIT An extension method like this: ``` public static DependencyObject FindVisualAncestor(this DependencyObject wpfObject, Predicate<DependencyObject> condition) { while (wpfObject != null) { if (condition(wpfObject)) { return wpfObject; } wpfObject = VisualTreeHelper.GetParent(wpfObject); } return null; } ``` Usage: ``` myButton.FindVisualAncestor((o) => o.GetType() == typeof(ListBoxItem)) ```
WPF ListBox Button Selected Item
[ "", "c#", ".net", "wpf", "listbox", "" ]
`myPythonClient` (below) wants to invoke a `ringBell` function (loaded from a DLL using `ctypes`). However, attempting to access `ringBell` via its *name* results in an `AttributeError`. Why? `RingBell.h` contains ``` namespace MyNamespace { class MyClass { public: static __declspec(dllexport) int ringBell ( void ) ; } ; } ``` `RingBell.cpp` contains ``` #include <iostream> #include "RingBell.h" namespace MyNamespace { int __cdecl MyClass::ringBell ( void ) { std::cout << "\a" ; return 0 ; } } ``` `myPythonClient.py` contains ``` from ctypes import * cdll.RingBell[1]() # this invocation works fine cdll.RingBell.ringBell() # however, this invocation errors out # AttributeError: function 'ringBell' not found ```
Perhaps because the C++ name is mangled by the compiler and not exported from the DLL as `RingBell`. Have you checked that it appears in the exported names exactly like that?
Your C++ compiler is mangling the names of all externally visible objects to reflect (as well as their underlying names) their namespaces, classes, and signatures (that's how overloading becomes possible). In order to avoid this mangling, you need an `extern "C"` on externally visible names that you want to be visible from non-C++ code (and therefore such names cannot be overloaded, nor in C++ standard can they be inline, within namespaces, or within classes, though some C++ compilers extend the standard in some of these directions).
Python: accessing DLL function using ctypes -- access by function *name* fails
[ "", "python", "dll", "ctypes", "attributeerror", "" ]
What is the best way to install a windows service written in C# (in the standard way) on a remote machine, where I need to provide the username and password it should run as? I am going to run it from MSBuild as part of integration tests. EDIT: I don't have an msi and I don't want to create one.
You can use the [SC](http://support.microsoft.com/kb/251192) command. > `sc.exe \\remotecomputer create newservice binpath= C:\Windows\System32\Newserv.exe start= auto obj= DOMAIN\username password= pwd` (Note the spaces after the equals signs are important) ``` Creates a service entry in the registry and Service Database. SYNTAX: sc create [service name] [binPath= ] <option1> <option2>... CREATE OPTIONS: NOTE: The option name includes the equal sign. type= <own|share|interact|kernel|filesys|rec> (default = own) start= <boot|system|auto|demand|disabled> (default = demand) error= <normal|severe|critical|ignore> (default = normal) binPath= <BinaryPathName> group= <LoadOrderGroup> tag= <yes|no> depend= <Dependencies(separated by / (forward slash))> obj= <AccountName|ObjectName> (default = LocalSystem) DisplayName= <display name> password= <password> ```
Installutil called from WMI invoked from Powershell is one way to go.
Installing a windows service on remote machine using given username
[ "", "c#", ".net", "msbuild", "windows-services", "" ]
I'm creating a web service using PHP5's native SOAP Methods. Everything went fine until I tried to handle authentication using SOAP Headers. I could easily find how to add the username/password to the SOAP headers, **client-side**: ``` $myclient = new SoapClient($wsdl, $options); $login = new SOAPHeader($wsdl, 'email', 'mylogin'); $password = new SOAPHeader($wsdl, 'password', 'mypassword'); $headers = array($login, $password); $myclient->__setSOAPHeaders($headers); ``` But I can't find anywhere the methods for collecting and processing these headers **server-side**. I'm guessing there has to be an easy way to define a method in my SoapServer that handles the headers...
[SoapClient](https://www.php.net/manual/en/soapclient.soapclient.php) uses the username and password to implement HTTP authentication. Basic and Digest authentication are support ([see source](http://cvs.php.net/viewvc.cgi/php-src/ext/soap/php_http.c?view=markup)) For information on implementing HTTP authentication in PHP on the server side, see [this manual page](http://php.net/manual/en/features.http-auth.php). If you don't want to use HTTP authentication, see [this user-contributed sample](https://www.php.net/manual/en/soapserver.soapserver.php#78872) on the SoapServer manual page which shows how you could pass some credentials in a UsernameToken header.
With a modern PHP version it is *NOT* necessary to add anything to the WSDL as the headers are part of the SOAP Envelope specification. The user contributed example cited by Paul Dixon does not work simply because the header is not ***UserToken*** as written in the comment, the header is ***Security***, so that's is the name the class method should have. Then you get a nice stdClass object with a UserToken stdClass object property that has Username and Password as properties. Example code (to be inserted in a PHP class that implements the SOAP service: ``` public function Security( $header ){ $this->Authenticated = true; // This should be the result of an authenticating method $this->Username = $header->UsernameToken->Username; $this->Password = $header->UsernameToken->Password; } ``` Works like a charm for Username/Password based WSSE Soap Security
Collecting/Processing headers in PHP Soap Server
[ "", "php", "web-services", "soap", "" ]
I am trying to find a way to get a list of Windows sessions? I need the same information as the one displayed in the Task Manager on the User tab. I need to know if the user is active or not and if s/he is logged on in the Remote Desktop session. Any idea on how to do that with C# / Windows XP Pro?
I believe you'll need to use P/Invoke to retrieve this information. The relevant APIs are documented in [this MSDN page](http://msdn.microsoft.com/en-us/library/aa379437%28VS.85%29.aspx).
As a starting point you can get a list of users logged on by running the command ``` qwinsta ``` From the command prompt. This will give output like ``` C:\WINDOWS\system32>qwinsta SESSIONNAME USERNAME ID STATE TYPE DEVICE >console me 0 Active wdcon rdp-tcp 65536 Listen rdpwd ``` and will list any remote sessions.
How to get a list of Windows sessions?
[ "", "c#", "windows", "" ]
Let's say I have a method m() that takes an array of Strings as an argument. Is there a way I can just declare this array in-line when I make the call? i.e. Instead of: ``` String[] strs = {"blah", "hey", "yo"}; m(strs); ``` Can I just replace this with one line, and avoid declaring a named variable that I'm never going to use?
``` m(new String[]{"blah", "hey", "yo"}); ```
Draemon is correct. You can also declare `m` as taking [*varargs*](http://java.sun.com/j2se/1.5.0/docs/guide/language/varargs.html): ``` void m(String... strs) { // strs is seen as a normal String[] inside the method } m("blah", "hey", "yo"); // no [] or {} needed; each string is a separate arg here ```
Any way to declare an array in-line?
[ "", "java", "arrays", "" ]
I have an instance of System.IO.TextWriter. It may be passed in from System.Console. Any way to find out it is Console without causing exception? I tried this but not compiled: ``` if (_myWriter as System.Console != null ) // error compiling ``` I guess I have to use type checking instead of boxing?
You could try something like IsConsoleOut below: ``` static void Main(string[] args) { Console.WriteLine("Console.Out: {0}", IsConsoleOut(Console.Out)); Console.WriteLine("Other: {0}", IsConsoleOut(new StreamWriter(Stream.Null))); Console.ReadLine(); } private static bool IsConsoleOut(TextWriter textWriter) { return object.ReferenceEquals(textWriter, Console.Out); } ``` Unfortunately, this isn't fool proof, as someone could create their own TextReader directly around the Console output stream (using Console.OpenStandardOutput() to get the stream), and the above function would fail to identify it, but provided the TextWriter has always come from Console.Out it should work - I think!
You could do: ``` if (_myWriter == Console.Out) ``` but that's no guarantee - it could be a wrapper around `Console.Out`, for example. Why would you want to treat it differently in this case? It would be nicer to design around this than to special-case console writers, IMO.
How to find out TextWriter instance is a Console?
[ "", "c#", "" ]
I have a large Java project with a large number of jar file dependencies. When I try to run the project (using exec) from Eclipse or Netbeans, Maven throws an exception which turns out to be a too large number of entries on the classpath (only 2/3 of the needed entries are included). Does anyone know a workaround for this? (Except from building an executable jar and running it from terminal.) Is it possbile to "extend" the "classpath-buffer"-size?
This is a Maven exec plugin bug, it is documented in [MEXEC-68](https://jira.codehaus.org/browse/MEXEC-68), the reporter created a patch so I hope it will be resolved soon. One workaround would be to add the classpath to the manifest file using this config for the maven-jar-plugin, add the dependencies to a folder and add just that folder to the CLASSPATH envvar. For example: ``` <project> ... <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-jar-plugin</artifactId> ... <configuration> <archive> <manifest> <addClasspath>true</addClasspath> </manifest> </archive> </configuration> ... </plugin> </plugins> </build> ... </project> ``` This will add to the manifest something like: ``` Class-Path: plexus-utils-1.1.jar commons-lang-2.1.jar ``` If that JARs are in a CLASSPATH folder, you can run your JAR using maven exec plugin hidding the classpath with something like: ``` mvn exec:exec [...] -Dexec.classpathScope="test" ``` I used -Dexec.classpathScope="test" to make the plugin ignore the dependencies and add just the ones in scope test.
This problem is fixed in Netbeans 6.10M1. Please take a look at [Bug 188864](http://netbeans.org/bugzilla/show_bug.cgi?id=188864). If you have an older version, you can still fix this yourself (you just have to edit an xml file inside org-netbeans-modules-maven.jar). Then, don't forget to check Maven Best Practices (<http://wiki.netbeans.org/MavenBestPractices#Binding_Maven_goals_to_IDE_actions>) where it is explained how to bind maven goals to IDE actions. Regards, Mach
How to resolve Maven exec plugin: classpath too long error?
[ "", "java", "maven-2", "classpath", "maven-plugin", "" ]
I want to do a JOIN with LINQ using an OR statement. Here is the SQL query I'm starting with: ``` SELECT t.id FROM Teams t INNER JOIN Games g ON (g.homeTeamId = t.id OR g.awayTeamId = t.id) AND g.winningTeamId != 0 AND g.year = @year GROUP BY t.id ``` I'm having trouble converting that ON clause to LINQ. This is where I'm at: ``` var y = from t in db.Teams join g in db.Games on t.ID equals g.AwayTeamID //missing HomeTeamID join where g.WinningTeamID != 0 && g.Year == year group t by t.ID into grouping select grouping; ``` I think I could use: ``` join g in db.Games on 1 equals 1 where (t.ID == g.HomeTeamID || t.ID == g.AwayTeamID) ``` and this works but seems kind of seems hacky. Is there a better way?
The where clause applies a boolean condition, so using "||" is the way to go. You can chain multiple where clauses but I believe that will give you a "and" operation, rather than an "or".
I struggled with this as well until I found the following solution, which worked well for my situation: ``` var y = from t in db.Teams from g in db.Games where ( t.ID == g.AwayTeamID || t.ID == g.HomeTeamID ) && g.WinningTeamID != 0 && g.Year == year group t by t.ID into grouping select grouping; ``` Under the covers, your solution probably works very close to this one. However, I bet this one is just a bit faster if you benchmark it since it is not JOINING every item in the first dataset with every item in the second dataset, which could be a disaster if either (or both) dataset were really big.
LINQ join with OR
[ "", "c#", "linq-to-sql", "" ]
Consider the following program. How is the behaviour that it displays (namely that exceptions will propagate out of an event handler) a "good thing"? As far as I can tell, it could only ever be bad; unexpected exceptions popping up from functions that they shouldn't. In my particular case, it was killing threads. So, is this behaviour actually a good thing in some cases? Is this a reason to say that letting exceptions out of event-handlers is poor design? ``` static class Program { static void Main() { Foo foo = new Foo(); foo.SomeEvent += ThrowException; try { foo.OnSomeEvent(); } catch (Exception) { // This is printed out Console.WriteLine("Exception caught!"); } } static void ThrowException(object sender, EventArgs e) { throw new Exception(); } } // Define other methods and classes here class Foo { public event EventHandler SomeEvent; public void OnSomeEvent() { SomeEvent(this, EventArgs.Empty); } } ```
What's your preferred alternative - silently swallowing the exception? I wouldn't like that at all. Events are *just* a way of implementing the observer pattern, really. If a listener throws an exception, I'd absolutely expect that exception to be thrown back to the caller. Any other behaviour I can think of would effectively treat the exception as unimportant. The whole point of exceptions is that when something goes wrong, you find out about it quickly and implicitly. You have to *explicitly* handle exceptions, so that you don't go on your merry way in a corrupt state without realising it. You make a valid point about whose responsibility it is to handle exceptions. Broadly speaking, I find it best to assume that just about anything can throw an exception at any time. Other than special cases where I know a specific exception may occur *and I can handle it*, I don't usually catch exceptions other than at the top level - except possibly to wrap and rethrow, or log and rethrow. Now it's possible that one of your event handlers really *shouldn't* be throwing an exception - that they haven't really run into an error condition - but what should happen if it's a perfectly reasonable exception which indicates a serious problem? While a program crashing is ugly, it's often better than continuing with some of it malfunctioning, possibly corrupting persisted state etc. Fundamentally, I don't think the CS/SE field has got error handling "right" yet. I'm not even sure that there *is* an elegant way of doing the right thing which is simple to express in all situations... but I hope that the current situation isn't as good as it gets.
The main aspect of exception handling discussed here is: do not catch exception if you don't know how to handle it. But let's talk about the observer pattern, where notifier emits event (or signal) about it's state change and listeners handle it. A good example of a notifier is a button emitting 'clicked' event. Does a button care about who are the listeners and what they do? Not really. If you're a listener and you got this event, then you've got a job to do. And if you can't do it, you have to handle this error or inform user, because passing exception to the button makes no sense - button definitely does not know how to handle errors of listener job. And buttons state changer (probably some message loop) does not either - your application will end up at Main() with a crash. That's how observer pattern works - event emitters don't know what their listeners are doing and there's very little chance they will handle this exception properly. Also bear in mind, that if your exception handler throws exception, there may be other listeners that won't receive notification and that may lead to undefined application state. So my advice is to catch all exceptions at event handler, but figure out how to handle them there. Or else no one will.
Why do exceptions propogate out of an event handler?
[ "", "c#", "events", "exception", "event-handling", "" ]
I need to get 5 random records from a table plus a further record based on data from the users preferences as stored in a second table. Here are the two statements i have created so far: Gets favourite charity based on key set in TBL\_MEMBERS: SELECT DISTINCT TBL\_CHARITIES.\* FROM TBL\_CHARITIES JOIN TBL\_MEMBERS ON TBL\_CHARITIES.cha\_Key = TBL\_MEMBERS.members\_Favourite WHERE TBL\_MEMBERS.members\_Id = 16 Gets 5 random charities: SELECT TOP 5 \* FROM TBL\_CHARITIES WHERE cha\_Active = 'TRUE' AND cha\_Key != '1' ORDER BY NEWID(); When used in a stored procedure it only returns the first SELECT statement to my .Net page. How can i combine the two statements whilst ensuring that no results are repeated (Eg the favourite is not present in the 5 random records? Many Thanks! --- Ok! So now ive updated things and got the following: ``` CREATE PROCEDURE web.getRandomCharities ( @tmp_ID bigint --members ID ) AS BEGIN WITH q AS ( SELECT TOP 5 * FROM TBL_CHARITIES WHERE cha_Active = 'TRUE' AND cha_Key != '1' ORDER BY NEWID() ) SELECT * FROM q UNION ALL SELECT TOP 1 * FROM ( SELECT * FROM TBL_CHARITIES WHERE TBL_CHARITIES.cha_Key IN ( SELECT members_Favourite FROM TBL_MEMBERS WHERE members_Id = @tmp_ID ) EXCEPT SELECT * FROM q ) tc END ``` Now i need to be able to the record "cha\_Key == '1'" but only if its not the users favourite. Is this possible? Thanks for everything so far. ITs truly appreciated.
Just `UNION ALL` them: ``` WITH q AS ( SELECT TOP 5 * FROM TBL_CHARITIES WHERE cha_Active = 'TRUE' AND cha_Key != '1' ORDER BY NEWID() ) SELECT * FROM q UNION ALL SELECT TOP 1 * FROM ( SELECT * FROM TBL_CHARITIES WHERE TBL_CHARITIES.cha_Key IN ( SELECT members_Favourite FROM TBL_MEMBERS WHERE members_Id = 16 ) EXCEPT SELECT * FROM q ) tc ``` **Update:** Unfortunately, the query above will not work as intended, since `CTE`'s are reevaluated in `SQL Server`, and the second instance of `q` will give different records. See this post in my blog for more detail: * [**`SQL Server`: random records avoiding `CTE` reevaluation**](http://explainextended.com/2009/07/28/sql-server-random-records-avoiding-cte-reevaluation/) You need to rewrite the query as this: ``` WITH q AS ( SELECT TOP 5 * FROM TBL_CHARITIES WHERE cha_Active = 'TRUE' AND cha_Key != '1' ORDER BY NEWID() ), r AS ( SELECT * FROM TBL_CHARITIES WHERE TBL_CHARITIES.cha_Key IN ( SELECT members_Favourite FROM TBL_MEMBERS WHERE members_Id = 16 ) ) SELECT TOP 6 * FROM q FULL OUTER JOIN r JOIN TBL_CHARITIES t ON t.id = COALESCE(q.id, r.id) ORDER BY q.id ``` , assuming that `id` is the `PRIMARY KEY` of `TBL_CHARITIES`.
I would suggest pulling down a list of IDs to your .Net page and use your background code to randomly select N number of IDs and pass that as a parameter to your query. You can exclude the user's favorite by using `where id != BL_MEMBERS.members_Favourite` in the query which retrieves the existing IDs,. This allows you to increase/decrease the number of randomly selected items fairly easily and moves the random generation and checks for unique items to .Net where it is accomplished much more easily.
SP: Get 5 random records plus 1
[ "", "sql", "sql-server", "sql-server-2005", "t-sql", "stored-procedures", "" ]
In the attached flex code, I am trying to call a javascript function in its HTML wrapper. The example is also live at : <http://www.cse.epicenterlabs.com/mbm/ajax_api.html> The problem I am facing is, that I have to click the button twice to get the desired output. Seems like there is some delay in setting the "output" variable. How could I get the output from the javascript function in one click? ``` <?xml version="1.0" encoding="utf-8"?> <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute"> <mx:TextArea x="209" y="139" height="245" width="318" id="text1" fontSize="28"/> <mx:Script> <![CDATA[ import mx.rpc.events.ResultEvent; import flash.external.*; public function callWrapper():void { var s:String; if (ExternalInterface.available) { var wrapperFunction:String = "initialize"; s = ExternalInterface.call(wrapperFunction,text1.text); text1.text = s; } else { s = "Wrapper not available"; } trace(s); } ]]> </mx:Script> <mx:Button x="92" y="118" label="Transliterate" click="callWrapper()"/> </mx:Application> ``` HTML Wrapper : ``` <!-- saved from url=(0014)about:internet --> <html lang="en"> <!-- Smart developers always View Source. This application was built using Adobe Flex, an open source framework for building rich Internet applications that get delivered via the Flash Player or to desktops via Adobe AIR. Learn more about Flex at http://flex.org // --> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <!-- BEGIN Browser History required section --> <link rel="stylesheet" type="text/css" href="history/history.css" /> <!-- END Browser History required section --> <title></title> <script src="AC_OETags.js" language="javascript"></script> <!-- BEGIN Browser History required section --> <script src="history/history.js" language="javascript"></script> <!-- END Browser History required section --> <style> body { margin: 0px; overflow:hidden } </style> <script language="JavaScript" type="text/javascript"> <!-- // ----------------------------------------------------------------------------- // Globals // Major version of Flash required var requiredMajorVersion = 9; // Minor version of Flash required var requiredMinorVersion = 0; // Minor version of Flash required var requiredRevision = 28; // ----------------------------------------------------------------------------- // --> </script> </head> <body scroll="no"> <script type="text/javascript" src="http://www.google.com/jsapi"></script> <script type="text/javascript"> google.load("language", "1"); var output; function initialize(input) { google.language.transliterate([input], "en", "hi", function(result) { if (!result.error) { if (result.transliterations && result.transliterations.length > 0 && result.transliterations[0].transliteratedWords.length > 0) { output = result.transliterations[0].transliteratedWords[0]; } } }); return output; } </script> <script language="JavaScript" type="text/javascript"> <!-- // Version check for the Flash Player that has the ability to start Player Product Install (6.0r65) var hasProductInstall = DetectFlashVer(6, 0, 65); // Version check based upon the values defined in globals var hasRequestedVersion = DetectFlashVer(requiredMajorVersion, requiredMinorVersion, requiredRevision); if ( hasProductInstall && !hasRequestedVersion ) { // DO NOT MODIFY THE FOLLOWING FOUR LINES // Location visited after installation is complete if installation is required var MMPlayerType = (isIE == true) ? "ActiveX" : "PlugIn"; var MMredirectURL = window.location; document.title = document.title.slice(0, 47) + " - Flash Player Installation"; var MMdoctitle = document.title; AC_FL_RunContent( "src", "playerProductInstall", "FlashVars", "MMredirectURL="+MMredirectURL+'&MMplayerType='+MMPlayerType+'&MMdoctitle='+MMdoctitle+"", "width", "100%", "height", "100%", "align", "middle", "id", "ajax_api", "quality", "high", "bgcolor", "#869ca7", "name", "ajax_api", "allowScriptAccess","sameDomain", "type", "application/x-shockwave-flash", "pluginspage", "http://www.adobe.com/go/getflashplayer" ); } else if (hasRequestedVersion) { // if we've detected an acceptable version // embed the Flash Content SWF when all tests are passed AC_FL_RunContent( "src", "ajax_api", "width", "100%", "height", "100%", "align", "middle", "id", "ajax_api", "quality", "high", "bgcolor", "#869ca7", "name", "ajax_api", "allowScriptAccess","sameDomain", "type", "application/x-shockwave-flash", "pluginspage", "http://www.adobe.com/go/getflashplayer" ); } else { // flash is too old or we can't detect the plugin var alternateContent = 'Alternate HTML content should be placed here. ' + 'This content requires the Adobe Flash Player. ' + '<a href=http://www.adobe.com/go/getflash/>Get Flash</a>'; document.write(alternateContent); // insert non-flash content } // --> </script> <noscript> <object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" id="ajax_api" width="100%" height="100%" codebase="http://fpdownload.macromedia.com/get/flashplayer/current/swflash.cab"> <param name="movie" value="ajax_api.swf" /> <param name="quality" value="high" /> <param name="bgcolor" value="#869ca7" /> <param name="allowScriptAccess" value="sameDomain" /> <embed src="ajax_api.swf" quality="high" bgcolor="#869ca7" width="100%" height="100%" name="ajax_api" align="middle" play="true" loop="false" quality="high" allowScriptAccess="sameDomain" type="application/x-shockwave-flash" pluginspage="http://www.adobe.com/go/getflashplayer"> </embed> </object> </noscript> </body> </html> ```
That is because `google.language.transliterate` is not a synchronous operation. Your `initialize` function returns even before `google.language.transliterate` has finished running (which is why you are attaching a callback function to run after it is done). You need to callback an actionscript function after transliterate is done. Explore ExternalInterface.addCallback() to add an actionscript function callable from javascript.
The call to `google.language.transliterate` in the JavaScript code is asynchronous, that is why it seems like you have to press the button twice. The anonymous function that is passed as the fourth argument doesn't run until some data has been loaded. Perhaps you should show some kind of loading indicator just before calling `google.language.transliterate` and then hiding it in the handler? That way you would see when it's loading data.
Problem in returning values from javascript function to flex
[ "", "javascript", "apache-flex", "transliteration", "" ]
Assuming that I have the following code: ``` final Catalog catalog = createCatalog(); for (int i = 0; i< 100; i++{ new Thread(new CatalogWorker(catalog)).start(); } ``` "Catalog" is an object structure, and the method createCatalog() and the "Catalog" object structure has not been written with concurrency in mind. There are several non-final, non-volatile references within the product catalog, there may even be mutable state (but that's going to *have* to be handled) The way I understand the memory model, this code is not thread-safe. Is there any simple way to make it safe ? (The generalized version of this problem is really about single-threaded construction of shared structures that are created *before* the threads explode into action)
No, there's no *simple* way to make it safe. Concurrent use of mutable data types is always tricky. In *some* situations, making each operation on `Catalog` synchronized (preferably on a privately-held lock) may work, but usually you'll find that a thread actually wants to perform *multiple* operations without risking any other threads messing around with things. Just synchronizing every access to variables should be enough to make the Java memory model problem less relevant - you would always see the most recent values, for example - but the bigger problem itself is still significant. Any *immutable* state in `Catalog` should be fine already: there's a "happens-before" between the construction of the `Catalog` and the new thread being started. From [section 17.4.5](http://java.sun.com/docs/books/jls/third_edition/html/memory.html#17.4.5) of the spec: > A call to start() on a thread > happens-before any actions in the > started thread. (And the construction finishing happens before the call to `start()`, so the construction happens before any actions in the started thread.)
You need to synchronize every method that changes the state of `Catalog` to make it thread-safe. ``` public synchronized <return type> method(<parameter list>){ ... } ```
Threadsafe publishing of java object structure?
[ "", "java", "multithreading", "java-memory-model", "" ]
I have this bash script on the server that runs every hour, via cron. I was perfectly happy, but now the user wants to be able to configure the frequency through the web interface. I don't feel comfortable manipulating the cron configuration programmatically, but I'm not sure if the other options are any better. The way I see it, I can either: * Schedule a script to run once a minute and check if it should really run "now" * Forgo cron altogether and use a deamon that is its own scheduler. This probably means rewriting the script in python * ...or suck it up and manipulate the cron configuration from the web interface (written in python BTW) What should I do? EDIT: to clarify, the main reason I'm apprehensive about manipulating cron is because it's basically text manipulation with no validation, and if I mess it up, none of my other cron jobs will run. **Here's what I ended up doing:** Taking stefanw's advice, I added the following line at the top of my bash script: ``` if [ ! `cat /home/username/settings/run.freq` = $1 ]; then exit 0 fi ``` I set up the following cron jobs: ``` 0 */2 * * * /home/username/scripts/publish.sh 2_hours @hourly /home/username/scripts/publish.sh 1_hour */30 * * * * /home/username/scripts/publish.sh 30_minutes */10 * * * * /home/username/scripts/publish.sh 10_minutes ``` From the web interface, I let the user choose between those four options, and based on what the user chose, I write the string `2_hours/1_hour/30_minutes/10_minutes` into the file at `/home/username/settings/run.freq`. I don't love it, but it seems like the best alternative.
Give your users some reasonable choices like every minute, every 5 minutes, every half an hour, ... and translate these values to a cron job string. This is user friendly and forbids users to tamper directly with the cron job string.
You could use a python scheduler library that does most of the work already: * [pycron](http://www.kalab.com/freeware/pycron/pycron.htm) * [scheduler-py](http://code.google.com/p/scheduler-py/)
Allowing user to configure cron
[ "", "python", "bash", "cron", "" ]
Is there a way in C# to mark a parameter as optional like VB.net's Optional keyword?
There will be in C# 4.0 For now you can either overload your method, set a default value and call the other method. Or set it to nullable. ``` public void DoSomething(int a) { int defaultValue = 1; DoSomething(a, defaultValue); } public void DoSomething(int a, int b) { // Do something } ``` or ``` public void DoSomething(int a, int? b) { // Check for b.HasValue and do what you need to do } ```
Up until C# 3.0, I'm afraid it is not possible, at least *per se*. (See later section of post.) With the advent of C# 4.0, you could do something like the following: ``` void FooMethod(int foo, string bar = "foobar") { Console.WriteLine("{0}, "{1}", foo, bar); } ``` Any parameter given a default value is necessarily an [**optional arguement**](http://msdn.microsoft.com/en-us/library/dd264739(VS.100).aspx). Which could be called in the following ways: ``` FooBar(123"); // Outputs: "123, foobar" FooBar(123, "hello"); // Outputs: "123, hello" FooBar(123, bar: "hello"); // Outputs: "123, hello" ``` In earlier versions of C#, you might achieve the same by [**operator overloading**](http://msdn.microsoft.com/en-us/library/dd264739(VS.100).aspx). ``` void FooMethod(int foo) { FooMethod(foo, "foobar"); } void FooMethod(int foo, string bar) { Console.WriteLine("{0}, {1}", foo, bar); } ``` **Note**: It is important here not to confuse *what* has been lacking support for optional arguments. The .NET framework (CLR/CIL language) have supported them for a while now (possible always), and the VB.NET language makes use of this. It is only with *C# 4.0* however, that C# specifically makes makes use of the feature.
C#: Is there an "Optional" keyword or alike in C#?
[ "", "c#", "" ]
Given such a list: ``` List<int> intList = new List<int>(); intList.Add(5); intList.Add(10); intList.Add(15); intList.Add(46); ``` how do you obtain the index of the maximum element in the list? In this case, it's at index 3. Edit: It's a shame that standard LINQ doesn't ship this functionalities.
Here is a simple\* and relatively efficient\*\* solution: ``` int indexMax = !intList.Any() ? -1 : intList .Select( (value, index) => new { Value = value, Index = index } ) .Aggregate( (a, b) => (a.Value > b.Value) ? a : b ) .Index; ``` 1. The `!intList.Any() ? -1 :` will force a `-1` if the list is empty; 2. The `Select` will project each `int` element into an anonymous type with two properties: `Value` and `Index`; 3. The `Aggregate` will get the element with the highest `Value`; 4. Finally, we get the `Index` of the chosen element. \* Simplicity is relative. The aim here was to reach a balance of readability and still only scan the list once. \*\* The allocation of lots of new objects during the `Select` is probably wasteful. As some people tested, it doesn't perform well for large lists. **EDIT 1:** empty list check added. **EDIT 2:** added caveats about performance.
this way : ``` var maxIndex = foo.IndexOf(foo.Max()); ```
Obtain the index of the maximum element
[ "", "c#", "linq", "" ]
A SorteDictionary is according to MSDN sorted on the key. Does that mean that you can be sure that it will be sorted when you enumerate it in a foreach? Or does it just mean that the SortedDictionary works that way internally to have better performance in various cases?
When you enumerate the collection it is sorted by keys (even if you enumerate say the `Values` collection). Internally the collection is implemented as a binary search tree (according to the documentation). Both insertion and lookup of values are O(log n) (meaning they are pretty efficient).
[From MSDN](http://msdn.microsoft.com/en-us/library/1z8z05h2.aspx): > The dictionary is maintained in a > sorted order using an internal tree. > Every new element is positioned at the > correct sort position, and the tree is > adjusted to maintain the sort order > whenever an element is removed. While > enumerating, the sort order is > maintained.
C#: Is a SortedDictionary sorted when you enumerate over it?
[ "", "c#", "sorting", "dictionary", "enumeration", "" ]
I want to read the custom XML section from the `app.config` of a C# windows service. How do I go about it? The XML is below: ``` <Books> <Book name="name1" title="title1"/> <Book name="name2" title="title2"/> </Books> ```
What you want to do is read up on [Custom Configuration Sections](http://msdn.microsoft.com/en-us/library/2tw134k3.aspx).
In a project I developed I use something similar for configuration that I found. I believe the article was called the last configuration section handler I'll ever need (I can't find a working link, maybe someone can link it for me). This method takes what you want to do one step further, and actually de-serializes the object into memory. I'm just copying code from my project, but it should be fairly simple to take a step backwards if all you want is the XML. First, you need to define a class that handles your configuration settings. ``` using System; using System.Configuration; using System.Xml; using System.Xml.Serialization; using System.Xml.XPath; namespace Ariel.config { class XmlSerializerSectionHandler : IConfigurationSectionHandler { #region IConfigurationSectionHandler Members public object Create(object parent, object configContext, XmlNode section) { XPathNavigator nav = section.CreateNavigator(); string typename = (string)nav.Evaluate("string(@type)"); Type t = Type.GetType(typename); XmlSerializer ser = new XmlSerializer(t); return ser.Deserialize(new XmlNodeReader(section)); } #endregion } } ``` Now, say you want to load a section of configuration... super easy, cast to the type of object you're expecting to XML Serialize to, and pass the section you're looking for (in this case `SearchSettings`. ``` try { config = (Eagle.Search.SearchSettings)ConfigurationSettings.GetConfig("SearchSettings"); } catch (System.Configuration.ConfigurationException ex) { syslog.FatalException("Loading search configuration failed, you likely have an error", ex); return; } ``` Now, all you need is your App.config file. I chose to split mine into separate files (1 file per section) just to make managing the config a little easier. You define a section, give it a name, and define the type (whatever you called the class listed above) and the assembly's name. App.config: ``` <?xml version="1.0" encoding="utf-8" ?> <configuration> <configSections> <section name="SearchSettings" type="Ariel.config.XmlSerializerSectionHandler, Ariel"/> </configSections> <SearchSettings configSource="Config\Search.config" /> </configuration> ``` Now, all that's left is the config file to be de-serialized. What's important here is that the block matches your section name, and your type is whatever object it should de-serialize to, and the Assembly name. ``` <?xml version="1.0" encoding="utf-8" ?> <SearchSettings type="Eagle.Search.SearchSettings, Eagle"> <NumThreads>4</NumThreads> </SearchSettings> ``` If you just want the pure raw XML, all you should need to do is modify the Object that handles the section to return the XML or do whatever you need to do.
How to Read Custom XML from the app.config?
[ "", "c#", ".net", "windows-services", "app-config", "" ]
I am looking for user-mode multi-threading library/framework for C++ under Linux. I am familiar with boost::thread and ACE\_Thread\_Manager but AFAIK both of them eventually use OS native thread's support. Suggestions will be highly appreciated.
Is [MTasker](http://ds9a.nl/mtasker/) the kind of thing you're looking for? It's also a cooperative multi-tasking library. You might also want to consider just whipping up some state machines. Also check out [State Threads](http://state-threads.sourceforge.net/) and [MIT Pthreads](http://www.humanfactor.com/pthreads/mit-pthreads.html). This tool will assist in the generation of hierarchical state machines, which could be used for this purpose: [CHSM](http://chsm.sourceforge.net/)
GNU PTH: <http://www.gnu.org/software/pth/> It's using cooperative multithreading, which is why it's used in GnuPG (which for security reasons doesn't want real threads, but for responsiveness reasons needs threads).
Is there any user-mode multi-threading library/framework for C++ under Linux?
[ "", "c++", "linux", "" ]
I've been searching around this morning and I'm not finding any simple solutions... basically, I want to capture a change in an input element, but also know the previous value. Here's a change event and an input element in its simplest form. Clearly, I can get the new value with $(elem).val(), but is there a sneaky method I'm missing for getting the previous value? I don't see anything in the jQuery API to do this, but maybe someone's already done this and has some tips? ``` <script> $(document).ready(function(){ $('#myInputElement').bind('change', function(){ //var oldvalue = ??? var newvalue = $(this).val(); }); }); </script> <input id="myInputElement" type="text"> ``` I'm not against writing my own solution, I just want to make sure I'm not recreating the wheel here.
A better approach is to store the old value using .data. This spares the creation of a global var which you should stay away from and keeps the information encapsulated within the element. A real world example as to why Global Vars are bad is documented [here](http://web.archive.org/web/20091030191126/http://billyreisinger.com/blog/2009/01/real-world-example-of-why-global-variables-are-bad/) e.g ``` <script> //look no global needed:) $(document).ready(function(){ // Get the initial value var $el = $('#myInputElement'); $el.data('oldVal', $el.val() ); $el.change(function(){ //store new value var $this = $(this); var newValue = $this.data('newVal', $this.val()); }) .focus(function(){ // Get the value when input gains focus var oldValue = $(this).data('oldVal'); }); }); </script> <input id="myInputElement" type="text"> ```
This might do the trick: ``` $(document).ready(function() { $("input[type=text]").change(function() { $(this).data("old", $(this).data("new") || ""); $(this).data("new", $(this).val()); console.log($(this).data("old")); console.log($(this).data("new")); }); }); ``` # [Demo here](http://jsfiddle.net/salman/t26g4/)
jQuery Change event on an <input> element - any way to retain previous value?
[ "", "javascript", "jquery", "html", "events", "forms", "" ]
What is the difference between function template and template function?
> The term "function template" refers to a kind of template. The term "template function" is sometimes used to mean the same thing, and sometimes to mean a function instantiated from a function template. This ambiguity is best avoided by using "function template" for the former and something like "function template instance" or "instance of a function template" for the latter. Note that a function template is not a function. The same distinction applies to "class template" versus "template class". From [this FAQ](https://womble.decadent.org.uk/c++/template-faq.html#phrase-order) ([archive](https://web.archive.org/web/20160331154357/https://womble.decadent.org.uk/c++/template-faq.html#phrase-order))
Function Template is the correct terminology (a template to instantiate functions from). Template Function is a colloquial synonym. So, there's no difference whatsoever.
What is the difference between function template and template function?
[ "", "c++", "templates", "terminology", "function-templates", "" ]
[\_com\_ptr\_](http://msdn.microsoft.com/en-us/library/417w8b3b(VS.80).aspx) has an overloaded operator&() with a side effect. If I have a variable: ``` _com_ptr_t<Interface> variable; ``` How could I retrieve its address (\_com\_ptr\_t<Interface>\* pointer) without calling the overloaded operator and triggering the side effect?
I've seen this case pop up in an ISO meeting as it broke some offsetof() macro implementations (LWG 273). The solution: `&reinterpret_cast<unsigned char&>(variable)`
I define this utility function: ``` template<typename T> T *GetRealAddr(T &t) { return reinterpret_cast<T*>(&reinterpret_cast<unsigned char &>(t)); } ```
If an operator is overloaded for a C++ class how could I use a default operator instead?
[ "", "c++", "operator-overloading", "" ]
I have a WCF service, marked with the `OperationContract` attribute. I have a potentially long running task I want to perform when this operation is carried out, but I don't want the caller (in this case Silverlight) to have to wait for that to complete. What is my best option for this? I was thinking of either * something like the OnActionExecuted method of `ActionFilterAttibute` in `System.Web.Mvc`, but couldn't see an equivilent. * something listening to an event. (The process I want to call is a static, so I'm not too sure about this approach) * something else: In the scenario I'm working in, I lock the app so the user cannot make any changes during the save until I get the response (a status code) back.
Keep in mind, Silverlight won't actually have to 'wait' for the call to finish. When you create a service reference within Silverlight you will automatically get async calls. Assuming you really don't need to wait for the call to finish (ie: your service method uses a 'void' return type) you can mark the service method as one-way via: ``` [OperationContract(IsOneWay = true)] void MyServiceMethod(some args); ```
In general, I suggest having another process service handle long-running actions. Create a simple Windows Service, and have it pull requests from an MSMQ queue via WCF. Have the main service post requests to the background service, then return to its caller. If anyone cares about the results, then the results may be placed in an output queue, and the Silverlight application could get them by querying the output queue. You might also look into Windows Workflow Foundation, which is made to fit very well with WCF. In fact, you can have just this kind of service, where all the logic of the service is in the workflow. If the workflow takes too long, it can be persisted to disk until it's ready to go again.
WCF Service, executed attribute?
[ "", "c#", "wcf", "" ]
Is it possible to write SQL query that returns table rows in random order every time the query run?
``` SELECT * FROM table ORDER BY NEWID() ```
This is the simplest solution: ``` SELECT quote FROM quotes ORDER BY RAND() ``` Although it is not the most efficient. [This one](http://www.titov.net/2005/09/21/do-not-use-order-by-rand-or-how-to-get-random-rows-from-table/) is a better solution.
Return rows in random order
[ "", "sql", "sql-server", "t-sql", "" ]
I always get confused with licenses, I'm reading up again, but I'm sure someone out there already understands this and may be able to explain it more clearly. I'm trying to get my company to use geodjango, and being a typical large enterprise company they don't want to open-source the resulting project. And therefore opposed to touching anything stamped "GPL". Looking at the geodjango stack with the recommended postgresql the licenses are: **Django** - BSD license **Postgresql** - BSD license **PostGIS** - *GPL* **GEOS** - LGPL **PROJ.4** - MIT license **GDAL** - MIT/X license **psycopg2** - *GPL* The wikipedia entry on gpl says the following: > Many of the most common free software licenses, such as the original MIT/X license, the > BSD license (in its current 3-clause form), and the LGPL, are "GPL-compatible". That > is, their code can be combined with a program under the GPL without conflict (the new > combination would have the GPL applied to the whole). From wikipedia's GPL entry, "Compatibility and multi-licensing": <http://en.wikipedia.org/wiki/Gpl> Does using psycopg2/PostGIS components with geodjango, make the resulting project's license GPL? If so, what are the alternatives? **UPDATE** *psycopg2* has a clause to specifically address how GPL is applied, thanks piquadrat.
Disclaimer: the following is my opinion and not intended to be legal advice -- consult a licensed attorney for that. In general, using psycopg2/PostGIS with your GeoDjango project does not make it subject to the GPLv2. I'll speak about PostGIS since others have already addressed the question as it relates to psycopg2. Unlike the other geospatial libraries that it uses, GeoDjango does not 'link' to PostGIS. PostgreSQL is what is linked to the PostGIS library (`liblwgeom.so`), and in doing exposes a wide selection of SQL functions. GeoDjango calls the SQL functions and uses their output to do what it does. Let's examine term 0 of the GPLv2: > This License applies to any program > or other work which contains a notice > placed by the copyright holder saying > it may be distributed under the terms > of this General Public License. The > "Program", below, refers to any such > program or work, and a "work based on > the Program" means either the Program > or any derivative work under copyright > law: that is to say, a work containing > the Program or a portion of it, either > verbatim or with modifications and/or > translated into another language. > > ... > > Activities other than copying, > distribution and modification are not > covered by this License; they are > outside its scope. The act of running > the Program is not restricted, and the > output from the Program is covered > only if its contents constitute a work > based on the Program (independent of > having been made by running the > Program). Whether that is true depends > on what the Program does. Because GeoDjango is just running PostGIS (by calling its public SQL API functions), and the output of PostGIS is geospatial data and/or numeric values (not source code based on PostGIS) it's clear to me that GeoDjango (or an app built with it) is not covered by the GPL because it is not copying, modifying, distributing, nor a derivative work of GPL code. Notice I said "in general" at the beginning. If you are *distributing* your GeoDjango application *including* psycopg2 and PostGIS, then your code may be subject to the GPL. For web applications this is typically not a problem, because the code is almost never distributed to others like traditional shrink-wrapped software. The code is running on your server, and the only thing your distributing is output of your program (e.g., HTML) to the users (sidebar: this is why I avoid GPL-licensed JavaScript libraries like the plague). This is how Google can keep their heavily-modified Linux kernel to themselves, because their modifications never leave the servers at Google. Bottom-line: if you are actually selling/distributing a GeoDjango application to end-users (they get a copy of the application), then *do not* include the GPL-licensed prerequisites to avoid triggering the licensing requirements on your proprietary code. In other words, install those libraries on-site so that you cannot be considered to be "distributing" GPL source/object code with your closed-source application.
You might ask Justin Bronn, the creator of GeoDjango, directly. He is also a lawyer that specializes in intellectual property. <http://djangopeople.net/jbronn/>
geodjango + PostGIS = GPL?
[ "", "python", "django", "licensing", "" ]
I would like to know if it is acceptable/preferred to use self::method() and parent::method() when working in php classes. You can use $this->method() but $this-> can also refer to a class variable, a parent class variable, or a method from the parent class. There is no ambiguity in self:: Is self:: depreciated and/or are there any caveats or cons to using this style? I understand that self:: and parent:: refer to a static instance of the class, but in kohana, unless you specifically define a method as static, there does not seem to be a difference. Thanks. Added an example: Assuming this application stores forums from multiple websites... ``` class Forum_Controller extends Controller { function __construct() { parent::__construct(); } function index() { echo self::categories(); } /* * get a list of categories from a specific site. */ private function categories() { $db = new Database; $categories = $db->query(" SELECT * FROM forum_categories WHERE fk_site = '$this->site_id' "); $view = new View('categories_view'); $view->categories = $categories; return $view; } } ``` This examples works in kohana with error reporting set to: error\_reporting(E\_ALL & ~E\_STRICT); $this->site\_id is defined in the main Controller\_Core class (a library in kohana). As far as I know, $this is not supposed to be available since I am calling self::categories() in a static manner, but it is only when i define categories() as static that it throws an error. But as I said I much rather prefer using self:: because from a readability perspective, I know exactly where this function should be, rather than using $this which causes ambiguity, to me that is.
Controllers are not static in Kohana, although they can contain static member variables / methods or constants. `self::` is a shorthand way of writing `ClassName::` i.e ``` class Animal { public static $arms = 0; } class Dog extends Animal { public static $leg = 0; const NAME = 'dog'; public static function bark() { echo 'Woof'; } } ``` To call static functions or get constants from a class we use the scope resolution operator `::`. Static functions are *per class* not per object. Saying `::` refers to static instances of a class is wrong, it is just a way to access the static methods - there isn't an object instance that has these methods. so: ``` Dog::bark(), Dog::$leg, Dog::NAME, ``` we can also use ``` Animal::$arms ``` Inside the class Dog we can use `self::` and `parent::` so that we do not need to type the full class name (as it could be very long!) In answer to your question though: No - `self::` is not deprecated and no it is not bad practice to use it. The reason it is not used in kohana core is for a very different reason.... (transparent class extensions with `eval` read below for more info...). p.s calling non-static methods statically is *wrong* and shouldn't be allowed- if you set `error_reporting(E_ALL | E_STRICT)` (like you should during development) you will see an error being raised. **Basically what happens is:** Core has a file called: ``` class Controller_Core { public function someMethod(){} } ``` You create: ``` // We can use someMethod of Controller_Core Index_Controller extends Controller {} ``` This is really extending `Controller_Core` **UNLESS** you have created MY\_Controller.php which would be `class Controller extends Controller_Core`. ``` //MY_Controller.php class Controller extends Controller_Core { // overloads Controller_Core::someMethod without us having to change the core file public function someMethod(){} } ```
There is a difference. `$this` refers to an instance of an object. `parent` and `self` are used to call methods statically. [This page of PHP's manual](http://www.php.net/manual/en/language.oop5.basic.php) explains it in better detail than I have time to write at the moment. The first example in particular should help to highlight some of the differences. I encourage you to copy paste the first example and mess about with it, as I think its an important concept to get in your mind if you don't already know the difference.
Using $this, self::, parent:: for code readability
[ "", "php", "coding-style", "kohana", "" ]
A C++ compiler that I will not name lets you take the address of a literal, int \*p = &42; Clearly 42 is an r-value and most compilers refuse to do so. Why would a compiler allow this? What could you do with this other than shoot yourself in the foot?
What if you needed a pointer to an integer with the value of 42? :) C++ references are much like automatically dereferenced pointers. One can create a constant reference to a literal, like this: ``` const int &x = 42; ``` It effectively requires the compiler to initialize a pointer with the address of an integer with the value 42, as you might subsequently do this: ``` const int *y = &x; ``` Combine that with the fact that compilers need to have logic to distinguish between a value which has not had its address taken, and one which has, so it knows to store it in memory. The first need not have a memory location, as it can be entirely temporary and stored in a register, or it may be eliminated by optimization. Taking the address of the value potentially introduces an alias the compiler can't track and inhibits optimization. So, applying the **`&`** operator may force the value, whatever it is, into memory. So, it's possible you found a bug that combined these two effects.
Because 42 is the answer to life, the universe and everything. When asked for its address it is the answer itself.
Why do some c++ compilers let you take the address of a literal?
[ "", "c++", "rvalue", "" ]
Is there a way to pass an unlimited amount of arguments to a function, and access all of those arguments without needing to define each one in the heading. Here is an example to make it more clear: ``` function doSomething($var1="", $var2="".........) { // Do something with the arguments } ``` I don't want to have to go define a bunch of arguments. Is there a way to just grab all the arguments in an array? Even if they haven't been defined? (PHP BTW) The end result should look something like this: ``` func("hello", "ya", "hi", "blah", "test", "go"); function func() { //Loop Over Arguments } ``` I've seen some native PHP functions be able to accept a seemingly infinite number of arguments, but can user-defined functions do the same?
You can use [`func_get_args`](http://php.net/func_get_args), [`func_get_arg`](http://php.net/manual/en/function.func-get-arg.php), and [`func_num_args`](http://php.net/manual/en/function.func-num-args.php) Considering you have declared these three variables : ``` $param_1 = "A"; $param_2 = "B"; $param_3 = "C"; ``` Here's a first example, using `func_get_args` to get all the parameters in one array : ``` my_function_1($param_1, $param_2, $param_3); function my_function_1() { $num_args = func_num_args(); if ($num_args >= 1) { $args = func_get_args(); var_dump($args); } } ``` And here's another one to get the parameters one by one, with `func_get_arg` : ``` my_function_2($param_1, $param_2, $param_3); function my_function_2() { $num_args = func_num_args(); if ($num_args >= 1) { $args = func_get_args(); for ($i = 0 ; $i<$num_args ; $i++) { var_dump(func_get_arg($i)); } } } ```
See [func\_get\_args](https://www.php.net/manual/en/function.func-get-args.php). It does exactly what you want
Accessing Undefined Arguments
[ "", "php", "" ]
How do I unit test a protected method in C++? In Java, I'd either create the test class in the same package as the class under test or create an anonymous subclass that exposes the method I need in my test class, but neither of those methods are available to me in C++. I am testing an unmanaged C++ class using NUnit.
Assuming you mean a protected method of a publicly-accessible class: In the test code, define a derived class of the class under test (either directly, or from one of its derived classes). Add accessors for the protected members, or perform tests within your derived class . "protected" access control really isn't very scary in C++: it requires no co-operation from the base class to "crack into" it. So it's best not to introduce any "test code" into the base class, not even a friend declaration: ``` // in realclass.h class RealClass { protected: int foo(int a) { return a+1; } }; // in test code #include "realclass.h" class Test : public RealClass { public: int wrapfoo(int a) { return foo(a); } void testfoo(int input, int expected) { assert(foo(input) == expected); } }; Test blah; assert(blah.wrapfoo(1) == 2); blah.testfoo(E_TO_THE_I_PI, 0); ```
You can also use using keyword to expose public block (using . ``` // in realclass.h class RealClass { protected: int foo(int a) { return a+1; } int foo(string a) { return a.length(); } // Overload works too template<class T> int foo(const T& a) { return 1; } // Templates work too }; // in test code #include "realclass.h" class RealClassExposed : public RealClass { public: using RealClass::foo; }; RealClassExposed blah; assert(blah.foo(1) == 2); assert(blah.foo("test") == 4); assert(blah.foo(blah) == 1); ``` See: <http://en.cppreference.com/w/cpp/language/using_declaration>
How do I unit test a protected method in C++?
[ "", "c++", "unit-testing", "nunit", "protected", "" ]
I'm trying to implement the [Sieve of Eratosthene](http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes) in C++. However after several attempts at this I always get runtime errors. I'm thinking this has to do with the state of iterators being used get corrupted somewhere. I can't put my finger on it though. Here is my code: ``` //Sieves all multiples of the current sequence element bool multiple_sieve(std::list<int>& num_list) { std::list<int>::iterator list_iter(num_list.begin()); std::list<int>::reverse_iterator last_element_iter(num_list.rbegin()); for(std::list<int>::iterator elements_iter(++list_iter); elements_iter != num_list.end();) { if((*elements_iter % *list_iter == 0) && (*elements_iter <= *last_element_iter) && (*list_iter != 1)) num_list.erase(elements_iter); else ++elements_iter; } return true; } std::list<int>& prime_sieve(std::list<int>& num_list) { for(std::list<int>::iterator list_iter(num_list.begin()); list_iter != num_list.end(); ++list_iter) multiple_sieve(num_list); return num_list; } ``` What I'm doing wrong? What's generating the runtime errors? Update: When I run this in my tests I get an error with the message "list iterators are not compatible".
This line: ``` num_list.erase(elements_iter); ``` Is going to cause you problems since you are modifying the list while iterating it. You could do this to avoid that problem: ``` elements_iter = num_list.erase(elements_iter); ``` ETA: Removed stuff about erase() invalidating other iterators (looks like they are safe in this case) - just set elements\_iter to the return value from erase() and you should be good to go.
I don't know why you're using a list here. It's easier to run sieve on vector and save primes in list. ``` std::list<int> primes(int MAXN){ std::list<int> result; std::vector<bool> sieve(MAXN+1,true); for(int i=2;i<=MAXN;i++){ if(sieve[i]==true){ result.push_back(i); if((long long)i*i<=MAXN) //prevent integer overflow for(int j=i*i;j<=MAXN;j+=i) sieve[j]=false; } } return result; } ```
What's wrong with this algorithm implementation [Sieve of Erathosthene]
[ "", "c++", "algorithm", "" ]
I created a "Hello World" application, in the same vein as <http://giantflyingsaucer.com/blog/?p=409>. It works perfectly on my development computer, using the built-in web server. I followed Phil Haack's advice for doing a Bin Deployment at <http://haacked.com/archive/2008/11/03/bin-deploy-aspnetmvc.aspx>. I used the Publish feature to get an output directory, and copied all of the files to the correct places on the ISP (Network Solutions). When I go to the site, I get the welcome page, but when I do <http://mydomain/hello>, I get a 404 error. What could be the problem? --- Here is the fix. Apparently Network Solutions is running IIS6 after all. I got what I needed from <http://blog.codeville.net/2008/07/04/options-for-deploying-aspnet-mvc-to-iis-6/>. The new routing is ``` {controller}.aspx/{action}/{id} ``` Notice the addition of the .aspx after the controller placeholder. IIS6 needs this because it always thinks it is talking to an actual web page instead of a controller. I'm not keen on the extra characters in the url, but I may have to live with it.
Are you sure you deployed it to an IIS7 server? If the server runs IIS6 check [this](http://haacked.com/archive/2008/11/26/asp.net-mvc-on-iis-6-walkthrough.aspx) and [this post](http://blog.codeville.net/2008/07/04/options-for-deploying-aspnet-mvc-to-iis-6/).
Another long shot: Do you know if your host has ASP.NET MVC installed in the server? If he doesn't, you need to [copy the three MVC DLLs to your BIN folder](http://haacked.com/archive/2008/11/03/bin-deploy-aspnetmvc.aspx) as well.
ASP.NET MVC: Default page works, but other pages return 404 error
[ "", "c#", "asp.net-mvc", "" ]
In my application, I have two classes: a logger that actually logs to the database and a dummy logger that does nothing (used when logging is disabled). Here is the entire DummyLog class: ``` class DummyLog(object): def insert_master_log(self, spec_name, file_name, data_source, environment_name): pass def update_master_log(self, inserts, updates, failures, total): pass ``` On one hand, I should probably let this go and not test it since there's not really any code to test. But then, my "test-infected" instinct tells me that this is an excuse and that the simplicity of the class means I should be *more* willing to test it. I'm just having trouble thinking of what to test. Any ideas? Or should I just let this go and not write any tests?
Of course you can test a class that doesn't do anything. You test that it does, in fact, not do anything. In practice, that means: * it exists and can be instantiated; * it doesn't throw an exception when used; call every method and simply assert that they succeed. This also doubles as checking that the class does, in fact, define every method that it's expected to. Don't run this test on DummyLog; use it as a generic test and run it on *all* loggers. When you add another method to the real Log class a year from now and forget to add it to DummyLog, the test will notice. (As long as you do remember to add a general test for the method, of course, but hopefully adding the test should be habitual, even if you forget about related classes.)
If you don't test, how will you really know it does nothing? :) Sorry - couldn't resist. Seriously - I would test because some day it might do more?
Do I test a class that does nothing?
[ "", "python", "unit-testing", "testing", "polymorphism", "" ]
Often I will send debugging info to my log file from within Java, and it helps to give decent information as to where in the code the log message was generated so I can quickly refer back to it. I don't want to hard-code anything in the log message about its location, because I have to remember to update the log message if I rename its method or otherwise refactor the code into a different structure. I'd love to have a static function that simply returns the calling function's class and method name. For example, if I have a class called Machine and a method called doStuff, I'd like my log message generation code in that method to look something like this: ``` String log_msg = Blah.getClassAndMethodName()+" did the wrong thing!"; ``` The static method getClassAndMethodName() in class Blah would return "Machine.doStuff". That way, when I look at the log file, I can easily tell where in the code the message was generated. I realize this is a bit tricky, since I need this method in Blah to return information about its calling function in a separate class, Machine, but this would make it easy to just use this static call anywhere. I don't know if this is possible, but I'd appreciate any pointers towards an answer! Also, assuming it is possible, is this a particularly high overhead kind of operation? (I'm assuming reflection would be needed, not my strong suit) Thanks!
Try this: ``` public static Log make() { Throwable t = new Throwable(); StackTraceElement directCaller = t.getStackTrace()[1]; return LogFactory.getLog(directCaller.getClassName()); } ``` The first entry in in the stacktrace, is the calling class
If you call [Thread.getStackTrace()](http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Thread.html#getStackTrace%28%29), you can determine your call stack from there. > Returns an array of stack trace > elements representing the stack dump > of this thread. This method will > return a zero-length array if this > thread has not started or has > terminated. If the returned array is > of non-zero length then the first > element of the array represents the > top of the stack, which is the most > recent method invocation in the > sequence. The last element of the > array represents the bottom of the > stack, which is the least recent > method invocation in the sequence. Re. performance. I can't advise beyond suggesting that you measure it. If your debug output can be enabled/disabled, I would ensure that you only do the above when debug output is *enabled*, so you only take the performance hit when required.
Java: Any simple way a function can return the calling class and method name?
[ "", "java", "reflection", "" ]
Is there any way to match a function block in javascript source code using regular expressions? (Really I'm trying to find the opposite of that, but I figured this would be a good place to start.)
There are a certain things that regular expressions just aren't very good at. That doesn't mean it's impossible to build an expression that will work, just that it's probably not a good fit. Among those things: * multi-line input * nesting Javascript function blocks tend to cover multiple lines, and you are going to want to find the matching "{" and "}" braces that signify the start and end of the block, which could be nested to an unknown depth. You also need to account for potential braces used inside comments. RegEx will be painful for this. That doesn't mean it's impossible, though. You might have additional information about the nature of the functions you're looking for. If you can do things like guarantee no braces in comments and limit nesting to a specific depth, you could still build an expression to do it. It'll be somewhat messy and hard to maintain, but at least within the realm of the possible.
I have a quite effective javascript solution, contrary to everyone elses belief... try this, i've used it and it works great `function\s*([A-z0-9]+)?\s*\((?:[^)(]+|\((?:[^)(]+|\([^)(]*\))*\))*\)\s*\{(?:[^}{]+|\{(?:[^}{]+|\{[^}{]*\})*\})*\}` <https://regex101.com/r/zV2fO7/1>
Regular Expressions for matching functions in javascript source code?
[ "", "javascript", "regex", "" ]
I'm sure this is very easy, but I've got a sudden mental block. I'm trying to get a DateTime object for the next occurence of 3am. For example, if `DateTime.Now` is `16/july/2009 : 12:04pm` - the next occurance of 3am would be `17/july/2009 : 03:00` However, if `DateTime.Now` was `17/july/2009 : 01:00` then the next occurence would still be `17/july/2009 : 03:00` (not the day after). Does that make sense?
One option: ``` DateTime now = DateTime.Now; DateTime today3am = now.Date.AddHours(3); DateTime next3am = now <= today3am ? today3am : today3am.AddDays(1); ``` Another: ``` DateTime now = DateTime.Now; DateTime today = now.Date; DateTime next3am = today.AddHours(3).AddDays(now.Hour >= 3 ? 1 : 0) ``` Lots of ways of skinning that particular cat :) This is all in *local* time of course, which means you don't need to worry about time zones. Life becomes trickier if you want to get time zones involved... Note that it's a good idea to take `DateTime.Now` *once* to avoid problems if the date rolls over while you're calculating...
``` DateTime now = DateTime.Now; DateTime threeAM = now.Date.AddHours(3); if (threeAM < now) threeAM = threeAM.AddDays(1); ```
DateTime of next 3am occurrence
[ "", "c#", "datetime", "" ]
I'm programming with PHP. I want to redirect https://abc.example.com/blah1/blah2 to https://www.example.com/blah1/blah2 but I don't want to redirect https://abc.example.com redirect to https://www.example.com Is it possible while preserving session information across the redirections? Thank you.
You can continue using the redirects as you have them now, but adjust your `session.cookie_domain` to use the top-level domain (e.g. example.com). You can do this by using [`session_set_cookie_params`](https://www.php.net/manual/en/function.session-set-cookie-params.php) or setting [`session.cookie_domain`](https://www.php.net/manual/en/session.configuration.php#ini.session.cookie-domain) in your php.ini file (or in a .htaccess file after `php_value` directive). That should allow your session information to persist across all sub-domains of your site.
If you’re using a cookie for the session ID, then you need to set the cookie for a common domain. If you are using `www.example.com` and *`foobar`*`.example.com`, you need to set the cookie for `example.com` to have it valid for both `www.example.com` and *`foobar`*`.example.com`.
How can I preserve session information when redirecting from one subdomain to another?
[ "", "php", "session", "redirect", "subdomain", "" ]
I know that with anonymous functions, local stack variables are promoted to a class, are now on the heap etc. So the following does not work: ``` using System; using System.Collections.Generic; using System.Linq; namespace AnonymousFuncTest { class Program { static void Main(string[] args) { foreach (var f in GetFuncs()) { Console.WriteLine(f()); } Console.ReadLine(); } static IEnumerable<Func<int>> GetFuncs() { List<Func<int>> list = new List<Func<int>>(); foreach(var i in Enumerable.Range(1, 20)) { list.Add(delegate() { return i; }); } return list; } } } ``` I know changing GetFuncs to this would work: ``` static IEnumerable<Func<int>> GetFuncs() { foreach(var i in Enumerable.Range(1, 20)) { yield return () => i; } } ``` But say I'm doing something like the following: ``` foreach (var arg in someArgList) { var item = new ToolStripMenuItem(arg.ToString()); ritem.Click += delegate(object sender, EventArgs e) { new Form(arg).Show(); }; mainMenu.DropDownItems.Add(ritem); } ``` This of course does not have the intended effect. I know why it doesn't work, just need suggestions on how to fix it so it does.
You should change it like this: ``` static IEnumerable<Func<int>> GetFuncs() { List<Func<int>> list = new List<Func<int>>(); foreach (var i in Enumerable.Range(1, 20)) { int i_local = i; list.Add(() => i_local); } return list; } ``` EDIT Thanks to Jon Skeet, read his answer.
Just to elaborate on kek444's answer, the problem isn't that local variables are being captured - it's that the *same* local variable is being captured by all of your delegates. Using a copy of the variable within the loop, a new variable is "instantiated" on each iteration of the loop, so each delegate captures a different variable. See [my article on closures](http://csharpindepth.com/Articles/Chapter5/Closures.aspx) for more details. --- *An alternative approach:* For this particular situation, there's actually a nice alternative using LINQ: ``` static IEnumerable<Func<int>> GetFuncs() { return Enumerable.Range(1, 20) .Select(x => (Func<int>)(() => x)) .ToList(); } ``` If you want lazy evaluation, you can just drop the `ToList()` call.
Anonymous functions local variable hoisting is getting in the way
[ "", "c#", "" ]
I am looking for a Java library to interface with standard Unix functions, i.e. `stat()`, `getpwuid()`, `readlink()`. This used to exist, and was called `javaunix`. It was released back in 2000. See this [announcement](http://lwn.net/2000/1019/a/javaunix.php3). But the project page is now gone. Is there any modern replacement for these types of functions in Java today? One could make a system call to `/bin/ls -l` and parse the output, or write a custom JNI method, but these approaches are more work than simply using the old `javaunix` library. **Clarification --** In order to find out a file's owner, from a C program, it should call `stat()` which gives the UID of the owner, and then use `getpwuid()` to get the account's name from the UID. In Java this can be done through a custom JNI method, or the `javaunix` library which uses JNI.
I'm aware of two compelling projects: * [posix for Java](http://bmsi.com/java/posix/) (based on JNI) [derived from Jython] * [jna-posix](http://kenai.com/projects/jna-posix) (based on JNA) [derived from JRuby] Personally I like very much [JNA](https://github.com/twall/jna/). Take a look at this example of mine, mapping `link(2)`: ``` import com.sun.jna.Library; import com.sun.jna.Native; class Link { private static final C c = (C) Native.loadLibrary("c", C.class); private static interface C extends Library { /** see man 2 link */ public int link(String oldpath, String newpath); } @Override protected void hardLink(String from, String to) { c.link(to, from); } } ```
JNA-POSIX is stagnant currently, as far as I know. The developers went on to create [JNR-POSIX](https://github.com/jnr/jnr-posix)
Is there a Java library of Unix functions?
[ "", "java", "unix", "java-native-interface", "posix", "" ]
In C++ I can declare a method "inline" and the compiler is likely to inline it. As far as I understand there is no such keyword in Java. Inlining is done if the JVM decides to do so? Can I influence this decision somehow?
A couple of the other answers have suggested that only final methods can be inlined - this is not true, as HotSpot is smart enough to be able to inline non-final methods so long as they haven't been overridden *yet*. When a class is loaded which overrides the method, it can undo its optimisation. Obviously making the method final mean that's never required... Basically let the JVM do its job - it's likely to be a lot better at working out where to inline than you are. Do you have a situation where you're convinced that the JVM isn't doing a good job? Assuming you're using HotSpot, have you tried using the server version instead of client? That can make a *huge* difference.
Although the java compiler can do inline (for short early-bound methods) the **real** inlining will be done by the JIT compiler. The JIT (HotSpot) compiler will be able to,even, inline *virtual* methods. The best way to interact with it is to write a simple and concise code. Most likely, code that uses Reflection will not allow for inlining. Hope that helps.
Inlining in Java
[ "", "java", "jvm", "inlining", "inline-method", "" ]
I'm looking for a concise way to compare two arrays for any match. I am using this comparison to apply a particular style to any table cell that has matching content. One array is a static list of content that should be contained in at least one table cell on the page. The other array is being generated by JQuery, and is the text of all table cells. The reason why I have to compare content to apply style is that the HTML document will semantically change over time, is being generated by different versions of excel (pretty awful looking code), and this script needs to accommodate that. I know that the content I'm looking to apply the style to in this document will never change, so I need to detect all matches for this content to apply styles to them. So, the code should be something like (in english): for each table cell, compare cell text to contents of array. If there is any match, apply this css to the table cell. This is what I have so far (and I know it's wrong): ``` $(document).ready(function(){ $("a.loader").click(function(event){ event.preventDefault(); var fileToLoad = $(this).attr("href"); var fileType = $(this).text(); var makes = new Array("ACURA","ALFA ROMEO","AMC","ASTON MARTIN","ASUNA","AUDI","BENTLEY","BMW","BRITISH LEYLAND","BUICK","CADILLAC","CHEVROLET","CHRYSLER","CITROEN","COLT","DACIA","DAEWOO","DELOREAN","DODGE","EAGLE","FERRARI","FIAT","FORD","GEO","GMC","HONDA","HUMMER","HYUNDAI","INFINITI","INNOCENTI","ISUZU","JAGUAR","JEEP","KIA","LADA","LAMBORGHINI","LANCIA","LAND ROVER","LEXUS","LINCOLN","LOTUS","M.G.B.","MASERATI","MAYBACH","MAZDA","MERCEDES BENZ","MERCURY","MG","MINI","MITSUBISHI","MORGAN","NISSAN (Datsun)","OLDSMOBILE","PASSPORT","PEUGEOT","PLYMOUTH","PONTIAC","PORSCHE","RANGE ROVER","RENAULT","ROLLS-ROYCE / BENTLEY","SAAB","SATURN","SCION","SHELBY","SKODA","SMART","SUBARU","SUZUKI","TOYOTA","TRIUMPH","VOLKSWAGEN","VOLVO","YUGO","Acura","Alfa Romeo","Amc","Aston Martin","Asuna","Audi","Bentley","Bmw","British Leyland","Buick","Cadillac","Chevrolet","Chrysler","Citroen","Colt","Dacia","Daewoo","Delorean","Dodge","Eagle","Ferrari","Fiat","Ford","Geo","Gmc","Honda","Hummer","Hyundai","Infiniti","Innocenti","Isuzu","Jaguar","Jeep","Kia","Lada","Lamborghini","Lancia","Land Rover","Lexus","Lincoln","Lotus","M.G.B.","Maserati","Maybach","Mazda","Mercedes Benz","Mercury","Mg","Mini","Mitsubishi","Morgan","Nissan (Datsun)","Oldsmobile","Passport","Peugeot","Plymouth","Pontiac","Porsche","Range Rover","Renault","Rolls-Royce / Bentley","Saab","Saturn","Scion","Shelby","Skoda","Smart","Subaru","Suzuki","Toyota","Triumph","Volkswagen","Volvo","Yugo"); $("div#carApp").html("<img src='images/loadingAnimation.gif' alt='LOADING...' />"); $("div#carApp").load(fileToLoad, function(){ $("#carApp style").children().remove(); $('#carApp td').removeAttr('style'); $('#carApp td').removeAttr('class'); $('#carApp table').removeAttr('class'); $('#carApp table').removeAttr('style'); $('#carApp table').removeAttr('width'); $('#carApp tr').removeAttr('style'); $('#carApp tr').removeAttr('class'); $('#carApp col').remove(); $('#carApp table').width('90%'); var content = $("#carApp table td"); jQuery.each(content, function() { var textValue = $(this).text(); if (jQuery.inArray(textValue, makes)==true) $(this).css("color","red"); }); }); }); }); ``` Any ideas?
You're checking `$.inArray(...) == true`. [`inArray`](http://docs.jquery.com/Utilities/jQuery.inArray) actually returns an integer with the index of the item in the array (otherwise `-1`.) So you want to check if it is greater than or equal to `0`. Here's how you can change your `each` loop. ``` $('#carApp td').each(function () { var cell = $(this); if ($.inArray(cell.text(), makes) >= 0) { cell.addClass('selected-make'); } }); ``` I use a CSS class instead of the `style` attribute, because it's better practice to put styling in a CSS file rather than in your JavaScript code. Easier to update that way (especially when you want to apply the same style in multiple places in your code.) Other points worth noting: * jQuery selections have the `each(...)` function as well. So you can do `$(...).each(...)` instead of `jQuery.each($(...), ...)` * `jQuery` and `$` are the same object as long as you don't have other frameworks that redefine the `$` variable. Therefore you can do `$.inArray(...)` instead of `jQuery.inArray(...)`. It's a matter of taste, though.
Have you had a look at [`$.grep()`](http://docs.jquery.com/Utilities/jQuery.grep) ? > Finds the elements of an array which > satisfy a filter function. The > original array is not affected. The > filter function will be passed two > arguments: the current array item and > its index. The filter function must > return 'true' to include the item in > the result array.
Using Jquery: Comparing Two Arrays for ANY Match
[ "", "javascript", "jquery", "arrays", "" ]
If you have a header file named ThisIsAHeaderFile.h, the following will still locate the file in Visual Studio: ``` #include <ThisIsAheaderFile.h> ``` Is there a way to enforce case sensitivity so that the `#include` will result in an error?
You can't, because the Windows file system is itself case-insensitive. If you could get into a situation where you had both RICHIE.h and richie.h, it might make sense to control case sensitivity, but you can't.
I would like to point out that this is **not** an unsolvable problem as many tries to point out to the OP. The case insensitivity is beside the point. The point is as [Lorenz03Tx](https://stackoverflow.com/users/340343/lorenz03tx) explains in a comment, even though the file system is case insentitive the case is retained, so it can be controlled. Such a counter measures is really great to have when doing cross platform development, and prevents much after work when the code is compiled for the other platform. Not to forget that making the build process more picky you would induce better habits for the developers, as they gradually will be more consistent how they include and name files. TL;DR One solution is to use a script that simply scans the source files for include statements and tries to match them along the include paths. Such a script could be added to visual studio post-build events, and thus run at every build, or (inspired by [krlmlr](https://stackoverflow.com/users/946850/krlmlr)) use the preprocessor of a compiler that enforce case sensitivity.
How to force Visual Studio preprocessor case sensitivity with #includes?
[ "", "c++", "visual-studio", "include", "c-preprocessor", "" ]
I would like to execute a PHP script from a C program and store the returning content in to a C variable. I tried like following but it doesn't work: **C:** ``` printf("calling php function\n"); execl("/usr/bin/php -q", "/var/www/html/phpinfo.php", NULL); printf("End php function\n"); ``` **PHP:** ``` <?php echo "hello"; ?> ``` **Environment:** * PHP 5.2.6 * Apache 2.0 * Fedora Core 10 Also suggest any other better way to do this.
Short answer here is to use `system()` or `popen()` rather than `execl()`. Seeing as Jason has already posted a good answer about using `popen()`, I'll skip that and explain how to use `execl()` just in case you actually care. Most likely, this is all unnecessary technical mumbo jumbo--but dammit, I had most of this typed out already as a long prelude before discussing `popen()` and I'm not throwing it away now! ## Firstly... When calling `execl()` all of the command-line arguments need to be passed separately. Also, the first argument must be repeated as `argv[0]` in any program's `main()` is traditionally the name of the program. So the fixed call should look like: ``` execl("/usr/bin/php", "/usr/bin/php", "-q", "/var/www/html/phpinfo.php", (char *) NULL); ``` (I added the cast to `(char *)` to ensure that a null pointer is passed as the final argument rather than the integer 0, if `NULL` happens to be defined as `0` and not `(void *) 0`, which is legal.) ## However... This gets the `execl()` call right, but there's a bigger problem. The `exec` family of functions are almost always used in combination with `fork()` and some complicated `pipe()` juggling. This is because the `exec` functions do not run the program in a separate process; they actually replace the current process! So once you call `execl()`, your code is done. Finished. `execl()` never returns. If you just call it like you've done you'll never get to see what happens as your program will magically transform into a `/usr/bin/php` process. OK, so what's this about `fork()` and `pipe()`? At a high level, what you've got to do is split your process into two processes. The parent process will continue to be "your" process, while the child process will immediately call `execl()` and transform itself into `/usr/bin/php`. Then if you've wired the parent and child processes together correctly they'll be able to communicate with each other. To make a long story short, if you're still here and haven't nodded off you should consult the wise oracle Google for way more details about all of this. There are plenty of web sites out there giving even more (!) in-depth details about how to do the `fork`/`exec` dance. I won't leave you hanging though. Here's a function I use for my own programs that does exactly what I've outlined. It is very similar to `popen()` in fact, the only difference being that the caller can access the child's `stderr` stream in addition to `stdin` and `stdout`. ## Code... ``` #include <errno.h> #include <stdio.h> #include <sys/types.h> #include <unistd.h> pid_t execute(const char *command, FILE **in, FILE **out, FILE **err) { pid_t pid; int fd[6]; pipe(&fd[0]); pipe(&fd[2]); pipe(&fd[4]); switch (pid = fork()) { case -1: perror("unable to fork()"); exit(1); case 0: close(fd[1]); // Close write end of stdin. close(fd[2]); // Close read end of stdout. close(fd[4]); // Close read end of stderr. dup2(fd[0], STDIN_FILENO); // Have stdin read from the first pipe. dup2(fd[3], STDOUT_FILENO); // Have stdout write to the second pipe. dup2(fd[5], STDERR_FILENO); // Have stderr write to the third pipe. execlp("/bin/sh", "/bin/sh", "-c", command, (char *) NULL); perror("execlp() failed"); _exit(1); default: close(fd[0]); // Close read end of stdin. close(fd[3]); // Close write end of stdout. close(fd[5]); // Close write end of stderr. if (in) *in = fdopen(fd[1], "wb"); else close(fd[1]); if (out) *out = fdopen(fd[2], "rb"); else close(fd[2]); if (err) *err = fdopen(fd[4], "rb"); else close(fd[4]); return pid; } } ```
Probably the easiest way would be to use the [popen function](http://www.opengroup.org/onlinepubs/009695399/functions/popen.html): (excerpt from linked page): > The following example demonstrates the use of popen() and pclose() to execute the command ls \* in order to obtain a list of files in the current directory: ``` #include <stdio.h> ... FILE *fp; int status; char path[PATH_MAX]; fp = popen("ls *", "r"); if (fp == NULL) /* Handle error */; while (fgets(path, PATH_MAX, fp) != NULL) printf("%s", path); status = pclose(fp); if (status == -1) { /* Error reported by pclose() */ ... } else { /* Use macros described under wait() to inspect `status' in order to determine success/failure of command executed by popen() */ ... } ``` However, wanting to read the output of a PHP script from within a C program is kind of red flag, and I suspect there is probably some cleaner overall solution to this, but it's hard to say more without a higher level description of what you're trying to do.
executing php script from C program and store the results in to a variable
[ "", "php", "c", "fedora10", "" ]
I love Eclipse's quickfixes. I use the "assign parameter to new field" often, but I would very much like to tweak it to not include the final keyword. (GWT RPC doesn't serialize final fields, and I am doing lots of GWT RPC right now.) I have not been able to find a setting that controls this quickfix. Is there a setting I am missing, or do I need to delve into the plugin development docs and make my own, "non final field" quickfix? I am using Eclipse 3.4 UPDATE - marked the answer about the marker resolution extension point as accepted, as it looks like there is not a baked in config option.
A not so easy way is to extend the org.eclipse.ui.ide.markerResolution extension point. ``` <extension point="org.eclipse.ui.ide.markerResolution"> <markerResolutionGenerator markerType="org.eclipse.core.resources.problemmarker" class="org.eclipse.escript.quickfix.QuickFixer"/> </extension> ``` More information is available in [the Eclipse Wiki](http://wiki.eclipse.org/FAQ_How_do_I_implement_Quick_Fixes_for_my_own_language%3F "Eclipse Wiki")
Use the Eclipse Save Actions for the Java Editor. Go to Window --> Preferences --> Java --> Editor --> Save Actions Tick "Perform the selected actions on save" Tick "Addition Actions" Add the following action "Add final modifier to private fields" See the attached screen shot. ![Eclipse Save Action](https://i.stack.imgur.com/AmA9J.png)
How to configure behavior of the "assign parameter to new field" quickfix in eclipse?
[ "", "java", "eclipse", "eclipse-plugin", "eclipse-pdt", "" ]
Can we update a jar / war file in a deployed server and then reload the new jar / war file ? if so how simple we can achieve this, and please if possible list web servers which support this feature.
Yes. All major Java EE Servlet containers support this. All that I've worked with anyway, which includes Glassfish, Tomcat, WebSphere, WebLogic and JRun. I haven't used the other Oracle container, but I would think it does too. That said, none of them support it all that reliably (they'll detect most changes, but there are certain types of class changes that will always require a restart), unless you're using [JavaRebel](http://www.zeroturnaround.com/javarebel/) underneath.
Just by copying the 'war' file in the Server domain folder will automatically deploy it. I have done it with glassfishv3.1 The path for windows is C:\Program Files\glassfish-3.1\glassfish\domains\domain1\autodeploy Once pasted another file gets created automatically [if the server is on] in the same directory For the editing purposes the 'war' file can be opened with programs like WinRar or WinZip Just open the files that you want to change and save it when the winrar asks for it.
Can we update a jar / war file in a deployed server and then reload the new jar / war file?
[ "", "java", "jakarta-ee", "jar", "webserver", "war", "" ]
I am building pages dynamically using a database to store the page info and .NET (C#) to build pages. Part of that process is to set the masterpage (in the code-behind) based on what is in the database and, as I understand it, that has to be done in `Page_PreInit`. My problem is how to pass objects and variables from `Page_PreInit` to `Page_Load`. I have been able to make it work as follows, but am having random compiling errors when using this method: ``` public partial class BuildPage : System.Web.UI.Page { protected static string pageData; protected void Page_PreInit(object sender, EventArgs e) { --- SET pageData = DATA FROM DATABASE, AND SET MASTERPAGE --- } protected void Page_Load(object sender, EventArgs e) { --- USE pageData TO BUILD AND DISPLAY THE REST OF THE PAGE --- } } ``` For various reasons, I'm am not using Visual Studio to compile the page, just letting .NET compile on the fly at the first page request. I have gotten two error messages: 1) "CS0102: The type 'BuildPage' already contains a definition for 'pageData'" 2) "ASPNET: Make sure that the class defined in this code file matches the 'inherits' attribute, and that it extends the correct base class (e.g. Page or UserControl)." The strange thing is that sometimes the page compiles on the first web request. And, for those times that it doesn't on the first request, after a random number of page refreshes, it will compile perfectly. After it compiles everything appears to work fine until I make another change to the code behind and it has to recompile. I seem to only get those compiling errors when using that method to share variables between `Page_PreInit` and `Page_Load`. In other words, if I simply request the data twice from the database, once in 'Page\_PreInit' and once in 'Page\_Load' I never get those errors. But I really would rather not double the database load. So my question really has two parts, first, is that an acceptable way to share variables or is there a better way to pass data from `Page_PreInit` to `Page_Load`? And second, if that is an acceptable way, are the errors unrelated and has anyone seen similar errors that simply go away after repeated web requests before? Thanks for any and all help! fodder
Using a protected (or private) member is definitely the correct way to share objects between methods in a class. However, your member should *not* be `static`. `Static` means there is a single instance across multiple threads. Every copy of the page which is being executed for the different requests accessing that page are competing to read/write that member. Also, your class is marked "partial". That means there could be another class fragment in another file which has additional members and methods for the same `BuildPage` class. If you declare the same `pageData` member in both, they will conflict.
You most likely don't want the member variable to be static. It could produce strange results if more than one person is accessing the page at the same time. It might also be the direct cause of your problem because of the way templates work, though I'm not certain of that.
Pass objects/vars between Page_PreInit and Page_Load
[ "", "c#", ".net", "compiler-construction", "html", "code-behind", "" ]
We have some unit tests which compile and run fine in Eclipse 3.4, but when we try to compile them using javac, it fails. I've managed to cut the code down to something small and self-contained, so it has no external dependencies. The code itself won't make much sense because it's all out of context, but that doesn't matter - I just need to find out why javac doesn't like this: ``` public class Test { public void test() { matchOn(someMatcher().with(anotherMatcher())); } void matchOn(SubMatcher matcher) {} SubMatcher someMatcher() { return new SubMatcher(); } Matcher anotherMatcher() { return null; } } interface Matcher <U, T> {} class BaseMatcher implements Matcher { public BaseMatcher with(Matcher<?,?> matcher) { return this; } } class SubMatcher extends BaseMatcher { @Override public SubMatcher with(Matcher matcher) { return this; } } ``` I've tried with `JDK 1.5.0_10` and `1.6.0_13`, with the same result: ``` Test.java:6: matchOn(test.SubMatcher) in test.Test cannot be applied to (test.BaseMatcher) matchOn(someMatcher().with(anotherMatcher())); ^ 1 error ``` I think this is perfectly valid Java. The SubMatcher.with() method returns a more specific type than BaseMatcher.with(), but the compiler seems to think that the return type is BaseMatcher. However, it's possible that the Eclipse compiler is incorrectly allowing something it shouldn't be. Any ideas?
in BaseMatcher you need to specify type parameters: ``` public SubMatcher with(Matcher<?, ?> matcher) { ``` in order to allow javac to match your `with` method PS imho is a bug of eclipse compiler
I made it build successfully by adding `<?,?>` to `Matcher` in `SubMatcher.with`: ``` class SubMatcher extends BaseMatcher { @Override public SubMatcher with(Matcher<?,?> matcher) { return this; } } ``` Without this, the method signature is different from the base. I wonder whether there's a bug in the `@Override` checking that fails to notice this.
Why does Eclipse compile this, but javac doesn't?
[ "", "java", "compiler-construction", "jls", "" ]
I am trying to use the MS SQL Server 2005 Import/Export tool to export a table so I can import it into another database for archival. One of the columns is text so if I export as comma-delimited, when I try to import it into the archive table, it doesn't work correctly for rows with commas in that field. What options should I choose to ensure my import will work correctly?
Over a year later, I now have an ideal solution to my data export needs, thanks to [https://stackoverflow.com/questions/20363/](https://stackoverflow.com/questions/20363/sql-server-2005-export-table-programatically-run-a-sql-file-to-rebuild-it/228957#228957) ``` bcp "SELECT * FROM CustomerTable" queryout "c:\temp\CustomerTable.bcp" -N -S SOURCESERVERNAME -T bcp TargetDatabaseTable in "c:\temp\CustomerTable.bcp" -N -S TARGETSERVERNAME -T -E ``` * -N use native types * -T use the trusted connection * -S ServerName * -E Keep identity values specified in the data file Very quick and easy to embed within code.
I never use the comma delimter unless the client requires it. Try using | as a delimter. YOu can also use the text qualifier if need be.
How to export text data from a SQL Server table?
[ "", "sql", "sql-server", "import", "export", "etl", "" ]
I'm facing a problem that I don't know how to solve and am hoping the community can help. I'm writing an app that manages "Lead" objects. (These are sales leads.) One part of my program will import leads from a text file. Now, the text file contains lots of potential leads, some of which I will want to import and some of which I won't. For ease of programming (and use), I'm parsing the text file into a List<Lead> object, and using a DataGridView to display the leads by setting the DataSource property of the DataGridView. What I want to do is add a column to the grid, called "Import," with a checkbox that the user can check to indicate whether or not each lead should be imported. My first thought is to derive a class from Lead: ```` ``` public Class LeadWithImportCheckbox : Lead { bool bImport = false; ``` ```` public bool Import { get { return bImport;} set { bImport = value;} } } However, the parsing engine returns a list of Lead objects. I can't downcast a Lead to a LeadWithImportCheckbox. This fails: ```` ``` LeadWithImportCheckbox newLead = (LeadWithImportCheckbox)LeadFromParsingEngine; ``` ```` This is an invalid cast. The other option I see is to create a constructor for LeadWithImportCheckbox: ```` ``` public LeadWithImportCheckbox(Lead newlead) { base.Property1 = newlead.Property1; base.Property2 = newlead.Property2; .... base.Property_n = newlead.Property_n; } ``` ```` This is problematic for two reasons. One, the Lead object has several dozen properties and writing this constructor is a PITA. But worse, if I ever change the underlying structure of Lead, I need to remember to go back and change this constructor for LeadWithImportCheckbox. This is a danger to my code maintenance. Is there a better way of accomplishing my goal?
or, to avoid the PITA aspect, use reflection... (try this...) EDIT: use property, not Field as I had originally written... ``` public class NewLead : Lead { public bool Insert; public NewLead(Lead lead, bool insert) { Insert = insert; foreach (PropertyInfo pi in typeof(Lead).GetProperties()) GetType().GetProperty(pi.Name).SetValue (this, pi.GetValue(lead,null), null); } } ```
``` public class LeadListItem { public Lead Lead { get; set; } public bool ShouldImport { get; set; } } ``` i.e. don't copy the Lead object's contents, just store a reference to it in a new LeadListItem object, which adds extra info "outside" the original object. If you want the properties of Lead to appear in the grid, there is almost certainly a way of doing that. Why not ask that question, instead of downvoting me for telling you the right answer to this question!
Downcasting in C#
[ "", "c#", "inheritance", "downcast", "" ]
of all the languages i know im the weakest in php... I have a script... that takes a csv file and does some stuff with it... fairly simple. the issue i am having: in\_array('username', $headers) ... returns null... while... print\_r ($headers); shows username being the first entry in the csv. thoughts? mistakes i may have made? TIA code here ``` /// Turn the string into an array $rows = explode("\n", $this->raw_data); /// First row includes headers $headers = $rows[0]; $headers = explode($this->delimiter, $headers); /// Trim spaces from $headers $headers = array_map('trim', $headers); /// Check that there are no empty headers. This can happen if there are delimiters at the end of the file foreach($headers as $header){ if(!empty($header)){ $headers2[] = $header; } } $headers = $headers2; if(! in_array('password', $headers)){ /// Add password column for generated passwords $headers[] = 'password'; } /// Add status column to the headers $headers[] = 'status'; $this->headers = $headers; /// Check that at least username, name and email are provided in the headers if(!in_array('username', $headers) || !in_array('name', $headers) || !in_array('email', $headers)){ echo "error\n"; return false; } ```
You can use the built in `str_getcsv()` function. Try replacing the `$headers` variable assignment with ``` $headers = str_getcsv($rows[0], $this->delimiter); ``` Then find the value(column) you want and loop through the rest of the `$rows` using the same `str_getcsv()` function to get the matches you need. You may want to use the `file()` function to grab the file in an array delimited by newlines to begin with, as well.
Check the first three functions [in this list](https://www.php.net/manual-lookup.php?pattern=csv&lang=en) . Your problem can arise from several causes. Start by elimination of unnecessary parsing by using the built in CSV function.
php array in_array oddity
[ "", "php", "arrays", "" ]
I have several xml files whose postfix is not .xml, but .component Now I want to handle them in the c# program, but It seems that the c# cant even find the root element of these xml files ``` var doc = new XmlDocument(); doc.Load(path); // MG: edited to Load based on comment XmlNode root = doc.SelectSingleNode("rootNodename"); ``` It seems that the root is null, How should I cope with this?
Given that you've resolved the `Load`/`LoadXml` confusion, I expect the issue is namespaces; do you have example xml? Handling xml with namespaces gets... "fun" ;-p For example: ``` XmlDocument doc = new XmlDocument(); doc.LoadXml(@"<test xmlns='myFunkyUri' value='abc'/>"); // wrong; no namespace consideration XmlElement root = (XmlElement)doc.SelectSingleNode("test"); Console.WriteLine(root == null ? "(no root)" : root.GetAttribute("value")); // right XmlNamespaceManager nsmgr = new XmlNamespaceManager(doc.NameTable); nsmgr.AddNamespace("x", "myFunkyUri"); // x is my alias for myFunkyUri root = (XmlElement)doc.SelectSingleNode("x:test", nsmgr); Console.WriteLine(root == null ? "(no root)" : root.GetAttribute("value")); ``` Note that even if your xml declares xml aliases, you may still need to re-declare them for your namespace-manager.
LoadXml takes an XML string, not a file path. Try Load instead. Load doesn't care about the file extension. Here is a link to the documention for Load: <http://msdn.microsoft.com/en-us/library/system.xml.xmldocument.load.aspx>
XmlDocument.SelectSingleNode returns null for root node
[ "", "c#", "xml", "file-extension", "" ]
I got a table 'foo' that looks like ``` ID | NAME ------+---------------------------- 123 | PiratesAreCool 254 | NinjasAreCoolerThanPirates ``` and a second table 'bar' ``` SID | ID | created | dropped ------+------+------------+----------- 9871 | 123 | 03.24.2009 | 03.26.2009 9872 | 123 | 04.02.2009 | ``` `bar.ID` is a reference (foreign key) to `foo.ID`. Now I want to prevent that you can insert a new record to 'bar' when there is a record with the same ID and bar.dropped is null on that record. So, when the 'bar' looks like above ``` INSERT INTO BAR VALUES ('9873','123','07.24.2009',NULL); ``` should be forbidden, but ``` INSERT INTO BAR VALUES ('9873','254','07.24.2009',NULL); ``` should be allowed (because there is no 'open' bar-record for 'NinjasAreCoolerThanPirates'). How do i do that? I hope my problem is clear and somebody can help me.
hmm, that should be enough to just create a unique index. ``` create unique index ix_open_bar on bar (id, dropped); ``` of course, that would also have the effect that you can not drop a bar twice per day (unless the dropped is a timestamp which would minimize the risk) Actually, I noticed that Postgres have support for partial indexes: ``` create unique index ix_open_bar on bar (id) where dropped is null; ``` **Update:** After some tests, the unique constraint is not enforced on null values, but the partial indexes will still work. And if you don't want to use the partial indexes, this might work as well: ``` create unique index ix_open_bar on bar(id, coalesce(dropped, 'NULL')); ``` However, when using coalesce, you need to have the same datatypes on them (so if dropped is a timestamp, you need to change 'NULL' to a timestamp value instead).
This will only insert a record if there isn't an 'open' record in bar for your id ``` INSERT INTO bar SELECT '9873','254','07.24.2009',NULL WHERE NOT EXISTS(SELECT 1 FROM bar WHERE ID='254' AND dropped IS NULL) ```
postgres: How to prevent INSERT in a special case
[ "", "sql", "database", "postgresql", "" ]
This is more a question of curiosity. So I was reading a chapter from ([Sitepoint's latest PHP/MySQL book](http://www.sitepoint.com/books/phpmysql4/)), in which the author mentioned using the extension ".html.php" to indicate files that has both HTML and PHP. I tried it out, and discovered this: If I have a file "fileA.html.php", and somewhere in "fileB.html" I have a link thusly: ``` <a href="fileA.html">Text text</a> ``` I'm able to link directly to fileA.html.php, correctly parsed, even though logic, and the book, tells me that I should have written `href="fileA.html.php"`. Anyone have any idea what PHP function does this, or if it's just standard PHP behavior? (Not that I'm complaining, it's just something my client noted and thought was cool.)
You'd have to have your server configured to do that. If you're using Apache there are numerous ways to accomplish that with htaccess rewrite rules or other processors. But if you're going to go to those lengths, why require the html at all? I'd say either serve the file with the appropriate extension type (in that case just .php) or make it extensionless or extension-optional. The only reason to do it at all is to make it easier on your users. There's no advantage for changing the extension otherwise.
PHP is not at cause. Apache probably has `mod_spelling` enabled and is auto-correcting the link. That behavior will not be consistent between servers with different configurations.
Using ".html" to link to a .html.php file - what's the magic?
[ "", "php", "html", "" ]
Consider this code: ``` class arraytest { public static void main(String args[]) { int[] a = null , b[] = null; b = a; System.out.println( b ); } } ``` The line ``` b = a; ``` is flagged by the compiler saying: ``` Incompatible types, found int[], required int [][] ``` Why is b considered two dimensional? I realize the "shortcut" declaration `int[] a = null , b[] = null;` is to blame, but why does it make the array two dimensional when only one set of brackets have been written? I find this syntax unclear and obfuscating.
Take this example: ``` int a, b; ``` Then both a and b are ints, right? So now take this: ``` int[] a, b; ``` The both a and b are int arrays. So by adding another set of brackets: ``` int[] a, b[]; ``` you **have** added another set of brackets to b. Either of these would be fine: ``` int[] a = null , b = null; int a[] = null , b[] = null; ``` or as you say, simply putting them on separate lines would work too (and be much easier to read).
``` int[] a = null , b[] =null; ``` .... it's equal to : ``` int[] a = null; int[][]b = null; ``` You have to do : ``` int[] a = null , b =null; ```
Why is this Java array considered two dimensional?
[ "", "java", "arrays", "" ]
Why aren't cookies able to be referenced from a servlet filter? It just seems beyond me that Java EE wouldn't allow you to sanitize cookie values: ``` public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException { request. } ``` ServletRequest does not support getCookies (as is the case with HttpServletRequest).
In order to get the cookies you need to cast it to an `HttpServletRequest`. ``` HttpServletRequest httpReq = (HttpServletRequest) request; ``` The reason that `ServletResponse` class doesn't support cookies is because the protocol isn't necessarly http in a `ServletRequest`, you can't be sure there are Cookies. Cookies are an Http thing.
Servlets aren't required to be accessed via the HTTP protocol. Therefore, your servlet does not have to be an HttpServlet - it may be a servlet that sends out specific documents via FTP, for example. Because of this, the basic properties of a servlet are encapsulated in the ServletRequest and ServletResponse interfaces, but if you know that your servlet is an HTTPServlet, you may downcast these to HttpServletRequest and HttpServletResponse respectively with no chance of a ClassCastException as long as your Servlet is truly an HttpServlet.
Java EE Filters not able to get cookies?
[ "", "java", "servlets", "cookies", "jakarta-ee", "servlet-filters", "" ]
I am tasked with writing unit tests for a suite of networked software written in python. Writing units for message builders and other static methods is very simple, but I've hit a wall when it comes to writing a tests for network looped threads. For example: The server it connects to could be on any port, and I want to be able to test the ability to connect to numerous ports (in sequence, not parallel) without actually having to run numerous servers. What is a good way to approach this? Perhaps make server construction and destruction part of the test? Something tells me there must a simpler answer that evades me. I have to imagine there are methods for unit testing networked threads, but I can't seem to find any.
I would try to introduce a factory into your existing code that purports to create socket objects. Then in a test pass in a mock factory which creates mock sockets which just pretend they've connected to a server (or not for error cases, which you also want to test, don't you?) and log the message traffic to prove that your code has used the right ports to connect to the right types of servers. Try not to use threads just yet, to simplify testing.
It depends on how your network software is layered and how detailed you want your tests to be, but it's certainly feasible in some scenarios to make server setup and tear-down part of the test. For example, when I was working on the Python logging package (before it became part of Python), I had a test (I didn't use `pyunit`/`unittest` - it was just an ad-hoc script) which fired up (in one test) four servers to listen on TCP, UDP, HTTP and HTTP/SOAP ports, and then sent network traffic to them. If you're interested, the distribution is [here](http://www.red-dove.com/logging-0.4.9.6.tar.gz) and the relevant test script in the archive to look at is `log_test.py`. The Python logging package has of course come some way since then, but the old package is still around for use with versions of Python < 2.3 and >= 1.5.2.
using pyunit on a network thread
[ "", "python", "unit-testing", "networking", "python-unittest", "" ]