Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
In a program I'm reading in some data files, part of which are formatted as a series of records each in square brackets. Each record contains a section title and a series of key/value pairs. I originally wrote code to loop through and extract the values, but decided it could be done more elegantly using regular expressions. Below is my resulting code (I just hacked it out for now in a console app - so know the variable names aren't that great, etc. Can you suggest improvements? I feel it shouldn't be necessary to do two matches and a substring, but can't figure out how to do it all in one big step: ``` string input = "[section1 key1=value1 key2=value2][section2 key1=value1 key2=value2 key3=value3][section3 key1=value1]"; MatchCollection matches=Regex.Matches(input, @"\[[^\]]*\]"); foreach (Match match in matches) { string subinput = match.Value; int firstSpace = subinput.IndexOf(' '); string section = subinput.Substring(1, firstSpace-1); Console.WriteLine(section); MatchCollection newMatches = Regex.Matches(subinput.Substring(firstSpace + 1), @"\s*(\w+)\s*=\s*(\w+)\s*"); foreach (Match newMatch in newMatches) { Console.WriteLine("{0}={1}", newMatch.Groups[1].Value, newMatch.Groups[2].Value); } } ```
I prefer named captures, nice formatting, and clarity: ``` string input = "[section1 key1=value1 key2=value2][section2 key1=value1 key2=value2 key3=value3][section3 key1=value1]"; MatchCollection matches = Regex.Matches(input, @"\[ (?<sectionName>\S+) (\s+ (?<key>[^=]+) = (?<value>[^ \] ]+) )+ ]", RegexOptions.IgnorePatternWhitespace); foreach(Match currentMatch in matches) { Console.WriteLine("Section: {0}", currentMatch.Groups["sectionName"].Value); CaptureCollection keys = currentMatch.Groups["key"].Captures; CaptureCollection values = currentMatch.Groups["value"].Captures; for(int i = 0; i < keys.Count; i++) { Console.WriteLine("{0}={1}", keys[i].Value, values[i].Value); } } ```
You should take advantage of the collections to get each key. So something like this then: ``` string input = "[section1 key1=value1 key2=value2][section2 key1=value1 key2=value2 key3=value3][section3 key1=value1]"; Regex r = new Regex(@"(\[(\S+) (\s*\w+\s*=\s*\w+\s*)*\])", RegexOptions.Compiled); foreach (Match m in r.Matches(input)) { Console.WriteLine(m.Groups[2].Value); foreach (Capture c in m.Groups[3].Captures) { Console.WriteLine(c.Value); } } ``` Resulting output: ``` section1 key1=value1 key2=value2 section2 key1=value1 key2=value2 key3=value3 section3 key1=value1 ```
Can you improve this C# regular expression code?
[ "", "c#", "regex", "" ]
Is it possible to call the member function of another controller in zend framework, if yes then how? ``` <?php class FirstController extends Zend_Controller_Action { public function indexAction() { // general action } public function memberFunction() { // a resuable function } } ``` Here's another controller ``` <?php class SecondController extends Zend_Controller_Action { public indexAction() { // here i need to call memberFunction() of FirstController } } ``` Please explain how i can access memberFunction() from second controller. # Solution Better idea is to define a AppController and make all usual controllers to extend AppController which further extends Zend\_Controller\_Action. ``` class AppController extends Zend_Controller_Action { public function memberFunction() { // a resuable function } } class FirstController extends AppController { public function indexAction() { // call function from any child class $this->memberFunction(); } } ``` Now `memberFunction` can be invoked from controllers extending `AppController` as a rule of simple inheritance.
Controllers aren't designed to be used in that way. If you want to execute an *action* of the other controller *after* your current controller, use the `_forward()` method: ``` // Invokes SecondController::otherActionAction() after the current action has been finished. $this->_forward('other-action', 'second'); ``` Note that this only works for *action methods* (“memberAction”), not arbitrary member functions! If `SecondController::memberFunction()` does something that is needed across multiple controllers, put that code in a action helper or library class, so that both controllers can access the shared functionality without having to depend on each other.
You should consider factoring out the code into either an action helper or to your model so that it can be called from both controllers that need it. Regards, Rob...
Calling member function of other controller in zend framework?
[ "", "php", "zend-framework", "" ]
I have a stored procedure that alters user data in a certain way. I pass it user\_id and it does it's thing. I want to run a query on a table and then for each user\_id I find run the stored procedure once on that user\_id How would I write query for this?
use a cursor ADDENDUM: [MS SQL cursor example] ``` declare @field1 int declare @field2 int declare cur CURSOR LOCAL for select field1, field2 from sometable where someotherfield is null open cur fetch next from cur into @field1, @field2 while @@FETCH_STATUS = 0 BEGIN --execute your sproc on each row exec uspYourSproc @field1, @field2 fetch next from cur into @field1, @field2 END close cur deallocate cur ``` in MS SQL, [here's an example article](http://www.sqlteam.com/article/cursors-an-overview) note that cursors are slower than set-based operations, but faster than manual while-loops; more details [in this SO question](https://stackoverflow.com/questions/287445/why-do-people-hate-sql-cursors-so-much) ADDENDUM 2: if you will be processing more than just a few records, pull them into a temp table first and run the cursor over the temp table; this will prevent SQL from escalating into table-locks and speed up operation ADDENDUM 3: and of course, if you can inline whatever your stored procedure is doing to each user ID and run the whole thing as a single SQL update statement, that would be optimal
**try to change your method if you need to loop!** within the parent stored procedure, create a #temp table that contains the data that you need to process. Call the child stored procedure, the #temp table will be visible and you can process it, hopefully working with the entire set of data and without a cursor or loop. this really depends on what this child stored procedure is doing. If you are UPDATE-ing, you can "update from" joining in the #temp table and do all the work in one statement without a loop. The same can be done for INSERT and DELETEs. If you need to do multiple updates with IFs you can convert those to multiple `UPDATE FROM` with the #temp table and use CASE statements or WHERE conditions. When working in a database try to lose the mindset of looping, it is a real performance drain, will cause locking/blocking and slow down the processing. If you loop everywhere, your system will not scale very well, and will be very hard to speed up when users start complaining about slow refreshes. Post the content of this procedure you want call in a loop, and I'll bet 9 out of 10 times, you could write it to work on a set of rows.
How do I execute a stored procedure once for each row returned by query?
[ "", "sql", "sql-server", "stored-procedures", "" ]
Is there a way to output a call trace for a particular thread in java? I do not want a stack trace. I would like a sequence of calls on each object for tracing.
I think you might find this interesting. It is a java agent which adds entry and exit logging to methods, using the slf4j framework to actually log the output. Then it is a matter of configuring the logging framework to only print out that thread you are interested in. <http://www.slf4j.org/extensions.html#javaagent> (just to be explicit: 1) I wrote it, 2) it works for me :) )
There is [btrace](https://github.com/btraceio/btrace), that can be used for this kind of action.
Call trace in java
[ "", "java", "" ]
I have the following set of dates (dd/MM/yyyy) matching events in my database: ``` eventId startDate endDate 1 02/05/2009 10/05/2009 2 08/05/2009 12/05/2009 3 10/05/2009 12/05/2009 4 21/05/2009 21/05/2009 5 25/05/2009 NULL 6 01/06/2009 03/06/2009 ``` The events have a start and end date (times don't matter) and a NULL endDate means that the event is still in progress. What I would like to determine is the ranges of dates between two arbitrary dates where there was a) no event and b) the events were overlapping. So for an input date range of 01/04/2009 - 30/06/2009 I would expect to have the following results: ``` no event: 01/04/2009 - 01/05/2009 overlap : 08/05/2009 - 10/05/2009 overlap : 10/05/2009 - 12/05/2009 no event: 13/05/2009 - 20/05/2009 no event: 22/05/2009 - 24/05/2009 overlap : 01/06/2009 - 03/06/2009 ``` Note that the two adjacent overlap ranges would be acceptable as one result. Can anyone please help me with a SQL algorithm to generate this result set? EDIT: The target platform database is SQL Server 2005. The dates are recorded as 10/05/2009 00:00:00, meaning that the event ended some time between 10/5/2009 00:00:00 and 10/5/2009 23:59:59. The same is true for the start dates. The input date range therefore also can be read as 01/04/2009 00:00:00 - 30/06/2009 23:59:59.
It's a little variation of the function to flatten intersecting timespans in `SQL Server`: * [**Flattening timespans: SQL Server**](http://explainextended.com/2009/06/11/flattening-timespans-sql-server/) It's one of the rare cases when cursor-based approach in `SQL Server` is faster the a set-based one: --- ``` CREATE FUNCTION mytable(@p_from DATETIME, @p_till DATETIME) RETURNS @t TABLE ( q_type VARCHAR(20) NOT NULL, q_start DATETIME NOT NULL, q_end DATETIME NOT NULL ) AS BEGIN DECLARE @qs DATETIME DECLARE @qe DATETIME DECLARE @ms DATETIME DECLARE @me DATETIME DECLARE cr_span CURSOR FAST_FORWARD FOR SELECT startDate, endDate FROM mytable WHERE startDate BETWEEN @p_from AND @p_till ORDER BY startDate OPEN cr_span FETCH NEXT FROM cr_span INTO @qs, @qe SET @ms = @qs SET @me = @qe WHILE @@FETCH_STATUS = 0 BEGIN FETCH NEXT FROM cr_span INTO @qs, @qe IF @qs > @me BEGIN INSERT INTO @t VALUES ('overlap', @ms, @me) INSERT INTO @t VALUES ('gap', @me, @qs) SET @ms = @qs END SET @me = CASE WHEN @qe > @me THEN @qe ELSE @me END END IF @ms IS NOT NULL BEGIN INSERT INTO @t VALUES (@ms, @me) END CLOSE cr_span RETURN END GO ``` This function compresses each contiguous set of intersecting ranges into one range, and returns both the range and the following gap.
Without really understanding what problem you're trying to solve, here's my solution to *some* problem off the top of my head: 1. Create table function (UDF) "all-dates" that would return all dates in a year. 2. Convert your events to separate dates (one event row would become as many rows as there are days in it) by inner-joining events to the all-dates `where the date is between event's start and end dates`... Retain original eventId. 3. Do an outer join of event-dates with all-dates (again) to find the gaps or misses. 4. Join event-dates with themselves on `where dates are same but eventId is not` to find overlaps.
Calculate missing date ranges and overlapping date ranges between two dates
[ "", "sql", "sql-server", "algorithm", "t-sql", "" ]
I am looking for an efficient way to create a file whose size is unknown but can range from mb's to gb's and fill its content randomly. I may write first 200 bytes than jump to the end and write last 200 bytes and move to the middle and write there. Is `RandomAccessFile` efficient for doing this or are there any alternatives better suited for this kind of job?
Yes, use `RandomAccessFile` - that's what it's there for. You *could* potentially use a `FileChannel`, but I'd go for `RandomAccessFile` first - it's likely to be simpler. Note that you won't be able to "insert in the middle" of the file after writing the end part: I don't know any file system which supports that. You'll need to know the complete size before you write the final section, basically. An alternative would be to write sequentially, remembering the final bit until the end. If you can give us more information about what you need to do (and when you have information about the size) we may be able to help you more. EDIT: To create the file with a specific size,you can `seek()` past the end and then write data: ``` import java.io.*; public class Test { // Just for the sake of a simple test program! public static void main(String[] args) throws Exception { RandomAccessFile file = new RandomAccessFile("file.dat", "rw"); file.seek(100); file.write(0); file.close(); } } ``` After this has exited, `file.dat` will be 101 bytes long. (Note that normally you'd use try/finally etc.) EDIT: As coobird mentioned in the comments, `setLength()` will also extend the file - but it will also truncate the file if you give a length less than the current size. Given your comment about basically writing torrent data, I suspect that seeking and then writing is exactly the behaviour you want. When you receive a chunk, just seek to the right spot, write it out, and the file will extend itself when it needs to.
RandomAccessFile should do it
Java access to big file
[ "", "java", "file", "file-io", "random-access", "" ]
I was just wondering if there is a way to find out where a java program will be searching for files. I am trying to load a settings file with `FileInputStream fstream = new FileInputStream("ldaplookup.ini");` but it is throwing a File not found error. The ini file is in the same folder as the class file but i am assuming it is searching somewhere else. Thanks, -Pete
FileInputStream looks up the file relative to the path of execution. If the resource file is in the same folder as the class, you can try using: ``` InputStream stream = this.getClass().getResourceAsStream("ldaplookup.ini"); ```
Java loads files from the current working directory for a relative path. If you want to see what is, try this: ``` System.out.println(System.getProperty("user.dir")); ```
Find where Java loads files from?
[ "", "java", "" ]
I've been looking at a Qt [tutorial](http://doc.trolltech.com/4.3/tutorial-t14.html) which uses a construction I haven't seen before: ``` (void) new QShortcut(Qt::Key_Enter, this, SLOT(fire())); (void) new QShortcut(Qt::Key_Return, this, SLOT(fire())); (void) new QShortcut(Qt::CTRL + Qt::Key_Q, this, SLOT(close())); ``` I've tried this without the `(void)` and it still compiles and works, so what is the purpose of the `(void)`?
Casting an expression to (void) basically tells the compiler to ignore the result of that expression (after computing it). In your example, each of the expressions (per statement/line) is dynamically allocating memory via the new operator - and since new returns a pointer (address) to the memory, the usual practice is to store that pointer in a variable that you can use to eventually delete the object and deallocate the memory. In your example, since the pointer is being discarded, an explicit cast to (void) makes the intention of the programmer clear: "I know exactly what I am doing - please discard the value returned by new" If you are interested in the technicalities (quoting from the C++ standard, clause 5): > Any expression can be explicitly converted to type cv void. The expression value is discarded. [ Note: however, if the value is in a temporary variable (12.2), the destructor for that variable is not executed until the usual time, and the value of the variable is preserved for the purpose of executing the destructor. —end note ] > The lvalue-to-rvalue (4.1), array-to-pointer (4.2), and function-to-pointer (4.3) standard conversions are not applied to the expression. And if you are wondering how those objects are getting deleted (if indeed they are getting deleted), the answer is that the 'this' pointer within the constructor of QShortcut should have the same value as that returned by new, and that can be passed to a ShortcutManager. Note, the 'this' within the constructor is not the same as the 'this' pointer that is being passed to the constructor of QShortcut.
Some C++ compilers will give a warning if you throw away the return value of a function like that. In this case, the code looks like it leaks memory, so you get a warning. The `(void)` tells the compiler not to emit the warning: "Treat this function as though it returned `void`".
What does "(void) new" mean in C++?
[ "", "c++", "void", "" ]
Does anyone know how can I get next week date based on this week date? example if I have this thursday date (25/6/2009) how can I use javascript to get next thursday date (2/7/2009)?
``` var firstDay = new Date("2009/06/25"); var nextWeek = new Date(firstDay.getTime() + 7 * 24 * 60 * 60 * 1000); ``` You can also look at [DateJS](https://github.com/datejs/Datejs) if you like "fluent" APIs.
``` function nextweek(){ var today = new Date(); var nextweek = new Date(today.getFullYear(), today.getMonth(), today.getDate()+7); return nextweek; } ```
how to get next week date in javascript
[ "", "javascript", "" ]
Could someone please give an example of how to use ling to query over a long string of text and find a substring within that string? regards
I wouldn't use LINQ, I would use [`String.Substring`](http://en.wikipedia.org/wiki/Fail-fast), [`String.IndexOf`](http://msdn.microsoft.com/en-us/library/system.string.indexof.aspx), or a [regular expression](http://msdn.microsoft.com/en-us/library/system.text.regularexpressions.regex.aspx). Can you post an example of the string you would like to search and an example of a substring you would like to find within that string?
``` static void Main(string[] args) { var found = "Where in the world is Carmen Sandiego".Split(' ').Where(part => part.StartsWith("i")); foreach (var part in found) Console.WriteLine(part); } ```
linq over strings C#
[ "", "c#", "linq", "string", "" ]
I am generating a List<T> with a runtime-determined type parameter. I'd like to invoke the ForEach method to iterate over the items in the list: ``` //Get the type of the list elements Type elementType = GetListElementType(finfo); Type listType = Type.GetType("System.Collections.Generic.List`1[" + elementType.FullName + "], mscorlib", true); //Get the list var list = getList.Invoke(null, new Object[] { finfo.GetValue(myObject) }); MethodInfo listForEach = listType.GetMethod("ForEach"); //How do I do this? Specifically, what takes the place of 'x'? listForEach.Invoke(list, new object[] { delegate ( x element ) { //operate on x using reflection } }); ``` Given a MethodInfo corresponding to the ForEach method contained in my runtime-generated list type, what's the proper way to invoke it using an anonymous method? The above is my first stab, but don't know how to declare the type of the anonymous method's parameter.
You can do this: ``` var someGenericListYouCreated = ...; var enumerable = someGenericListYouCreated as IEnumerable; foreach(var foo in enumerable){ ... } ``` However, I'm working on way to do what you ACTUALLY want. Edit: Right, I hope this makes sense ``` private class Adapter<T> { private readonly Action<object> act; public Adapter(Action<object> act){ this.act = act; } public void Do(T o) { act(o); } } public static void Main(string[] args) { Type elementType = typeof(string); var genericType = typeof(List<>).MakeGenericType(elementType); var list = Activator.CreateInstance(genericType); var addMethod = list.GetType().GetMethod("Add"); addMethod.Invoke(list, new object[] { "foo" }); addMethod.Invoke(list, new object[] { "bar" }); addMethod.Invoke(list, new object[] { "what" }); Action<object> printDelegate = o => Console.WriteLine(o); var adapter = Activator.CreateInstance(typeof(Adapter<>).MakeGenericType(elementType), printDelegate); var adapterDo = adapter.GetType().GetMethod("Do"); var adapterDelegate = Delegate.CreateDelegate(typeof(Action<string>), adapter, adapterDo); var foreachMethod = list.GetType().GetMethod("ForEach"); foreachMethod.Invoke(list, new object[] { adapterDelegate }); } ``` What this does: 1. Create a generic list (notice that it's using typeof(List<>) 2. Add some strings to this list 3. Create a new delegate, in this case an Action 4. Create an instance of the adapter class 5. Create a delegate of the type we need (Action) on the adapter class 6. Call ForEach Note, you don't necessarily have to use Action if you know the type you're going to be processing. You could very easily use an Action and it'll work...
There are a number of issues here. First, getting the type object of the type with the generic parameter by constructing the name of the type with string concatenation is a bit dodgy. You should do this instead: ``` Type genericType = typeof(List<>).MakeGenericType(new Type[] { listType }); ``` This is a lot cleaner. Now, to invoke the ForEach method of an instance of this type, you will need an `Action<T>` object. It's not entirely obvious for me if you want to use a lambda expression or a function pointer, but the point is that you pass the instance of `Action<T>` just like a normal parameter: ``` methodInfo.Invoke(list, new object[] { x }); ``` If you could clarify the origin of x (that is, the `Action<T>` parameter) maybe we could give more help.
C#: Invoking ForEach on a runtime-generated List<T>
[ "", "c#", "generics", "" ]
I am attempting to use a Microsoft.SqlServer.Management.Smo.Restore object to restore a SQL Server 2000 database. Just before I begin the restore operation, I change the text of a label so that the user knows what is going on. However, the changed text isn't visible on the GUI (i.e., the text remains the same as it was) until AFTER the fullRestore.Wait() line. ``` lblStatus.Text = "Restoring Database"; Restore fullRestore = new Restore(); // Configure fullRestore fullRestore.SqlRestore(_server); fullRestore.Wait(); ``` The weird thing is, lblStatus eventually does display "Restoring Database", but not until *after* the restore is complete. Any ideas?
You're blocking on the GUI thread, which is preventing it from updating. You can call lblStatus.Refresh(), or move your Wait to a background thread (which is ultimately the right thing to do).
It's a threading issue. You can do this on seperate threads or on a background thread. One approach I've seen people use is do a Application.DoEvents() although I typically stay away from that call.
Label.Text change being blocked?
[ "", "c#", ".net", "sql-server-2000", "label", "database-restore", "" ]
I'm working on an online store in Django (just a basic shopping cart right now), and I'm planning to add functionality for users to mark items as favorite (just like in stackoverflow). Models for the cart look something like this: ``` class Cart(models.Model): user = models.OneToOneField(User) class CartItem(models.Model): cart = models.ForeignKey(Cart) product = models.ForeignKey(Product, verbose_name="produs") ``` The favorites model would be just a table with two rows: user and product. The problem is that this would only work for registered users, as I need a user object. How can I also let unregistered users use these features, saving the data in cookies/sessions, and when and if they decides to register, moving the data to their user? I guess one option would be some kind of generic relations, but I think that's a little to complicated. Maybe having an extra row after *user* that's a session object (I haven't really used sessions in django until now), and if the User is set to None, use that? So basically, what I want to ask, is if you've had this problem before, how did you solve it, what would be the best approach?
I haven't done this before but from reading your description I would simply create a user object when someone needs to do something that requires it. You then send the user a cookie which links to this user object, so if someone comes back (without clearing their cookies) they get the same skeleton user object. This means that you can use your current code with minimal changes and when they want to migrate to a full registered user you can just populate the skeleton user object with their details. If you wanted to keep your DB tidy-ish you could add a task that deletes all skeleton Users that haven't been used in say the last 30 days.
Seems to me that the easiest way to do this would be to store both the user id or the session id: ``` class Cart(models.Model): user = models.ForeignKey(User, null=True) session = models.CharField(max_length=32, null=True) ``` Then, when a user registers, you can take their `request.session.session_key` and update all rows with their new user id. Better yet, you could define a "`UserProxy`" model: ``` class Cart(models.Model): user = models.ForeignKey(UserProxy) class UserProxy(models.Model): user = models.ForeignKey(User, unique=True, null=True) session = models.CharField(max_length=32, null=True) ``` So then you just have to update the UserProxy table when they register, and nothing about the cart has to change.
Giving anonymous users the same functionality as registered ones
[ "", "python", "django", "session", "" ]
What is the most efficient way to monitor a queue. The follwoing piece of code is the biggest hog of resources : ``` /// <summary> /// Starts the service. /// </summary> private void StartService() { while (true) { //the check on count is not thread safe while (_MessageQueue.Count > 0) { Common.IMessage message; // the call to GetMessageFromQueue is thread safe if (_MessageQueue.GetMessageFromQueue(out message) == true) { if (message.RoutingInfo == Devices.Common.MessageRoutingInfo.ToDevice) { _Port.SerialPort.WriteLine(message.Message); } if (message.RoutingInfo == Devices.Common.MessageRoutingInfo.FromDevice) { OnDeviceMessageReceived(new Common.DeviceMessageArgs(message.Message)); } } } } } ``` Start Service runs on background thread , the call to \_MessageQueue.Count is not thread safe , I am not locking on count in MessageQueue . I do however lock on the implementation of \_MessageQueue.GetMessageFromQueue . Is the way I have gone about this efficient? Should I rather raise an event Every time the queue goes from a Count of 0 to greater than zero ?
You should probably include some type of thread sleep into that method, otherwise its going to be using 100% CPU. Alternatively, you could create a wait handle, and set it when you add a message to the queue.
If I haven't missed anything - you're doing a busy wait on the \_messageQueue.Count property. I would try doing something like is done at: <http://msdn.microsoft.com/en-us/library/yy12yx1f.aspx>
Most efficient way to monitor a queue
[ "", "c#", ".net", "performance", "" ]
I have a table in HTML which I am generating from XML/XSL and I want it to suppress repeating values. However, I also want to sort it on the fly by clicking the titles. Without a round trip to the server I need to suppress different values after each sort. Is there a good javascript/css solution. For example **Data** ``` Date Person Score May Jeff 1 May Joel 2 June Alex 1 ``` **Initial Display** *Note lack of second May* ``` Date Person Score May Jeff 1 Joel 2 June Alex 1 ``` **Display After sorting by Score** *Note lack of second 1* ``` Date Person Score May Joel 2 June Alex 1 May Jeff ```
Personally I would use something like [jQuery Table Sorter](http://tablesorter.com/docs/). You can use the unique() function to remove duplicates as well. Using jQuery just makes doing things a lot easier than using JS. Either that or I would use JSF for my presentation layer, which already comes with functionality for just such occasions. I don't really know of a "good" way to do it with JS. Every implementation in JS that I have ever seen is messy. Adding jQuery to you project will save you from having to write nasty JS code.
Have a javascript function loop through the relevant table columns and remove the values that where the same as the ones before. You might also want to add a rowspan attribute to the first cell with that value so that the table' semantics are correct. This isn't really a job for CSS as it's processing the information and not just displaying things (plus it'd be really hard).
How to suppress the display of repeating values in html tables which can be sorted?
[ "", "javascript", "html", "css", "sorting", "html-table", "" ]
I'm using Java's SSLSocket to secure communications between a client and a server program. The server program also serves up HTTPS requests from web browsers. According to "[Beginning Cryptography with Java](http://www.wrox.com/WileyCDA/WroxTitle/productCd-0764596330.html)", page 371, you should always call `setEnabledCipherSuites` on your `SSLSocket` / `SSLServerSocket` to ensure that the cipher suite that ends up being negotiated is sufficiently strong for your purposes. That being said, a call to my `SSLSocketFactory`'s `getDefaultCipherSuites` method yields some *180* options. These options range from `TLS_RSA_WITH_AES_256_CBC_SHA` (which I think is fairly secure) to `SSL_RSA_WITH_RC4_128_MD5` (not so sure if that's secure, given MD5's current status) to `SSL_DHE_DSS_EXPORT_WITH_DES40_CBC_SHA` (not entirely sure what that does). **What's a sensible list of cipher suites to restrict the sockets to?** Note that the client and server have access to the [Bouncy Castle](http://www.bouncycastle.org/) service provider, and that they may or may not have unlimited cryptographic policy files installed.
Don't use anything with export in it. That's crippleware due to export restrictions on strong cryptography. EDIT: Changed to use 2009 document. A 2009 NIST [recommendation](http://csrc.nist.gov/publications/nistpubs/800-57/sp800-57_PART3_key-management_Dec2009.pdf) lists the following, incluing TLS\_RSA\_WITH\_AES\_256\_CBC\_SHA (which you mentioned): TLS\_RSA\_WITH\_NULL\_SHA (don't use this unless you're sure you don't need any privacy/confidentiality). ``` TLS_RSA_WITH_3DES_EDE_CBC_SHA TLS_RSA_WITH_AES_128_CBC_SHA TLS_RSA_WITH_AES_256_CBC_SHA TLS_DH_DSS_WITH_3DES_EDE_CBC_SHA TLS_DH_RSA_WITH_3DES_EDE_CBC_SHA TLS_DHE_DSS_WITH_3DES_EDE_CBC_SHA TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA TLS_DH_DSS_WITH_AES_128_CBC_SHA TLS_DH_RSA_WITH_AES_128_CBC_SHA TLS_DHE_DSS_WITH_AES_128_CBC_SHA TLS_DHE_RSA_WITH_AES_128_CBC_SHA TLS_DH_DSS_WITH_AES_256_CBC_SHA TLS_DH_RSA_WITH_AES_256_CBC_SHA TLS_DHE_DSS_WITH_AES_256_CBC_SHA TLS_DHE_RSA_WITH_AES_256_CBC_SHA TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA TLS_ECDH_RSA_WITH_AES_128_CBC_SHA TLS_ECDH_RSA_WITH_AES_256_CBC_SHA TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA TLS_PSK_WITH_3DES_EDE_CBC_SHA TLS_PSK_WITH_AES_128_CBC_SHA TLS_PSK_WITH_AES_256_CBC_SHA TLS_DHE_PSK_WITH_3DES_EDE_CBC_SHA TLS_DHE_PSK_WITH_AES_128_CBC_SHA TLS_DHE_PSK_WITH_AES_256_CBC_SHA TLS_RSA_PSK_WITH_3DES_EDE_CBC_SHA TLS_RSA_PSK_WITH_AES_128_CBC_SHA TLS_RSA_PSK_WITH_AES_256_CBC_SHA TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384 TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256 TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384 ```
Below is the Java class I use to enforce cipher suites and protocols. Prior to `SSLSocketFactoryEx`, I was modifying properties on the `SSLSocket` when I had access to them. The Java folks on Stack Overflow helped with it, so its nice to be able to post it here. `SSLSocketFactoryEx` prefers stronger cipher suites (like `ECDHE` and `DHE`), and it omits weak and wounded cipher suites (like `RC4` and `MD5`). It does have to enable four RSA key transport ciphers for interop with Google and Microsoft when TLS 1.2 is *not* available. They are `TLS_RSA_WITH_AES_256_CBC_SHA256`, `TLS_RSA_WITH_AES_256_CBC_SHA` and two friends. If possible, you should remove the `TLS_RSA_*` key transport schemes. Keep the cipher suite list as small as possible. If you advertise *all* available ciphers (similar to Flaschen's list), then your list will be 80+. That takes up 160 bytes in the `ClientHello`, and it can cause some appliances to fail because they have a small, fixed-size buffer for processing the `ClientHello`. Broken appliances include F5 and Ironport. In practice, the list in the code below is paired down to 10 or 15 cipher suites once the preferred list intersects with Java's supported cipher suites. For example, here's the list I get when preparing to connect or microsoft.com or google.com with an unlimited JCE policy in place: * TLS\_ECDHE\_ECDSA\_WITH\_AES\_256\_CBC\_SHA384 * TLS\_ECDHE\_RSA\_WITH\_AES\_256\_CBC\_SHA384 * TLS\_ECDHE\_ECDSA\_WITH\_AES\_128\_CBC\_SHA256 * TLS\_ECDHE\_RSA\_WITH\_AES\_128\_CBC\_SHA256 * TLS\_ECDHE\_RSA\_WITH\_AES\_256\_GCM\_SHA384 * TLS\_DHE\_DSS\_WITH\_AES\_256\_GCM\_SHA384 * TLS\_ECDHE\_RSA\_WITH\_AES\_128\_GCM\_SHA256 * TLS\_DHE\_DSS\_WITH\_AES\_128\_GCM\_SHA256 * TLS\_DHE\_DSS\_WITH\_AES\_256\_CBC\_SHA256 * TLS\_DHE\_RSA\_WITH\_AES\_128\_CBC\_SHA * TLS\_DHE\_DSS\_WITH\_AES\_128\_CBC\_SHA * TLS\_RSA\_WITH\_AES\_256\_CBC\_SHA256 * TLS\_RSA\_WITH\_AES\_256\_CBC\_SHA * TLS\_RSA\_WITH\_AES\_128\_CBC\_SHA256 * TLS\_RSA\_WITH\_AES\_128\_CBC\_SHA The list omits weak/wounded algorithms, like RC4 and MD5. If they are enabled, then you will likely get a [Obsolete cryptography warning from Browser](https://stackoverflow.com/q/30270788) on occasion. The list will be smaller with the default JCE policy because the policy removes AES-256 and some others. I think its about 7 cipher suites with the restricted policy. The `SSLSocketFactoryEx` class also ensures protocols TLS 1.0 and above are used. Java clients prior to Java 8 disable TLS 1.1 and 1.2. `SSLContext.getInstance("TLS")` will also sneak in `SSLv3` (even in Java 8), so steps have to be taken to remove it. Finally, the class below is TLS 1.3 aware, so it should work when the provider makes them available. The `*_CHACHA20_POLY1305` cipher suites are preferred if available because they are so much faster than some of the current suites and they have better security properties. Google has already rolled it out on its servers. I'm not sure when Oracle will provide them. OpenSSL will provide them with OpenSSL 1.0.2 [1.1.0](https://mta.openssl.org/pipermail/openssl-users/2015-March/000866.html). You can use it like so: ``` URL url = new URL("https://www.google.com:443"); HttpsURLConnection connection = (HttpsURLConnection) url.openConnection(); SSLSocketFactoryEx factory = new SSLSocketFactoryEx(); connection.setSSLSocketFactory(factory); connection.setRequestProperty("charset", "utf-8"); InputStream input = connection.getInputStream(); InputStreamReader reader = new InputStreamReader(input, "utf-8"); BufferedReader buffer = new BufferedReader(reader); ... ``` --- ``` class SSLSocketFactoryEx extends SSLSocketFactory { public SSLSocketFactoryEx() throws NoSuchAlgorithmException, KeyManagementException { initSSLSocketFactoryEx(null,null,null); } public SSLSocketFactoryEx(KeyManager[] km, TrustManager[] tm, SecureRandom random) throws NoSuchAlgorithmException, KeyManagementException { initSSLSocketFactoryEx(km, tm, random); } public SSLSocketFactoryEx(SSLContext ctx) throws NoSuchAlgorithmException, KeyManagementException { initSSLSocketFactoryEx(ctx); } public String[] getDefaultCipherSuites() { return m_ciphers; } public String[] getSupportedCipherSuites() { return m_ciphers; } public String[] getDefaultProtocols() { return m_protocols; } public String[] getSupportedProtocols() { return m_protocols; } public Socket createSocket(Socket s, String host, int port, boolean autoClose) throws IOException { SSLSocketFactory factory = m_ctx.getSocketFactory(); SSLSocket ss = (SSLSocket)factory.createSocket(s, host, port, autoClose); ss.setEnabledProtocols(m_protocols); ss.setEnabledCipherSuites(m_ciphers); return ss; } public Socket createSocket(InetAddress address, int port, InetAddress localAddress, int localPort) throws IOException { SSLSocketFactory factory = m_ctx.getSocketFactory(); SSLSocket ss = (SSLSocket)factory.createSocket(address, port, localAddress, localPort); ss.setEnabledProtocols(m_protocols); ss.setEnabledCipherSuites(m_ciphers); return ss; } public Socket createSocket(String host, int port, InetAddress localHost, int localPort) throws IOException { SSLSocketFactory factory = m_ctx.getSocketFactory(); SSLSocket ss = (SSLSocket)factory.createSocket(host, port, localHost, localPort); ss.setEnabledProtocols(m_protocols); ss.setEnabledCipherSuites(m_ciphers); return ss; } public Socket createSocket(InetAddress host, int port) throws IOException { SSLSocketFactory factory = m_ctx.getSocketFactory(); SSLSocket ss = (SSLSocket)factory.createSocket(host, port); ss.setEnabledProtocols(m_protocols); ss.setEnabledCipherSuites(m_ciphers); return ss; } public Socket createSocket(String host, int port) throws IOException { SSLSocketFactory factory = m_ctx.getSocketFactory(); SSLSocket ss = (SSLSocket)factory.createSocket(host, port); ss.setEnabledProtocols(m_protocols); ss.setEnabledCipherSuites(m_ciphers); return ss; } private void initSSLSocketFactoryEx(KeyManager[] km, TrustManager[] tm, SecureRandom random) throws NoSuchAlgorithmException, KeyManagementException { m_ctx = SSLContext.getInstance("TLS"); m_ctx.init(km, tm, random); m_protocols = GetProtocolList(); m_ciphers = GetCipherList(); } private void initSSLSocketFactoryEx(SSLContext ctx) throws NoSuchAlgorithmException, KeyManagementException { m_ctx = ctx; m_protocols = GetProtocolList(); m_ciphers = GetCipherList(); } protected String[] GetProtocolList() { String[] preferredProtocols = { "TLSv1", "TLSv1.1", "TLSv1.2", "TLSv1.3" }; String[] availableProtocols = null; SSLSocket socket = null; try { SSLSocketFactory factory = m_ctx.getSocketFactory(); socket = (SSLSocket)factory.createSocket(); availableProtocols = socket.getSupportedProtocols(); Arrays.sort(availableProtocols); } catch(Exception e) { return new String[]{ "TLSv1" }; } finally { if(socket != null) socket.close(); } List<String> aa = new ArrayList<String>(); for(int i = 0; i < preferredProtocols.length; i++) { int idx = Arrays.binarySearch(availableProtocols, preferredProtocols[i]); if(idx >= 0) aa.add(preferredProtocols[i]); } return aa.toArray(new String[0]); } protected String[] GetCipherList() { String[] preferredCiphers = { // *_CHACHA20_POLY1305 are 3x to 4x faster than existing cipher suites. // http://googleonlinesecurity.blogspot.com/2014/04/speeding-up-and-strengthening-https.html // Use them if available. Normative names can be found at (TLS spec depends on IPSec spec): // http://tools.ietf.org/html/draft-nir-ipsecme-chacha20-poly1305-01 // http://tools.ietf.org/html/draft-mavrogiannopoulos-chacha-tls-02 "TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305", "TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305", "TLS_ECDHE_ECDSA_WITH_CHACHA20_SHA", "TLS_ECDHE_RSA_WITH_CHACHA20_SHA", "TLS_DHE_RSA_WITH_CHACHA20_POLY1305", "TLS_RSA_WITH_CHACHA20_POLY1305", "TLS_DHE_RSA_WITH_CHACHA20_SHA", "TLS_RSA_WITH_CHACHA20_SHA", // Done with bleeding edge, back to TLS v1.2 and below "TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384", "TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384", "TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256", "TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256", "TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384", "TLS_DHE_DSS_WITH_AES_256_GCM_SHA384", "TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256", "TLS_DHE_DSS_WITH_AES_128_GCM_SHA256", // TLS v1.0 (with some SSLv3 interop) "TLS_DHE_RSA_WITH_AES_256_CBC_SHA384", "TLS_DHE_DSS_WITH_AES_256_CBC_SHA256", "TLS_DHE_RSA_WITH_AES_128_CBC_SHA", "TLS_DHE_DSS_WITH_AES_128_CBC_SHA", "TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA", "TLS_DHE_DSS_WITH_3DES_EDE_CBC_SHA", "SSL_DH_RSA_WITH_3DES_EDE_CBC_SHA", "SSL_DH_DSS_WITH_3DES_EDE_CBC_SHA", // RSA key transport sucks, but they are needed as a fallback. // For example, microsoft.com fails under all versions of TLS // if they are not included. If only TLS 1.0 is available at // the client, then google.com will fail too. TLS v1.3 is // trying to deprecate them, so it will be interesteng to see // what happens. "TLS_RSA_WITH_AES_256_CBC_SHA256", "TLS_RSA_WITH_AES_256_CBC_SHA", "TLS_RSA_WITH_AES_128_CBC_SHA256", "TLS_RSA_WITH_AES_128_CBC_SHA" }; String[] availableCiphers = null; try { SSLSocketFactory factory = m_ctx.getSocketFactory(); availableCiphers = factory.getSupportedCipherSuites(); Arrays.sort(availableCiphers); } catch(Exception e) { return new String[] { "TLS_DHE_DSS_WITH_AES_128_CBC_SHA", "TLS_DHE_DSS_WITH_AES_256_CBC_SHA", "TLS_DHE_RSA_WITH_AES_128_CBC_SHA", "TLS_DHE_RSA_WITH_AES_256_CBC_SHA", "TLS_RSA_WITH_AES_256_CBC_SHA256", "TLS_RSA_WITH_AES_256_CBC_SHA", "TLS_RSA_WITH_AES_128_CBC_SHA256", "TLS_RSA_WITH_AES_128_CBC_SHA", "TLS_EMPTY_RENEGOTIATION_INFO_SCSV" }; } List<String> aa = new ArrayList<String>(); for(int i = 0; i < preferredCiphers.length; i++) { int idx = Arrays.binarySearch(availableCiphers, preferredCiphers[i]); if(idx >= 0) aa.add(preferredCiphers[i]); } aa.add("TLS_EMPTY_RENEGOTIATION_INFO_SCSV"); return aa.toArray(new String[0]); } private SSLContext m_ctx; private String[] m_ciphers; private String[] m_protocols; } ```
Which Cipher Suites to enable for SSL Socket?
[ "", "java", "ssl", "encryption", "" ]
I am working on a large-scale checkout application for a current project. This checkout has many cases depending on the user's admin level, how they got to the checkout, and what type of item they are checking out, and so the process is abstracted away from the .aspx pages via a set of context classes. These classes all subclass from a single class, CheckoutContext, and the type of class to be used is noted via an enum. Is there something similar to typedef I can use to choose which subclass to use, or should I simply have a method that returns the relevant class, like so: ```` ``` CheckoutContext chooseSubclass(CheckoutCase c) { CheckoutContext output; switch (c): { case CheckoutCase.SingleItemNew: output = new SingleItemNew; break; case . . . return output; } } ``` ````
If there are a large number of cases, I would create a `Dictionary<CheckoutCase, Type>` and populate it one time with the set of all CheckoutCase values and corresponding CheckoutContext Types. Then you could use Activator.CreateInstance to return the appropriate type instead of a gigantic switch statement.
What you're implementing is a [Factory Pattern](http://en.wikipedia.org/wiki/Factory_pattern). This is a standard practice, though it typically means writing a lot of repetitive code (much like your switch statement, which is often how they're implemented). You could do all sorts of fancy things like dynamic instantiation via reflection, but don't play with fire. Just stick with switch statement and you'll be fine.
Best way to decide which subclass is needed
[ "", "c#", "enums", "subclassing", "" ]
I have a basic SQL query, starting with: ``` SELECT top 20 application_id, [name], location_id FROM apps ``` Now, I would like to finish it so that it does this (written in Pseudocode) ``` if @lid > 0 then WHERE location_id IN (@lid) else WHERE location_id is all values in location_id column ``` --- As requested, here is an example ``` application_id name location_id ---------------------------------------------------------- 1 Joe Blogs 33 2 Sam Smith 234 3 Jeremy Carr 33 ``` @locid is the results given by the user, for example '33, 234' If @lid is empty then I'd like it to output all rows for location\_id with name and application\_id. Otherwise, I'd like it to output all rows in relation to the provided numbers in @lid (standing for location\_id. So, if @lid is 0: ``` application_id name location_id ---------------------------------------------------------- 1 Joe Blogs 33 2 Sam Smith 234 3 Jeremy Carr 33 ``` Otherwise, if @lid contains '33' ``` application_id name location_id ---------------------------------------------------------- 1 Joe Blogs 33 3 Jeremy Carr 33 ```
Try using **Case**, which serves the purpose of an IIF or a ternary operator. Please check this link <http://msdn.microsoft.com/en-us/library/ms181765.aspx> cheers
If @locid is a list eg "33, 234" etc, then no solution here will work. However, I guess these were posted before your update with this information. I assume that because you said this: > @locid is the results given by the > user, for example '33, 234' You can not expand the variable directly so that `location_in IN (33, 234)`. You are actually asking for `location_id = '33, 234'`, which will fail with a CAST conversion, because of datatype precedence. You have to parse the list first into a table form for use in a JOIN/EXISTS construct. There are several options and Erland covers them all here: [Arrays and Lists in SQL Server 2005](http://www.sommarskog.se/arrays-in-sql-2005.html)
How do I use a comma separated list of values as a filter in T-SQL?
[ "", "sql", "sql-server", "t-sql", "" ]
I recently got tossed some C# code to make some minor cosmetic changes to. When I open up some of the files in Visual Studio though, I get errors saying: > To prevent possible data loss... The first of these errors is: > Object reference not set to an instance of an object. I can follow the stack trace fine, but I'm not sure what I really should be looking for in this situation. Also, the end of my stack trace has a call that ends in "PageScroller..ctor()". Based on a little Google research, I'm assuming that means call the constructor. Is that true?
You have a bug in design mode for some custom control, probably PageScroller, and apparently starting from the constructor. Perhaps there's some code in the constructor that returns null in design mode, and the null is not checked for.
I occasionally see problems like this. I started moving code from the constructor to the load event and that helped.
Using the Visual Studio designer - "Object reference not set to an instance of an object" (Visual Studio 2008)
[ "", "c#", "visual-studio", "visual-studio-2008", "" ]
I've used [ServiceWrapper](http://wrapper.tanukisoftware.org/doc/english/download.jsp) a few times in the past, however, the dual license is somewhat complex for commercial products (generally you have to pay them). Are there are fully FOSS alternatives with similar functionality?
[YAJSW](http://yajsw.sourceforge.net/) seems to be the best alternative, though I have not yet completed my evaluation.
Try [Apache Procrun](http://commons.apache.org/daemon/procrun.html). It's what Tomcat uses on Windows. There is also [Apache jsvc](http://commons.apache.org/daemon/jsvc.html) for Unix; they are both part of a parent project called [Apache Commons Daemon](http://commons.apache.org/daemon/index.html).
Alternative to servicewrapper for java?
[ "", "java", "windows-services", "service", "" ]
I'm writing a small tray application that needs to detect the last time a user interacted with their machine to determine if they're idle. Is there any way to retrieve the time a user last moved their mouse, hit a key or interacted in any way with their machine? I figure Windows obviously tracks this to determine when to display a screen saver or power down, etc, so I'm assuming there's a Windows API for retrieving this myself?
[GetLastInputInfo](http://msdn.microsoft.com/en-us/library/ms646302(VS.85).aspx). Documented at [PInvoke.net](http://www.pinvoke.net/default.aspx/user32.GetLastInputInfo).
include following namespaces ``` using System; using System.Runtime.InteropServices; ``` and then include following ``` internal struct LASTINPUTINFO { public uint cbSize; public uint dwTime; } /// <summary> /// Helps to find the idle time, (in milliseconds) spent since the last user input /// </summary> public class IdleTimeFinder { [DllImport("User32.dll")] private static extern bool GetLastInputInfo(ref LASTINPUTINFO plii); [DllImport("Kernel32.dll")] private static extern uint GetLastError(); public static uint GetIdleTime() { LASTINPUTINFO lastInPut = new LASTINPUTINFO(); lastInPut.cbSize = (uint)System.Runtime.InteropServices.Marshal.SizeOf(lastInPut); GetLastInputInfo(ref lastInPut); return ((uint)Environment.TickCount - lastInPut.dwTime); } /// <summary> /// Get the Last input time in milliseconds /// </summary> /// <returns></returns> public static long GetLastInputTime() { LASTINPUTINFO lastInPut = new LASTINPUTINFO(); lastInPut.cbSize = (uint)System.Runtime.InteropServices.Marshal.SizeOf(lastInPut); if (!GetLastInputInfo(ref lastInPut)) { throw new Exception(GetLastError().ToString()); } return lastInPut.dwTime; } } ``` To convert the tickcount into time you can use ``` TimeSpan timespent = TimeSpan.FromMilliseconds(ticks); ``` Note. This routine uses the term TickCount but the values are in milliseconds and are so not the same as Ticks. From [MSDN article on Environment.TickCount](https://msdn.microsoft.com/en-us/library/system.environment.tickcount%28v=vs.110%29.aspx?f=255&MSPPError=-2147217396) > Gets the number of milliseconds elapsed since the system started.
C# - Detect time of last user interaction with the OS
[ "", "c#", "windows", "winapi", "system-tray", "idle-processing", "" ]
I've been taught to keep class definitions and code separate. However, I've seen situations where people would often include some bits of code in the header, e.g. simple access methods which returns a reference of a variable. Where do you draw the line?
Generally speaking, things you want the compiler to inline, or templated code. In either case, the code must be available to the compiler everywhere it's used, so you have no choice. However, note that the more code you put in a header file, the longer it will take to compile - and the more often you'll end up touching header files, thus causing a chain reaction of slow builds :)
One reason to minimize the amount of code in headers is to minimize the amount of code to be recompiled when the implementation changes. If you don't care about that you can have any amount of code in headers. Sometimes having the code in headers only is done intentionally to expose the code - ATL does that for eaxmple.
C++: When is it acceptable to have code in the header file?
[ "", "c++", "coding-style", "header", "" ]
Ok heres my problem. I have a form that when it is not maximised, its maximum size has to be the total height of the components inside the form. To achieve this, i use this: ``` private void resize_form(object sender, EventArgs e) { this.MaximumSize = new System.Drawing.Size(1000, this.panel4.Height + this.label2.Height + this.HeightMin); } ``` That fires on the Resize event of the form. Because the component size is always changing it made sense to do this on a resize event. How ever if i want to maximise the form, the form just goes to the highest settings defined in this.MaximumSize. So i was wondering is there a way to tell when a form is going to be maximised and set its maximumsize to the screen boundarys before the form maximises. If there is a better way to change the maximumsize value without resize event, that would also be great :)
I found the answer that suited me perfectly. A lil WndProc override :D (i love WndProc now) ``` protected override void WndProc(ref Message message) { const int WM_SYSCOMMAND = 0x0112; const int SC_MAXIMIZE = 0xF030; switch (message.Msg) { case WM_SYSCOMMAND: int command = message.WParam.ToInt32() & 0xfff0; if (command == SC_MAXIMIZE) { this.maximize = true; this.MaximumSize = new System.Drawing.Size(0, 0); } break; } base.WndProc(ref message); } private void resize_form(object sender, EventArgs e) { if (!maximize) { this.MaximumSize = new System.Drawing.Size(1000, this.panel4.Height + this.label2.Height + this.HeightMin); } } ``` Basically it sets this.maximize to true when it receives teh SC\_MAXIMIZE message. The resize event will only set a new MaximumSize if this.maximize is set to false. Nifty xD
You still need to use the resize event, but check the `WindowState`: ``` if (this.WindowState == FormWindowState.Maximized) { // Do your stuff } ``` As yshuditelu points out you can set the minimum size property of your form too - which should, when coupled with judicious use of anchor values, mean that it can never shrink too far and when it does grow the components will move and/or grow as required.
C# Tell If Form Is Maximising
[ "", "c#", "winforms", "resize", "wndproc", "maximize", "" ]
I´m trying to run an old .NET application from an ASP.NET website. After reading the web and Stackoverflow (for similar problem) I come to the following code. The Problem is that I get always an error code (I am using administrator account just to testing purposes). If I run the exe manually it works ok. ``` private void Execute(string sPath) { System.Diagnostics.Process proc = new System.Diagnostics.Process(); proc.StartInfo.UserName = "administrador"; string pass = "............."; System.Security.SecureString secret = new System.Security.SecureString(); foreach (char c in pass) secret.AppendChar(c); proc.StartInfo.Password = secret; proc.StartInfo.WorkingDirectory = ConfigurationManager.AppSettings["WORKINGDIRECTORY"].ToString(); proc.StartInfo.RedirectStandardOutput = true; proc.StartInfo.RedirectStandardError = true; proc.StartInfo.UseShellExecute = false; proc.StartInfo.FileName = sPath; proc.Start(); proc.WaitForExit(); string result = proc.StandardOutput.ReadToEnd(); Response.Write(result + " - " + proc.ExitCode); proc.Close(); } ``` } The exitcode I get is: -1066598274 Result variable is empty. No exception is thrown I am using Windows 2008 with IIS 7.0 Thanks in advance, Ezequiel
You may need to set the `proc.StartInfo.LoadUserProfile` property to `true` so the administrator's user profile stuff is loaded into the registry (AFAIK this does not happen by default). Also, it might be educational to run a 'hello world' program to see if the problem is with actaully creating the process or if the process itself is having problems running in the context it's given. Finally, as a step in trying to narrow down where the problem might be, you might want to run the ASP.NET process itself with admin or system credentials to see if something in the permissions of the account the ASP.NET instance is running under is part of the problem (but please do this only for troubleshooting).
Don't do this. This is just plain dirty and should not be done from ASP.NET 1. Write a windows service 2. Store the request in a queue 3. The service should poll the queue and process. If needed run the exe. It is suggested that the service stays in a different server. Don't do this. This is very bad and not scalable and bad for the web server Don't Don't Don't
ASP.NET running an EXE File
[ "", "c#", ".net", "process", "execution", "" ]
I got thousands of data inside the array that was parsed from xml.. My concern is the processing time of my script, Does it affect the processing time of my script since I have a hundred thousand records to be inserted in the database? I there a way that I process the insertion of the data to the database in batch?
This is for SQL files - but you can follow it's model ( if not just use it ) - It splits the file up into parts that you can specify, say 3000 lines and then inserts them on a timed interval < 1 second to 1 minute or more. This way a large file is broken into smaller inserts etc. This will help bypass editing the php server configuration and worrying about memory limits etc. Such as script execution time and the like. New Users can't insert links so Google Search "sql big dump" or if this works goto: www [dot] ozerov [dot] de [ slash ] bigdump [ dot ] php So you could even theoretically modify the above script to accept your array as the data source instead of the SQl file. It would take some modification obviously. Hope it helps. -R
Syntax is: ``` INSERT INTO tablename (fld1, fld2) VALUES (val1, val2), (val3, val4)... ; ``` So you can write smth. like this (dummy example): ``` foreach ($data AS $key=>$value) { $data[$key] = "($value[0], $value[1])"; } $query = "INSERT INTO tablename (fld1, fld2) VALUES ".implode(',', $data); ``` This works quite fast event on huge datasets, and don't worry about performance if your dataset fits in memory.
Batch processing in array using PHP
[ "", "php", "arrays", "" ]
Google's finance API is incomplete -- many of the figures on a page such as: <http://www.google.com/finance?fstype=ii&q=NYSE:GE> are not available via the API. I need this data to rank companies on Canadian stock exchanges according to the formula of Greenblatt, available via google search for "greenblatt index scans". My question: what is the most intelligent/clean/efficient way of accessing and processing the data on these webpages. Is the tedious approach really necessary in this case, and if so, what is the best way of going about it? I'm currently learning Python for projects related to this one.
You could try asking Google to provide the missing APIs. Otherwise, you're stuck with [screen scraping](http://en.wikipedia.org/wiki/Screen_scraping), which is never fun, prone to breaking without notice, and **likely in violation of Google's terms of service**. But, if you still want to write a screen scraper, it's hard to beat a combination of [mechanize](http://wwwsearch.sourceforge.net/mechanize/) and [BeautifulSoup](http://www.crummy.com/software/BeautifulSoup/). BeautifulSoup is an HTML parser and mechanize is a Python-based web browser that will let you log in, store cookies, and generally navigate around like any other web browser.
[BeautifulSoup](http://www.crummy.com/software/BeautifulSoup/) would be the preferred method of HTML parsing with Python Have you looked into options besides Google (e.g. Yahoo Finance API)?
Obtaining financial data from Google Finance which is outside the scope of the API
[ "", "python", "api", "data-mining", "google-finance", "" ]
Thi simple code below outputs two alerts instead of one Google Chrome browser. Can you tell why only in Chrome? ``` <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /> <title>Can you tell?</title> <script language="javascript" type="text/javascript"> function hitme() { alert('yep!'); } </script> </head> <body> <a href="#" onmouseover="hitme();">LINK</a> </body> </html> ``` Is chrome seeing the anchor as text + it's row? What's making this double box in Chrome?
alerting on events like mouseover is notoriously bad (read: unpredictable). mouseover event handling is great for a state change but less so for some kind of interaction like an alert. What is likely happening is the mouseover is being fired multiple times (note mouseover is not the same as mouseenter -- note: not well supported) see <http://www.quirksmode.org/js/events_mouse.html> for more details on mouse events. It's important to be aware that different browsers handle events differently. mousemove, for example, is only fired when the mouse *moves* in most browsers, but in firefox (if I recall correctly) it is almost constantly firing. Ditto for mouseover, and if you're really lucky, you get a stack of alert windows to close for that half second your mouse was over an element.
I'm guessing it's something to do with window focus; if you move the mouse over the link quick enough you get only one alert box. Doesn't happen in Safari for Mac fwiw.
Chrome Javascript Double Alert Loop?
[ "", "javascript", "jquery", "xhtml", "dhtml", "" ]
I'm writing yet another ActiveRecord implementation for a company that is less scared of my code than they are the designation "Release Candidate" on CastleProject's implementation. Anyway, I'm using Attributes on each property in the base class to map them to the returning DataSet's columns: ``` [ResultColumnAttribute("CUST_FIRST_NAME")] public string FirstName { get { return _columnName; } set { _columnName = value; } } ``` so that when I instantiate the class from a DataSet, I assign that property value the column's value. What exception should I throw when a column is mapped with an attribute, but doesn't show up in the DataSet? I don't want to go and write a custom one (lazy), and I think Application.Exception is a little nondescript.
This exception is localized to your domain and as such I think you would be better off writing your own `InvalidMappingException`. Here is how I would write it: ``` [Serializable] public class InvalidMappingException : Exception { public InvalidMappingException() { } public InvalidMappingException(String message) : base(message) { } public InvalidMappingException (String message, Exception innerException) : base(message, innerException) { } protected InvalidMappingException (SerializationInfo info, StreamingContext context) : base(info, context) { } } ```
I see no reason not to use `InvalidOperationException`. Remember that unless your callers will do something programmatic with your exception, the exception type does not matter. For instance, if they are going to catch it explicitly, or reference some property of your exception, then you need one of your own. Otherwise, the built-in exceptions will do fine. --- See [How to Design Exception Hierarchies](http://blogs.msdn.com/kcwalina/archive/2007/01/30/ExceptionHierarchies.aspx) by Krzysztof Cwalina, coauthor of [Framework Design Guidelines: Conventions, Idioms, and Patterns for Reusable .NET Libraries](https://rads.stackoverflow.com/amzn/click/com/0321545613).
Which .Net 2.0 Exception should I throw in this circumstance?
[ "", "c#", "exception", "" ]
In the past I've used Perl's AUTOLOAD facility for implementing lazy loading of symbols into a namespace, and wanted the same functionality in python. Traditionally the closest you appear to be able to get is to use a class and a `__getattr__` class to achieve this sort of thing. However I've also tried rummanging around in `sys.modules`, and come up with this: ``` # mymod.py def greet(greeting="Hello World"): print greeting class Autoload(object): def __init__(self, __name__): super(Autoload, self).__init__() self.wrapped_name = __name__ self.wrapped = sys.modules[__name__] def __getattr__(self, name): try: return getattr(self.wrapped, name) except AttributeError: def f(): greet(name+" "+self.wrapped_name) return f if __name__ != "__main__": import sys sys.modules[__name__] = autoload(__name__) ``` This does work the way I'd like from a user perspective: ``` ~> python Python 2.5.1 (r251:54863, Jan 10 2008, 18:01:57) [GCC 4.2.1 (SUSE Linux)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import mymod >>> mymod.hello() hello mymod >>> from mymod import Hello_World >>> Hello_World() Hello_World mymod ``` But it strikes me - is there a standard approach that people tend to use for autoloading in python? Secondly, a question for experienced python developers really is "does this strike you as good or bad practice"? I'm a reasonably experienced python developer, and it strikes me as really useful, but it strikes me as borderline and interested in whether this can be viewed as good practice, bad practice or similar.
To answer the question of using a class to impersonate a module: Yes, the functionality is not accidental. It has been there since early in the 2.x series and still works in the 3.x series. To answer the question of lazy loading: There are several ways to do it, and each one is going to be a bit mysterious. Using a module impersonator is a fine method.
"Lazy imports" could be built on top of the "import hooks" specified in [PEP 302](http://www.python.org/dev/peps/pep-0302/), and now fully implemented. PEP 369 used to cover "lazy imports" as well as post-import hooks, but has since been simplified and now only covers post-import hooks; still, you might be interested in the [original draft](http://permalink.gmane.org/gmane.comp.python.devel/90949). A good implementation of "lazy imports" via the `meta_path` hook can be found in [this recipe](http://code.activestate.com/recipes/473888/).
Autoload in Python
[ "", "python", "coding-style", "autoload", "" ]
Good day, I have a hibernate mapping which goes something like this ``` <class name="Person"> <id name="id" type="long" column="person_id" unsaved-value="null"> <generator class="sequence"> <param name="sequence">person_id_seq</param> </generator> </id> ... <set name="thinCollection" table="(select person_id, person_property from some_other_table where another_property = 'something')" fetch="subselect" lazy="false"> <key column="person_id"/> <element column="person_property" type="long"/> </set> ... </class> ``` Now my problem is, when a Person object gets flushed, it tries to execute a Collection Remove Action against Person#thinCollection, which fails because it's trying to execute `delete from (select person_id, person_property from some_other_table where another_property = 'something')`. Thus in line with that, how do I stop Hibernate from executing such actions (as well as update and inserts) ? Thanks
What I currently did to solve this is to create my own persister (which is a subclass of BasicCollectionPersister) which never does an insertion/update/deletion. But I am not sure if this is the best way to go about this or if could simply just add a magic mapping attribute to prevent the insertion/update/deletion. [EDIT] I found it hard to map my Set to a subselect so I used my own custom BasicCollectionPersister instead. I overriden #isRowDeleteEnabled() and #isRowInsertEnabled() to both always return false. And I overriden #doUpdateRows(..) to always return 0.
I believe you want to use a subselect for your query, thus rendering it readonly. <http://docs.jboss.org/hibernate/stable/core/reference/en/html/mapping.html>
Hibernate set mapped to a 'sql select' table
[ "", "java", "hibernate", "" ]
What convention do you use to comment getters and setters? This is something I've wondered for quite some time, for instance: ``` /** * (1a) what do you put here? * @param salary (1b) what do you put here? */ public void setSalary(float salary); /* * (2a) what do you put here? * @return (2b) */ public float getSalary(); ``` I always find I'm pretty much writing the exact same thing for 1a/b and 2a/b, something like 1a) Sets the salary of the employee, 1b) the salary of the employee. It just seems so redundant. Now I could see for something more complex you might write more in the (a) parts, to give context, but for a majority of the getters/setters out there the wording is almost exactly the same. I'm just curious if, for the simple getters/setters its ok to only fill in either the (a) part OR the (b) part. What do you think?
I usually just fill the param part for setters, and the @return part for getters: ``` /** * * @param salary salary to set (in cents) */ public void setSalary(float salary); /** * @return current salary (in cents, may be imaginary for weird employees) */ public float getSalary(); ``` That way javadoc checking tools (such as Eclipse's warnings) will come out clean, and there's no duplication.
Absolutely pointless - you're better off without this kind of crap cluttering your code: ``` /** * Sets the foo. * * @param foo the foo to set */ public void setFoo(float foo); ``` Very useful, if warranted: ``` /** * Foo is the adjustment factor used in the Bar-calculation. It has a default * value depending on the Baz type, but can be adjusted on a per-case base. * * @param foo must be greater than 0 and not greater than MAX_FOO. */ public void setFoo(float foo); ``` Especially the explanation of what the property actually means can be crucial in domain models. Whenever I see a bean full of properties with obscure names that only investment bankers, biochemists or quantum physicists understand, and the comments explain that the setGobbledygook() method "sets the gobbledygook.", I want to strangle someone.
Simple Getter/Setter comments
[ "", "java", "comments", "javadoc", "setter", "getter", "" ]
Let's say your processing a message in an overridden class like: ``` class MailProcessorServer(smtpd.SMTPServer): def process_message(self, peer, sender, rcpttos, data): badrecipients = [] for rcpt in rcpttos: badrecipients.append(rcpt) #Here I want to warn the sender via a bounced email # that the recipient does not exist raise smtplib.SMTPRecipientsRefused(badrecipients) #but this just crashes the process and eventually the sender times out, # not good enough ``` I just want to bounce back to the sender immediately. Instead the sending service (say, GMail) just gives up eventually and warns the user many hours later. The [documentation](http://www.python.org/doc/2.5.2/lib/node620.html) seems pretty sparse.
As documented only in [the sources](http://svn.python.org/view/python/trunk/Lib/smtpd.py?revision=69846&view=markup) (sorry!), `process_message`'s specs include: > This function should return None, for > a normal `250 Ok' response; otherwise > it returns the desired response string > in RFC 821 format. So you could "return '554 bad recipients %s' % badrecipients" instead of using that `raise` statement -- not entirely satisfactory (doesn't properly account for a mix of good and bad, which by RFC 821 *should* return a '250 Ok' but also send a warning mail later) but it does seem to be the "bounce back immediately" effect that you're looking for with that `raise`.
The way to reject a message is to return a string with the error code from your `process_message` method; e.g. ``` return '550 No such user here' ``` However, RFC 821 doesn't allow error code 550 to be returned after the message data has been transfered (it should be returned after the `RCPT` command), and the smtpd module unfortunately doesn't provide an easy way to return an error code at that stage. Furthermore, smtpd.py makes it difficult to subclass its classes by using auto-mangling "private" double-underscore attributes. You may be able to use the following custom subclasses of smtpd classes, but I haven't tested this code: ``` class RecipientValidatingSMTPChannel(smtpd.SMTPChannel): def smtp_RCPT(self, arg): print >> smtpd.DEBUGSTREAM, '===> RCPT', arg if not self._SMTPChannel__mailfrom: self.push('503 Error: need MAIL command') return address = self._SMTPChannel__getaddr('TO:', arg) if not address: self.push('501 Syntax: RCPT TO: <address>') return if self._SMTPChannel__server.is_valid_recipient(address): self._SMTPChannel__rcpttos.append(address) print >> smtpd.DEBUGSTREAM, 'recips:', self._SMTPChannel__rcpttos self.push('250 Ok') else: self.push('550 No such user here') class MailProcessorServer(smtpd.SMTPServer): def handle_accept(self): conn, addr = self.accept() print >> smtpd.DEBUGSTREAM, 'Incoming connection from %s' % repr(addr) channel = RecipientValidatingSMTPChannel(self, conn, addr) def is_valid_recipient(self, address): # insert your own tests here, return True if it's valid return False ```
How to refuse a recipient in smtpd.SMTPServer.process_message?
[ "", "python", "email", "smtp", "" ]
I've got a JavaScript-function that sets the "onclick"-event of some HTML-Nodes - even if that "onclick"-event has been set before. How can i check if that event has already been set, so I can extend my function to set the event only on HTML-Nodes where it has not already been set?
Check, like this: ``` if(typeof someNode.onclick == "function") { // someNode has an event handler already set for the onclick event... } ``` By the way, if you are using a library, you should say so - if you are, it might be easier/cleaner and would differ based on which library you are using...
It should be possible to detect event handlers attached using `<element>.addEventListener()` by intercepting calls to the function: ``` var myListOfAddedEvents = []; var realAddEventListener = HTMLElement.prototype.addEventListener; HTMLElement.prototype.addEventListener = function(evtType,fn,cap) { myListOfAddedEvents.push( {on: this, type: evtType, handler: fn, capture: cap} ); return realAddEventListener.apply(this, arguments); }; ``` Note: That is untested code and may need some work. I'm *hoping* this same function will be used by all element types, but I could be wrong. Also it will only work if you can run this bit of code *before* they start adding events. A copy for attachEvent could be constructed similarly.
How can i check if a JavaScript-Eventhandler has been set?
[ "", "javascript", "events", "" ]
I have C++ structure as ``` struct myStruct { int a; int b; int c; }; myStruct b; int *ptr = &b.c; ``` How can I get myStruct object back from ptr? (I know I can do this using pointer arithmatic like container\_Of() in C. Basically something like ``` reinterpret_cast<myStruct*>(reinterpret_cast<char *>(ptr) - offsetof(myStruct, c)); ``` I am asking if there is any recommended/elegant way?)
There's certainly no recommended way, as doing this is definitely not recommended at all in C++. This is one of those questions where the correct answer has to be "Don't do that!" The whole reason for using C++ instead of C is that you want to encapsulate the structure of data inside classes with sensible operations defined on them, instead of allowing the whole program to have knowledge of the internal layout of data structures. That said, the `offsetof` technique you describe will work on plain old data objects, because they are no different to C structs.
Because **ptr** has no knowledge of its overlaying struct, I don't think there's an elegant way of getting back to **myStruct**. I just recommend to not do this!
Getting a class/struct object from the member pointer
[ "", "c++", "" ]
There are at least two ways that I know of to write a Symbian application: 1. J2ME 2. A native application. My question is, does the SDK/API for either of those methods (or any other method) grant me (at least) read-only access to contact information (names/numbers/etc) on the phone itself? Does this in any way depend on the specific phone being used?
In C++, you can use e.g. the Contacts Model API. There's an [example](http://www.forum.nokia.com/info/sw.nokia.com/id/604e40f2-a85c-4a16-8699-0f34a85b0b14/S60_Platform_Contacts_Model_API_Example.html) in Forum Nokia. In J2ME, you need to be working on [a phone that has JSR-75](http://www.forum.nokia.com/advanced-search/search.xhtml?mandatoryKeywords=&facets=&keywords=&resourceType=http%3A%2F%2Fsw.nokia.com%2FFN-1%2FType%2FTerminal&searchSubmitted=true&mandatoryFacets=UEsDBBQACAAIAERmyzoAAAAAAAAAAAAAAAABAAAAMKvIKCkpSDW1cE01MQfj4vJUEzPXvPzszEQQIzk%2FFyxjZuEakGpi6moI4mUlliWmWpq6JhZkRoRWkGOCF9AExwBPsGHFReamEQpEGuPmBzejpLIg1dDA0JVoJyDpDYHqBbPBrKLczLzEnAgFAFBLBwhJMi25bAAAABEBAAA%3D&editorView=http%3A%2F%2Fsw.nokia.com%2FEditor-1%2FView%2Fsearch). Again, there's an [example](http://wiki.forum.nokia.com/index.php/How_to_read_contacts_using_JSR_75) in Forum Nokia.
Open the default contact database using CContactDatabase::OpenL(). use thus returned database object in TContactIter::NextL() in a loop to fetch the IDs of every contact in the contact book.
Symbian: Is it possible to get access to a list of contacts through an application?
[ "", "c++", "java-me", "mobile", "symbian", "nokia", "" ]
I'm porting a library of image manipulation routines into C from Java and I'm getting some very small differences when I compare the results. Is it reasonable that these differences are in the different languages' handling of float values or do I still have work to do! The routine is Convolution with a 3 x 3 kernel, it's operated on a bitmap represented by a linear array of pixels, a width and a depth. You need not understand this code exactly to answer my question, it's just here for reference. Java code; ``` for (int x = 0; x < width; x++){ for (int y = 0; y < height; y++){ int offset = (y*width)+x; if(x % (width-1) == 0 || y % (height-1) == 0){ input.setPixel(x, y, 0xFF000000); // Alpha channel only for border } else { float r = 0; float g = 0; float b = 0; for(int kx = -1 ; kx <= 1; kx++ ){ for(int ky = -1 ; ky <= 1; ky++ ){ int pixel = pix[offset+(width*ky)+kx]; int t1 = Color.red(pixel); int t2 = Color.green(pixel); int t3 = Color.blue(pixel); float m = kernel[((ky+1)*3)+kx+1]; r += Color.red(pixel) * m; g += Color.green(pixel) * m; b += Color.blue(pixel) * m; } } input.setPixel(x, y, Color.rgb(clamp((int)r), clamp((int)g), clamp((int)b))); } } } return input; ``` Clamp restricts the bands' values to the range [0..255] and Color.red is equivalent to (pixel & 0x00FF0000) >> 16. The C code goes like this; ``` for(x=1;x<width-1;x++){ for(y=1; y<height-1; y++){ offset = x + (y*width); rAcc=0; gAcc=0; bAcc=0; for(z=0;z<kernelLength;z++){ xk = x + xOffsets[z]; yk = y + yOffsets[z]; kOffset = xk + (yk * width); rAcc += kernel[z] * ((b1[kOffset] & rMask)>>16); gAcc += kernel[z] * ((b1[kOffset] & gMask)>>8); bAcc += kernel[z] * (b1[kOffset] & bMask); } // Clamp values rAcc = rAcc > 255 ? 255 : rAcc < 0 ? 0 : rAcc; gAcc = gAcc > 255 ? 255 : gAcc < 0 ? 0 : gAcc; bAcc = bAcc > 255 ? 255 : bAcc < 0 ? 0 : bAcc; // Round the floats r = (int)(rAcc + 0.5); g = (int)(gAcc + 0.5); b = (int)(bAcc + 0.5); output[offset] = (a|r<<16|g<<8|b) ; } } ``` It's a little different xOffsets provides the xOffset for the kernel element for example. The main point is that my results are out by at most one bit. The following are pixel values; ``` FF205448 expected FF215449 returned 44 wrong FF56977E expected FF56977F returned 45 wrong FF4A9A7D expected FF4B9B7E returned 54 wrong FF3F9478 expected FF3F9578 returned 74 wrong FF004A12 expected FF004A13 returned ``` Do you believe this is a problem with my code or rather a difference in the language? Kind regards, Gav
After a quick look: do you realize that (int)r will floor the r value instead of rounding it normally? in the c code, you seem to use (int)(r + 0.5)
Further to Fortega's answer, try [the `roundf()` function from the C math library](http://www.codecogs.com/reference/c/math.h/round.php).
Convolution Filter - Float Precision C Vs Java
[ "", "java", "c", "image", "floating-point", "convolution", "" ]
I have this method signature: ``` public int nrOfEntities(Class<? extends MailConfirmation> clazz, User user, String email) ``` I would like nrOfEntities to return the number of entities that: * Are of the concrete class clazz * Have a matching User if user != null * Have a matching email if user == null It's the class matching I'm having a problem with. I've tried a few statements without any luck.
Can clazz have subtypes that should not be counted? If not, is it not sufficient to create the query on clazz? ``` Criteria criteria = session.createCriteria(clazz); if (user == null) { criteria.add(Restrictions.eq("email", email); } else { criteria.add(Restrictions.eq("user", user); } int result = (Integer) criteria.setProjection(Projections.rowCount()).uniqueResult(); ``` Now I am guessing how your mapping looks (that there are "email" and "user" properties). If that is not working, I know that there is a pseudo property named "class", at least in HQL. Maybe you can experiment with that.
If you want to test the class of an object, you should be able to use something like the following: ``` Object entity = ... // Get the entity however boolean matchesClass = entity.getClass().equals(clazz); ``` If this isn't working for you, give some examples of how it fails since it should be this straightforward!
Find concrete class using a dynamic expression (where a Class instance is passed to a DAO)
[ "", "java", "hibernate", "" ]
How to determine whether a file is using?
In java you can lock Files and checking for [shared access](http://java.sun.com/developer/JDCTechTips/2002/tt0924.html). > You can use a file lock to restrict > access to a file from multiple > processes ``` public class Locking { public static void main(String arsg[]) throws IOException { RandomAccessFile raf = new RandomAccessFile("junk.dat", "rw"); FileChannel channel = raf.getChannel(); FileLock lock = channel.lock(); try { System.out.println("Got lock!!!"); System.out.println("Press ENTER to continue"); System.in.read(new byte[10]); } finally { lock.release(); } } } ``` You also can check whether a lock exists by calling ``` // Try acquiring the lock without blocking. This method returns // null or throws an exception if the file is already locked. try { lock = channel.tryLock(); } catch (OverlappingFileLockException e) { // File is already locked in this thread or virtual machine } ```
I don't think that Java can tell you whether another process is using a file. Depending on what you're trying to do, you might get an `IOException` when you try to manipulate it. Otherwise, if you're no Linux, you might want to look at [lsof](http://en.wikipedia.org/wiki/Lsof).
[Java]How to determine whether a file is using?
[ "", "java", "" ]
I got a simple problem in SQLAlchemy. I have one model in a table, lets call it Model1 here. I want to add a row in this table, and get the autoincremented key, so I can create another model with it, and use this key. This is not a flawed database design (1:1 relation etc). I simply need this key in another table, because the other table is being transferred to a remote host, and I need the matching keys so the servers will understand each other. There will be no further local reference between these 2 tables, and it's also not possible to create relations because of that. Consider the following code: ``` object1 = model.Model1(param) DBSession.add(object1) # if I do this, the line below fails with an UnboundExecutionError. # and if I dont do this, object1.id won't be set yet #transaction.commit() object2 = model.AnotherModel(object1.id) #id holds the primary, autoincremented key ``` I wished I wouldn't even have to commit "manually". Basically what I would like to achieve is, "Model1" is constantly growing, with increasing Model.id primary key. AnotherModel is always only a little fraction of Model1, which hasn't been processed yet. Of course I could add a flag in "Model1", a boolean field in the table to mark already processed elements, but I was hoping this would not be necessary. How can I get my above code working? Greets, Tom
A couple of things: * Could you please explain what the variable `transaction` is bound to? * Exactly what statement raises the UnboundExecutionError? * Please provide the full exception message, including stack trace. * The 'normal' thing to do in this case, would be to call `DBSession.flush()`. Have you tried that? Example: ``` object1 = Model1(param) DBSession.add(object1) DBSession.flush() assert object1.id != None # flushing the session populates the id object2 = AnotherModel(object1.id) ``` For a great explanation to the SA session and what `flush()` does, see [Using the Session](http://www.sqlalchemy.org/docs/05/session.html#id1). Basically, `flush()` causes Pending instances to become Persistent - meaning that new objects are INSERTed into the database tables. `flush()` also UPDATEs the tables with values for instances that the session tracks that has changes. `commit()` always issues `flush()` first. Within a transaction, you can flush multiple times. Each flush() causes UPDATEs and/or INSERTs in the database. The entire transaction can be commited or rolled back.
if you want to get new primary key identifiers to generate without anything being committed, just call session.flush(). That will emit everything pending to the database within the current transaction.
SQLAlchemy: Object Mappings lost after commit?
[ "", "python", "database", "sqlalchemy", "" ]
Does anyone know the command to check if there is an un-committed transaction in SQL Server 2005?
use [@@trancount](http://msdn.microsoft.com/en-us/library/ms187967.aspx) or [sys.dm\_tran\_active\_transactions](http://msdn.microsoft.com/en-us/library/ms174302.aspx) DMV in sql 2005, 2008
**XACT\_STATE()** reports the transaction state of a session, indicating whether or not the session has an active transaction, and whether or not the transaction is capable of being committed. It returns three values: * 1, The session has an active transaction. The session can perform any actions, including writing data and committing the transaction. * 0, There is no transaction active for the session. * -1, The session has an active transaction, but an error has occurred that has caused the transaction to be classified as an uncommittable transaction. The session cannot commit the transaction or roll back to a savepoint; it can only request a full rollback of the transaction. The session cannot perform any write operations until it rolls back the transaction. The session can only perform read operations until it rolls back the transaction. After the transaction has been rolled back, the session can perform both read and write operations and can begin a new transaction. **@@TRANCOUNT** Returns the number of active transactions for the current connection. * 0, not in a transaction * 1, in a transaction * n, in a nested transaction
How to check that there is transaction that is not yet committed in SQL Server 2005?
[ "", "sql", "sql-server", "sql-server-2005", "transactions", "" ]
I need a link in an HTML page that could use any JavaScript to "start downloading" a normal webpage / file that is on my webserver, either filetypes like PDF / ZIP or simply the outputs of PHP / ASP / HTML. I know this is possible with some server-side download script that returns a *mime\_content\_type* so the browser handles it based on its configuration. (typically Download) but I would really like a JavaScript-only solution. Any ideas?
If you want to force the browser to display the Save As dialog I uses the following headers: ``` Content-type: application/octet-stream Content-Transfer-Encoding: binary Content-disposition: attachment; filename=test.pdf ```
You simply cannot do that in javascript, as you need to change the mime type header. The best you could do is to use open('the url') to open it in another window, but I don't think that fits to your needs and could be blocked by popup blockers.
Download any filetype from a webserver
[ "", "javascript", "html", "download", "" ]
I am having trouble handling the selections in `DataGridView`. My grid view contains an amount column. There is a textbox on the form which should display the total amount of the selected grid view rows. Hence I need to capture events when the user selects/ deselects the gridview rows and calculate (add/ subtract) the amount accordingly. I have found two methods of doing it: 1. Using the `RowEnter` and `RowLeave` events. These work fine when user selects/ deselects a single row. However, when the user is selecting multiple rows at one go, the event gets fired only for the last row. Hence, from my total amount only the amount in the last row gets added/ subtracted. Thus making my result erroneous. 2. Using the `RowStateChanged` event. This works for multiple rows. However, the event gets fired event if the user scrolls through the datagrid. Has anyone handled such a scenario. I would like to know which datagrid event I should be using, so that my code executes only when user selects/ deselects rows including multiple rows.
Found the solution. I can use `RowStateChanged` and run my code only if `StateChanged` for the row is `Selected`... ``` private void dgridv_RowStateChanged(object sender, DataGridViewRowStateChangedEventArgs e) { // For any other operation except, StateChanged, do nothing if (e.StateChanged != DataGridViewElementStates.Selected) return; // Calculate amount code goes here } ```
I use **SelectionChanged** event or **CellValueChanged** event: ``` dtGrid.SelectionChanged += DataGridView_SelectionChanged; this.dtGrid.DataSource = GetListOfEntities; dtGrid.CellValueChanged += DataGridView_CellValueChanged; private void DataGridView_CellValueChanged(object sender, DataGridViewCellEventArgs e) { DataGridViewRow row = dtGrid.Rows[e.RowIndex]; SetRowProperties(row); } private void DataGridView_SelectionChanged(object sender, EventArgs e) { var rowsCount = dtGrid.SelectedRows.Count; if (rowsCount == 0 || rowsCount > 1) return; var row = dtGrid.SelectedRows[0]; if (row == null) return; ResolveActionsForRow(row); } ```
DataGridView capturing user row selection
[ "", "c#", "winforms", "" ]
I'm trying to come up with a good design for converting a set of different objects into a common object. Basically, I receive one (of many slightly different) complex object from system A, and must convert it into a simpler object for system B. The objects I'm converting from all inherit from the same base class, so part of the conversion is always the same. But in every case, the conversion does involve something very specific to the type of the object I'm converting. It could be a RPC, an HTTP fetch, a database lookup, or something entirely different. I'm looking at the [Template method](http://en.wikipedia.org/wiki/Template_method_pattern) and the [Strategy](http://en.wikipedia.org/wiki/Strategy_pattern) patterns. But neither seems like a perfect fit. The problem is that the method/strategy to use is tied to the type of object being converted and so isn't interchangeable. This is a sketch of what I'm thinking about doing: ``` class FooConverter { Map<String, FooConverter> converters; Foo convert(Bar bar) { Foo foo = ...; // Common part of the conversion. FooConverter c = converters.get(bar.getType(), foo); c.finishConversion(bar, foo); return foo; } } ``` What annoys me is that `FooConverter` must define an additional conversion method that takes the partially converted object as a parameter. So I end up with a mix of a Strategy (since all the converters implement the same interface) and Template method (since the common part of the conversion is shared by all the converter). Is there a better way?
It sounds like you need to traverse a structure and be able to do something with each element in the structure. That 'something' varies by the type of the element, and you also want to be able to vary *how* that 'something' is implemented. If that is the case, it sounds like a perfect fit for the **Visitor** pattern. I just recently used it myself in a scenario much like yours where I needed to convert one structure into another in a flexible manner.
You are taking a bunch of "Convertable" objects, perhaps you could make "Foo" have Decorators for each "Convertable" base type, when you detect the "Convertable" type, you can add the appropriate Decorator to the "Foo"?
Design for converting objects
[ "", "java", "design-patterns", "" ]
I want to compare C++ class/structure objects. In C, most of the time, one knows exact size of the `struct` by adding up the sizes of individual fields (assuming that compiler does not add padding). Hence one can use memcmp() function on two object to compare them very fast. I am not sure if the same works for C++. This is because a class also has function definitions and maybe some other hidden things (some RTTI info perhaps? A virtual function table even?) A quick program with a simple structure containing `int` and `char` members and a function showed that size of the structure was `sizeof(int)+sizeof(char)`. I have a one big struct class with simple int, char etc data types (but a large number of them). I want to compare objects from time to time. I cannot overload the `==` operator as that will make them compare each field by field. In C, I can compare in one go using `memcmp()`. Any suggestions for C++? Can I use `memcmp()` directly? I dont want memcmp() to fail because some other value like virtual function pointer table is different (but all the fields are actually equal) (I'm using g++)
Be wary on numerous counts... 1. The values in any padding is indeterminate and hence not comparable. 2. If your machine is little-endian, comparing integer fields will produce one answer; if your machine is big-endian, it will produce another answer. 3. Most people regard -1 as smaller than 0, but `memcmp()` will do byte-wise unsigned comparison, and will therefore treat -1 as bigger than 0. 4. Any pointers are inherently not comparable relevantly by `memcmp()`. 5. You cannot compare `float` or `double` using `memcmp()`. On the whole, you are seeking a non-sensible optimization.
It is possible to take `sizeof()` a struct or class. **edit:** since I provided the answer above, you have changed your question from "How can I manually determine the size of C++ structures and classes?" to a more general one about comparing two classes. The short answer is that you *do* want to overload the `==` operator. The belief that it will compare each field by field one at a time is incorrect; you may overload `operator ==` to use any algorithm you like, including a `memcmp`. `memcmp()` on the memory from the first field offset to the last should work fine. A `memcmp()` on the entire footprint of the class may fail if you are comparing a class of type A to another class B which inherits from A, as the vtable pointers may be different.
Comparing structures in C vs C++
[ "", "c++", "class", "" ]
Can someone explain to me what the difference between ``` include_once 'classb.php' class A { $a = new B } ``` and ``` class A extends B { $a = new B } ``` is? What advantages/disadvantages are there to extending a class vs. including the .php file?
Your `include_once` reads in a source file, which in this case presumably has a class definition for `B` in it. Your `extends` sets up class `A` as [inheriting](http://en.wikipedia.org/wiki/Inheritance_(computer_science)) class `B`, i.e. `A` gets everything in `B` and can then define its own modifications to that basic structure. There isn't really any relationship at all between the two operations, and your `$a = new B` operations are nonsensical (not to mention syntax errors).
In case you're looking for a higher level answer... Using extends binds A to doing things similarly to B, whereas creating an instance of B within A doesn't impose any restrictions on A. The second approach is called Composition and is generally the preferred approach to building OO systems since it doesn't yield tall Class hierarchies and is more flexible long term. It does however yield slightly slower code, and more of it than then simple use of extends. My 2 Cents
What is the difference between extending a class and including it in PHP?
[ "", "php", "oop", "include", "extends", "" ]
I have a c# application which is launched under the System account on a machine and presents some dialogs to a user. When a regular user logs off the application is terminated as well. I would have thought that since its running under the system account it would continue to run despite the user not being logged in. Any info on why this happens would be appreciated.
If you want your app to keep running after the user has logged off (e.g. to maintain state for as long as the computer is running), you need a service. However, services are strongly discouraged from displaying UI. If you need both long-running and UI, consider writing a service to store your data, and an application that runs each time a user logs in that shows UI and interacts with the service.
Is your application a service? It sounds like what you want is a service. Note that you can run any process as any user, but that doesn't make it a service. If your process is implemented as a service, then it will continue running even with no users logged in.
Why does an application running as the system account on windows when logging off
[ "", "c#", "windows", "logoff", "" ]
Is is possible to only deserialize a limited number of items from a serialized array? Background: I have a stream that holds a serialized array of type T. The array can have millions of items but i want to create a preview of the content and only retrieve the, say, first one hundred items. My first idea was to create a wrapper around the input stream that limits the number of bytes, but there's no direct translation from the number of items of the array to the stream size.
No, this can't be done with standard .NET serialization. You'll have to invent your own storage format. For example, include a header with offsets of data chunks: ``` ---------------- <magic-value> <chunks-count> <chunk-size> <chunk-1-offset> <chunk-2-offset> --+ ... | ---------------- | ... | <chunk-1> | ... | ---------------- | ... <-+ <chunk-2> ... ----------------- ... ``` So in order to preview data (from any arbitrary position) you'll have to load at most `ceil(required-item-count/chunk-size)`. This will incur some overhead, but it's much better than loading the whole file.
What is the serializer? With `BinaryFormatter`, that would be very, very tricky. With xml, you could perhaps pre-process the xml, but that it very tricky. Other serializers exist, though - for example, with protobuf-net there is little difference between an array/list of items, and a sequence of individual items - so it would be pretty easy to pick of a finite sequence of items without processing the entire array. --- Complete protobuf-net example: ``` [ProtoContract] class Test { [ProtoMember(1)] public int Foo { get; set; } [ProtoMember(2)] public string Bar { get; set; } static void Main() { Test[] data = new Test[1000]; for (int i = 0; i < 1000; i++) { data[i] = new Test { Foo = i, Bar = ":" + i.ToString() }; } MemoryStream ms = new MemoryStream(); Serializer.Serialize(ms, data); Console.WriteLine("Pos after writing: " + ms.Position); // 10760 Console.WriteLine("Length: " + ms.Length); // 10760 ms.Position = 0; foreach (Test foo in Serializer.DeserializeItems<Test>(ms, PrefixStyle.Base128, Serializer.ListItemTag).Take(100)) { Console.WriteLine(foo.Foo + "\t" + foo.Bar); } Console.WriteLine("Pos after reading: " + ms.Position); // 902 } } ``` Note that `DeserializeItems<T>` is a lazy/streaming API, so it only consumes data from the stream as you iterate over it - hence the LINQ `Take(100)` avoids us reading the whole stream.
Deserializing only first x items of an array
[ "", "c#", ".net", "arrays", "serialization", "" ]
I am new to RESTful web services in WCF, but not new to WCF. I want to develop some simple RESTful web services in WCF which manually be accessed from a browser. Any good samples or documents to recommend? I am using C#.
Aaron Skonnard of PluralSight has a bunch of great little screencasts on Channel9 and is probably the best intro I've seen - you'll probably do well to have some WCF experience first - those coming from the world of SOAP will pick it up easier. <http://channel9.msdn.com/shows/Endpoint/endpointtv-Screencast-Building-RESTful-Services-with-WCF/> Also, stick this in Bing restful site:msdn.com **UPDATE** This answer still gets votes, so I thought it would be good to update it with recent changes. Basically, the WCF team have joined forces with the ASP.NET MVC community to bring REST to the Microsoft stack via ASP.NET MVC 4 Web API, so I guess the WCF REST stuff will not be developed from 2012 on. <http://wcf.codeplex.com/wikipage?title=WCF%20Web%20API%20is%20now%20ASP.NET%20Web%20API>
I wrote a short blog [post](http://toranbillups.com/blog/archive/2009/07/07/Getting-familiar-with-REST-and-WCF/) showing how to build REST services using WCF (sample code included). Keep in mind this example does not use the REST Toolkit released by Microsoft.
Samples for RESTful web services for WCF
[ "", "c#", "wcf", "rest", "" ]
I'm fairly new to the C programming language but I know that it is not standardized in the same way as Java. When performing a comparisson of the runtime of a algorithm, to keep the analysis fair, I need to call a method similar to Java's Array.sort(int []). ``` void qsort(void *base, size_t nmemb, size_t size, int (*compar)(const void *, const void *)); ``` Seems to be my best bet but I was wondering how I could find out the backend implementation for the version of C that I'm compiling to. How can I find out which implementation I am using? Does this depend on the Compiler or the includes? I am running I run Ubuntu and use the gcc compiler, all of my tools are obtained through the synaptic package manager or are installed by default. I hope this question makes sense! Kind regards, Gavin
qsort is part of the C stadard library, so a look at the libc code might help: <http://www.google.com/codesearch/p?hl=en#XAzRy8oK4zA/libc/stdlib/qsort.c&q=qsort> Hope this helps, Vlad
Run ``` man qsort ``` It gives the description of what qsort is doing. When you need to find out the information about a C function XXX, try to do `man XXX` first. Then, if there's not enough info, search for XXX on Google.
C equivalent to Arrays.sort from Java - qsort? (How do i find the nature of its implementation)
[ "", "java", "c", "sorting", "" ]
I've tried all manner of Python modules and they either escape too much or in the wrong way. What's the best way you've found to escape quotes (", ') in Python?
If it's part of a Database query you should be able to use a [Parameterized SQL Statement](https://web.archive.org/web/20100813151305/http://python.projects.postgresql.org/docs/0.8/driver.html). As well as escaping your quotes, this will deal with all special characters and will protect you from [SQL injection attacks](https://stackoverflow.com/questions/681583/sql-injection-on-insert).
Use `json.dumps`. ``` >>> import json >>> print json.dumps('a"bc') "a\"bc" ```
A good way to escape quotes in a database query string?
[ "", "python", "database", "escaping", "sql-injection", "" ]
> **Possible Duplicate:** > [How do I get the name of the current executable in C#?](https://stackoverflow.com/questions/616584/how-do-i-get-the-name-of-the-current-executable-in-c) An executable file loads an external library. Is there a way for the library to know the calling executable file? (I would have sworn I saw the answer to this elsewhere, but I can't seem to find it anymore)
*EDIT:* As of .NET 6, the recommended approach ([CA1839](https://learn.microsoft.com/en-us/dotnet/fundamentals/code-analysis/quality-rules/ca1839)) is to use [`System.Environment.ProcessPath`](https://learn.microsoft.com/en-us/dotnet/api/system.environment.processpath?view=net-6.0#system-environment-processpath) --- *Original answer:* ``` System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName ```
If you want the executable: ``` System.Reflection.Assembly.GetEntryAssembly().Location ``` If you want the assembly that's consuming your library (which could be the same assembly as above, if your code is called directly from a class within your executable): ``` System.Reflection.Assembly.GetCallingAssembly().Location ``` If you'd like just the file*name* and not the path, use: ``` Path.GetFileName(System.Reflection.Assembly.GetEntryAssembly().Location) ```
How do I find the current executable filename?
[ "", "c#", ".net", "" ]
When I ran my web application under Eclipse IDE everything worked fine. But when I exported my project into war-file and deployed in tomcat I've got following message: ``` java.lang.ClassNotFoundException: com.microsoft.sqlserver.jdbc ``` I've tried putting sqljdbc4.jar everywhere: * catalina-home\lib dir * WEB-INF\lib dir * both of them What I'am missing? Environment: tomcat 6.0.20, sql server 2005
Your driver class *name* is wrong. The exception text points to a package, not an actual driver class. And don't forget to restart Tomcat after changing the contents of various lib directories. **Edit:** Your IDE might use different configuration than your deployed war. Or fail with the same exception silently but the driver itself was already loaded by other means - then the actual connection just works.
The driver class is "com.microsoft.sqlserver.jdbc.SQLServerDriver". You've just missed the class name off the end.
ClassNotFoundException: com.microsoft.sqlserver.jdbc
[ "", "java", "jdbc", "" ]
IMHO to me OOPS, design patterns make sense and i have been able to apply them practically. But when it comes to **"generic programming /meta programming"** of the Modern C++ kind, i am left confused. -- Is it a new programming/design paradigm ? -- Is it just limited to "library development"? If not, What design/coding situations call for using meta programming/generic programming. -- Does using templates mean i am doing generic programming? I have googled a lot on this topic but do not grasp the BIG PICTURE fully. Also see this [post](http://discuss.fogcreek.com/joelonsoftware/default.asp?cmd=show&ixPost=85900). --- After reading dicussions here under, up till now, I am sure ( might still not be correct): a) Generic programming and meta programming are two different concepts.
Metaprogramming is a pretty exotic topic. It's interesting to learn about, it's a powerful tool, and occasionally you might find it useful. But it'll never be the most often used tool in your toolbox. Sometimes, you might want your code to act on a range of unrelated types with different properties, and that's where metaprogramming comes in. With a bit of trickery, you can write an overload of a function that is only available if the argument type is integral, or if it is a pointer, or if it is either type X, Y, or Z (perhaps ignoring constness on Z). It is essentially programming with types. Normally, your program can do things like take two numbers and produce a third number, or tell you whether a number satisfies some requirement. Metaprogramming can take two types and produce a third type, or tell you whether a type satisfies some requirement. And yes, it is probably mostly useful in library development. But then again, most code *could* be considered library code. You could say that everything outside your main() function is library code. Usually, if you want to solve a problem through metaprogramming, you'll probably want to use the relevant boost libraries to do the heavy lifting. Boost.TypeTraits and of course Boost.Mpl can really simplify things for you. But it's not something you *need* to know, and it's not something you're likely to need very often. Generic programming is related (and may in some cases use metaprogramming under the hood to become really generic, for example the standard library uses a touch of metaprogramming to turn raw pointers into valid iterators which is required for the "iterator" concept to be generic), but not entirely the same. And it is much more widely used. Every time you instantiate a `std::vector`, you use generic programming. Every time you use a pair of iterators to process a sequence of values, you use generic programming. Generic programming is just the idea that your code should be as generic as possible, and should work regardless of what types are put into it. A std::vector doesn't require the contained type to implement a "ICanBeContained" interface (remember how Java requires everything to be derived from Object in order for it to be stored in a container class? Which means primitive types get boxed, and that we lose type safety. That's not generic, and it's a pointless restriction.) The code to iterate over a sequence using iterators is generic, and works with *any* type of iterators, or even with plain pointers. Generic programming is very widely useful, and can often to a large extent replace OOP. (see the above example. Why would I write a container that required the contained types to implement an interface, if I can avoid that limitation?) Often, when you use interfaces in OOP, it is not to allow the type to change during runtime (although of course that happens from time to time too), but to allow you to swap in another type at compile-time (perhaps injecting a mock object during tests, rather than using the full-fledged implementation), or just to decouple two classes. Generic programming can do that, without having you do the tedious work of defining and maintaining the interface. In those cases, generic programming means you have to write and maintain less code, and you get better performance and better type-safety. So yes, you should definitely feel at home with generic programming. C++ isn't a very good OOP language. If you want to stick strictly with OOP, you should switch to Java or another more more OOP-fixated language. C++ *allows* you to write OO code, but it's often not the best solution. There's a reason why almost the entire standard library relies on generic programming, rather than OOP. There is very little inheritance or polymorphism in the standard library. They didn't need it, and the code became simpler to use and more powerful without it. And to answer your other questions, yes, Generic programming is pretty much a separate paradigm. Template metaprogramming is not. It is a fairly specific technique for manipulating the type system, and is very good at solving a small number of problems. To be considered a paradigm, I think it'd have to be much more generally useful, and approach you can use for basically *everything*, like functional, OO or generic programming. I think xtofl really nailed it: Generic programming is about making your code type-unaware. (A std::vector doesn't *care*, or *need to know* what type is stored in it. It just works.) Metaprogramming on the other hand, is about type computations. Given type T0 and T1, we can define a type T2, just like how we can, given integers N0 and N1, we can define a N2 that is the sum of N0 and N1. The Boost.Mpl library has an obvious example of this. In your normal code, if you have the integers N0, N1 and N2, you can create a std::vector containing these three values. I can then use some other algorithm to compute an index, and then extract the value stored at that location in the vector. Given types T0, T1 and T2, we can create a mpl::vector containing these three *types*. I can now use some other algorithm to compute an index at compile-time, and extract the *type* stored at that location in the vector.
You really have to differentiate between generic programming (which is kinda type-unaware) and metaprogramming, which is a perfectly legal way to do calculations within the type system. Generic programming is *very* useful when you find a generalizable pattern in a lot of code. If the difference in the pattern lies not only in variable values, but also in different types, generic programming is useful to refactor the code. Metaprogramming is applicable in a totally different domain. That domain is, indeed, quite new, and needs some exploring of your own. It *is* fun, too! One very useful, and common, metaprogramming pattern is the Traits/Policy concept.
When/Why ( if ever ) should i think about doing Generic Programming/Meta Programming
[ "", "c++", "templates", "metaprogramming", "generic-programming", "" ]
[This stackoverflow question](https://stackoverflow.com/questions/495051/c-naming-convention-for-enum-and-matching-property) has an interesting discussion on how to avoid giving enums and properties the same names so that you don't have code like this: ``` public SaveStatus SaveStatus { get; set; } ``` It seems the accepted answer suggested to use "State" for the enum and "Status" for the property: ``` public SaveStatus SaveState { get; set; } ``` But I think this is hard to read and not immediately clear what is what. Since this enum naming problem is a constant issue, I am considering simply always suffixing my enums with "Enum" so I would have this: ``` public SaveStatusEnum SaveStatus { get; set; } SaveStatus = SaveStatusEnum.Succeeded; ``` Does anyone do this? Happy with it? Solved this issue in another way?
From the [MSDN page for Property naming guidelines](http://msdn.microsoft.com/en-us/library/fzcth91k(VS.71).aspx): > *Consider creating a property with the same name as its underlying > type. For example, if you declare a property named Color, the type of > the property should likewise be Color.* I'd take that as a "no" :) **Edit:** If you dislike using the fully qualified name inside the class that declares the property, you can work around it: ``` using SaveStatusEnum = MyNamespace.SaveStatus; ... SaveStatus = SaveStatusEnum.SomeValue; ``` That way you can keep the enum name without the suffix, and limit the naming oddity to just that one class. :)
Does the .net Framework use Enum as a Suffix? [No.](http://msdn.microsoft.com/en-us/library/system.stringsplitoptions.aspx) That's why I do not use it either. Instead, I use words like Option (or Options if it's a Flags-Enum), Mode or similar. ``` public SaveStatusMode SaveStatus { get; set; } public SaveStatusOption SaveStatus { get; set; } public SaveStatusVariant SaveStatus { get; set; } ```
Is it recommended to suffix all C# enums with "Enum" to avoid naming conflicts?
[ "", "c#", "enums", "naming-conventions", "" ]
I have an Oracle table with data that looks like this: ``` ID BATCH STATUS 1 1 0 2 1 0 3 1 1 4 2 0 ``` That is, **ID** is the primary key, there will be multiple rows for each "batch," and each row will have a status code in the **STATUS** column. There are a bunch of other columns, but these are the important ones. I need to write a query which will summarize the **status codes** for each **batch**; there are three possible values that can go in the STATUS column, 0, 1, and 2, and I would like output that looks something like this: ``` BATCH STATUS0 STATUS1 STATUS2 1 2 1 0 2 1 0 0 ``` Those numbers would be counts; for batch 1, there are * 2 records where **STATUS** is set to 0 * 1 record where **STATUS** is set to 1, and * no records where **STATUS** is set to 0. For batch 2, there is * 1 record where **STATUS** is set to 0, and * no records where **STATUS** is set to 1 or 2. Is there a way that I can do this in one query, without having to rewrite the query for each status code? i.e. I can easily write a query like this, and run it three times: ``` SELECT batch, COUNT(status) FROM table WHERE status = 0 GROUP BY batch ``` I could run that, then run it again where status = 1, and again where status = 2, but I'm hoping to do it in one query. If it makes a difference, aside from the **STATUS** column there is *another* column that I might want to summarize the same way--another reason that I don't want to have to execute SELECT statement after SELECT statement and amalgamate all of the results.
``` select batch , count(case when status=1 then 1 end) status1 , count(case when status=2 then 1 end) status2 , count(case when status=3 then 1 end) status3 from table group by batch; ``` This is often called a "pivot" query, and I have written an article about how to generate these queries dynamically [on my blog](http://tonyandrews.blogspot.com/2004/10/pivot-queries.html). Version using DECODE (Oracle-specific but less verbose): ``` select batch , count(decode(status,1,1)) status1 , count(decode(status,2,1)) status2 , count(decode(status,3,1)) status3 from table group by batch; ```
``` select batch, sum(select case when status = 0 then 1 else 0 end) status0, sum(select case when status = 1 then 1 else 0 end) status1, sum(select case when status = 2 then 1 else 0 end) status2 from table group by batch ```
Oracle SQL Query to Summarize Statistics, using GROUP BY
[ "", "sql", "oracle", "group-by", "pivot", "" ]
I need to deserialize some JavaScript object represented in JSON to an appropriate C# class. Given the nice features of automatic properties, I would prefer having them in these classes as opposed to just having fields. Unfortunately, the .NET serialization engine (at least, by default) totally ignores automatic properties on deserialization and only cares about the backing field, which is obviously not present in the JavaScript object. Given that there's [no standard way to name backing fields](https://stackoverflow.com/questions/371398/problems-with-auto-properties) and to be honest I don't even want to bother with the "let's create a JavaScript object that looks like it had C# backing fields" approach as it sounds a bit dirty, the only way I could serialize JavaScript fields to C# auto-properties if I could force the serialization engine to somehow ignore the backing field and use the property directly. Unfortunately, I can't figure out how this is done or if this can be done at all. Any ideas would be appreciated. **EDIT**: Here's an example: Javascript: ``` function Cat() { this.Name = "Whiskers"; this.Breed = "Tabby"; } var cat = new Cat(); ``` This is then serialized to "{Name: 'Whiskers'}". The C# class: ``` [Serializable()] public class Cat { public string Name { get; set; } public string Breed { get; set; } } ``` And the deserialization code, that fails: ``` new DataContractJsonSerializer(typeof(Cat)).ReadObject(inputStream); ``` And it is apparent from the exception that it fails because it is looking for the backing field. **EDIT2**: Here's the exception, if that helps (no inner exceptions): > System.Runtime.Serialization.SerializationException > > "The data contract type 'Test.Cat' > cannot be deserialized because the > required data members > '`<Name>k__BackingField, <Breed>k__BackingField`' were not > found."
What's happening here is the deserializer is trying to guess the name of your backing fields. You can solve this by adding explicit mappings (DataContract/DataMember attributes) like this: ``` [DataContract] public class Cat { [DataMember] public string Name { get; set; } [DataMember] public string Breed { get; set; } } ```
You can do this with `JavaScriptSerializer` found in the `System.Web.Script.Serialization` namespace: ``` JavaScriptSerializer serializer = new JavaScriptSerializer(); Cat c = serializer.Deserialize<Cat>(jsonString); ``` I have POCO objects with automatic properties and this works just fine. EDIT: I wrote about [JSON Serializers in .NET](http://aleembawany.com/2009/05/22/json-serializers-in-net/) which compares this serializer with `DataContractJsonSerializer`.
C# automatic property deserialization of JSON
[ "", "c#", ".net", "json", "serialization", "automatic-properties", "" ]
So to sketch out our situation We have a html page(domain: hyves.nl) with an iframe in that iframe we load a php file (domain : atik.nl) in that php file we start a session and we embed our swf file (domain : atik.nl ) in our swf file we access a special page "calls.php" (domain: atik.nl) where we can get some special data. (that's why we needed to start a session in the first php file so that it can share some authorizing data) but beside that in our swf we want to connect to our amfphp gateway.php file (domain: atik.nl) but when i try to do that. Charles (web debugging proxy) tells me i have an 500 server internal error. Is it because amfphp doesn't do well with a session that is already started on the same domain ? because when i try to run my amfphp browser it works until i go to the dedicated page, my amfphp browser fails also until i restart my web browser. anybody any ideas?
I'm not sure what's at fault but it seems you need to synchronize the two sessions from hyves.nl and atik.nl . I think for debugging purposes you need to pass something to link these together. You need to look at the traffic being generated. You might look at the HTTP traffic with a tool like [HttpFox](https://addons.mozilla.org/en-US/firefox/addon/6647). It will show you the traffic generated between your various pages and even show you the payloads, though encoded AMFPHP ends up looking like binary noise.
If you're getting a 500 error, it should be showing in your Apache log... I'd look there for some hints, first.
Amfphp 500 internal server error (sessions)
[ "", "php", "session", "flash", "amfphp", "" ]
Is there a difference between `dir(…)` and `vars(…).keys()` in Python? (I hope there is a difference, because otherwise this would break the "one way to do it" principle... :)
Python objects usually store their instance variables in a dictionary that belongs to the object (except for slots). [`vars(x)`](https://docs.python.org/3/library/functions.html#vars) returns this dictionary (as does `x.__dict__`). [`dir(x)`](https://docs.python.org/3/library/functions.html#dir), on the other hand, returns a dictionary of `x`'s "attributes, its class's attributes, and recursively the attributes of its class's base classes." When you access an object's attribute using the dot operator, Python does a lot more than just look up the attribute in that objects dictionary. A common case is when `x` is an instance of class `C` and you call its method `m`: ``` class C: def m(self): print("m") x = C() x.m() ``` The method `m` is not stored in `x.__dict__`. It is an attribute of the class `C`. When you call `x.m()`, Python will begin by looking for `m` in `x.__dict__`, but it won't find it. However, it knows that `x` is an instance of `C`, so it will next look in `C.__dict__`, find it there, and call `m` with `x` as the first argument. So the difference between `vars(x)` and `dir(x)` is that `dir(x)` does the extra work of looking in `x`'s class (and its [bases](https://docs.python.org/3/library/stdtypes.html#class.__bases__)) for attributes that are accessible from it, not just those attributes that are stored in `x`'s own symbol table. In the above example, `vars(x)` returns an empty dictionary, because `x` has no instance variables. However, `dir(x)` returns ``` ['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'm'] ```
The documentation has this to say about [`dir`](https://docs.python.org/library/functions.html#dir): > Without arguments, return the list of names in the current local scope. *With an argument, attempt to return a list of valid attributes for that object.* And this about [`vars`](https://docs.python.org/library/functions.html#vars): > Without arguments, return a dictionary corresponding to the current local symbol table. *With a module, class or class instance object as argument (or anything else that has a `__dict__` attribute), returns a dictionary corresponding to the object’s symbol table.* If you don't see the difference, maybe this will show you more (grouped for easier reading): ``` >>> dir(list) ['__add__', '__class__', '__class_getitem__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort'] >>> vars(list).keys() dict_keys(['__repr__', '__hash__', '__getattribute__', '__lt__', '__le__', '__eq__', '__ne__', '__gt__', '__ge__', '__iter__', '__init__', '__len__', '__getitem__', '__setitem__', '__delitem__', '__add__', '__mul__', '__rmul__', '__contains__', '__iadd__', '__imul__', '__new__', '__reversed__', '__sizeof__', 'clear', 'copy', 'append', 'insert', 'extend', 'pop', 'remove', 'index', 'count', 'reverse', 'sort', '__class_getitem__', '__doc__']) ``` If you don't feel like reading through that, `dir` includes these attributes while `vars` does not: ``` >>> set(dir(list)) - vars(list).keys() {'__class__', '__delattr__', '__dir__', '__format__', '__init_subclass__', '__reduce__', '__reduce_ex__', '__setattr__', '__str__', '__subclasshook__'} ``` Note also that `dir()`'s output is sorted alphabetically, whereas `vars()`'s output is sorted by the order the attributes were defined in.
Difference between dir(…) and vars(…).keys() in Python?
[ "", "python", "" ]
I have a problem that sscanf solves (extracting things from a string). I don't like sscanf though since it's not type-safe and is old and horrible. I want to be clever and use some more modern parts of the C++ standard library. What should I use instead?
Try [`std::stringstream`](http://en.cppreference.com/w/cpp/io/basic_stringstream): ``` #include <sstream> ... std::stringstream s("123 456 789"); int a, b, c; s >> a >> b >> c; ```
For most jobs standard streams do the job perfectly, ``` std::string data = "AraK 22 4.0"; std::stringstream convertor(data); std::string name; int age; double gpa; convertor >> name >> age >> gpa; if(convertor.fail() == true) { // if the data string is not well-formatted do what ever you want here } ``` If you need more powerful tools for more complex parsing, then you could consider Regex or even Spirit from Boost.
What should I use instead of sscanf?
[ "", "c++", "scanf", "std", "" ]
I have a taskbar menu that when clicked is connected to a slot that gets the trigger event. Now the problem is that I want to know which menu item was clicked, but I don't know how to send that information to the function connected to. Here is the used to connect the action to the function: ``` QtCore.QObject.connect(menuAction, 'triggered()', menuClickedFunc) ``` I know that some events return a value, but triggered() doesn't. So how do I make this happen? Do I have to make my own signal?
Use a `lambda` Here's an example from the [PyQt book](http://www.qtrac.eu/pyqtbook.html): ``` self.connect(button3, SIGNAL("clicked()"), lambda who="Three": self.anyButton(who)) ``` By the way, you can also use `functools.partial`, but I find the `lambda` method simpler and clearer.
As already mentioned [here](https://stackoverflow.com/questions/8824311) you can use the lambda function to pass extra arguments to the method you want to execute. In this example you can pass a string obj to the function AddControl() invoked when the button is pressed. ``` # Create the build button with its caption self.build_button = QPushButton('&Build Greeting', self) # Connect the button's clicked signal to AddControl self.build_button.clicked.connect(lambda: self.AddControl('fooData')) def AddControl(self, name): print name ``` Source: [snip2code - Using Lambda Function To Pass Extra Argument in PyQt4](http://www.snip2code.com/Snippet/12165/)
PyQt sending parameter to slot when connecting to a signal
[ "", "python", "qt4", "pyqt", "" ]
I just reorganized the code for a project and now I'm getting errors I can't resolve. This header is included by a .cpp file trying to compile. ``` #include "WinMain.h" #include "numDefs.h" #include <bitset> class Entity { public: Entity(); virtual ~Entity(); virtual bitset<MAX_SPRITE_PIXELS> getBitMask(); virtual void getMapSection(float x, float y, int w, int h, bitset<MAX_SPRITE_PIXELS>* section); }; ``` I'm getting these compiler errors for the declaration of Entity::getBitMask(): error C2143: syntax error : missing ';' before '<' error C2433: 'Entity::bitset' : 'virtual' not permitted on data declarations error C4430: missing type specifier - int assumed. Note: C++ does not support default-int error C2238: unexpected token(s) preceding ';' There are more similar errors for the next line as well. It seems like bitset isn't getting included but it clearly is? I can't figure out what's going wrong. WinMain.h includes windows.h, and numDefs.h includes nothing. Using MS Visual C++ 2008.
Declare the bitset as `std::bitset<MAX_SPRITE_PIXELS>`.
The [`bitset`](http://www.cplusplus.com/reference/stl/bitset/) template is defined in the `std::` namespace, so you either need to reference it by it's full name `std::bitset` or add `using namespace std;` somewhere before the class declaration.
Trouble compiling a header file in VC++
[ "", "c++", "visual-c++", "bitset", "" ]
I've got a table of 5,651,744 rows, with a primary key made of 6 columns (int x 3, smallint, varchar(39), varchar(2)). I am looking to improve the performance with this table and another table which shares this primary key plus an additional column added but has 37m rows. In anticipation of adding a column to create the hash key, I did an analysis and found 18,733 collisions. ``` SELECT SUM(CT) FROM ( SELECT HASH_KEY ,COUNT(*) AS CT FROM ( SELECT CHECKSUM(DATA_DT_ID, BANK_NUM, COST_CTR_NUM, GL_ACCT_NUM, ACCT_NUM, APPN_CD) AS HASH_KEY FROM CUST_ACCT_PRFTBLT ) AS X GROUP BY HASH_KEY HAVING COUNT(*) > 1 ) AS Y SELECT COUNT(*) FROM CUST_ACCT_PRFTBLT ``` It's about twice as bad with `BINARY_CHECKSUM()` Does this seem too high (.33%) given the smaller relative amount of the destination space I'm covering? And if the collisions are this high, is there a benefit in joining on this manufactured key first in joins for the cost of the extra 4 bytes per row, given that you still have to join on the regular columns to handle the occasional collision?
I don't see where adding a checksum will get you anything with that level of collisons. Even 1 collision is too many as it would cause you to join to the wrong data. If you can't guarantee to be joining to the correct record, it is pointless if it improves performance but messes with data integrity. This appears to be financial data, so you had better be really sure that your queries won't return bad results. You could actually end up debiting or crediting the wrong accounts if there are any collisions. If you do go this route, Marc is right that you should if at all possible pre-compute (Adding a computation that has to happen to every record in multimillion record tables is not likely to improve performance in my experience). Possibly if you can do the precomputed column (and you'll need triggers to keep it up-date) then you may not need to join to all six of the other columns to ensure no collisions. Then possibly you might have imporved performance. All you can do is test your theory. But be very sure you don't have any collisions. Have you considered using a surrogate key and then a unique index on the six natural key fields instead? Then you could join on the surrogate key and likely that would improve performance a good bit. It can't be efficient to join on six columns (one a varchar) instead of one surrogate key. I realize from the size of the data, this might be harder to refactor than in a non-production system, but really it might be worth the down time to permananently fix persistent performance problems. Only you can say how complex a change this would be and how hard it would be to change all the sps or queries to a better join. However, it might be feasible to try.
What I've seen a lot of folks glossing over thus far is that `CHECKSUM` has a ton of collisions, by [Microsoft's own admission](http://msdn.microsoft.com/en-us/library/ms189788.aspx). It's even worse than `MD5`, which has its fair share of meaningful collisions. If you're looking to get a hash column, consider using [`HASHBYTES`](http://msdn.microsoft.com/en-us/library/ms174415.aspx) with `SHA1` specified. `SHA1` has a lot less meaningful collisions than `MD5` or `CHECKSUM`. Therefore, `CHECKSUM` should never be used to determine if a row is unique, but rather, it's a quick check on the fidelity of two values. Therefore, your collision rate should be 0% with `HASHBYTES`, unless you have duplicate rows (which, being a PK, should never happen). Keep in mind that `HASHBYTES` will truncate anything larger than 8000 bytes, but your PK is a lot less than that (all concatenated), so you shouldn't have any trouble.
CHECKSUM() collisions in SQL Server 2005
[ "", "sql", "sql-server-2005", "checksum", "hash-collision", "" ]
As the title says I need a way to stop or interrupt a thread that is blocked waiting on an input from the socket.
[Thread.interrupt()](http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Thread.html#interrupt()) should be the method you're looking for. Be sure that your input-accessing methods also check for InterruptedException and ClosedByInterruptException. Also look at the corresponding [page in the Sun Concurrency Tutorial](http://java.sun.com/docs/books/tutorial/essential/concurrency/interrupt.html), as another solution suggests.
You could simply close() the IO stream/socket from another thread. Then, you could check on a volatile boolean field if the resulting IOException is due the close or something else. I think the close might result in an `java.net.SocketException: Socket closed` exception.
Stop/Interrupt threads blocked on waiting input from socket
[ "", "java", "multithreading", "" ]
I need to build an XML document from a Java object hierarchy. Both the Java classes and the XML format are fixed. So I can't use an XML serializer like [XStream](http://xstream.codehaus.org/): it bases the XML format on the Java classes. Likewise, a Java XML binding technology like [JAXB](http://jaxb.java.net/) won't work, since it creates Java classes from the XML schema [ed: but see below]. I need a manual approach. The low-tech StringBuilder route results in fragile and buggy code (at least for me!). An API like [JAXP](https://jaxp.dev.java.net/) or [JDOM](http://www.jdom.org/index.html) leads to much more robust code, but these are pretty verbose. [Groovy](http://groovy.codehaus.org/) has an elegant [MarkupBuilder](http://groovy.codehaus.org/Creating+XML+using+Groovy%27s+MarkupBuilder): ``` def writer = new StringWriter() def xml = new MarkupBuilder(writer) xml.records() { car(name:'HSV Maloo', make:'Holden', year:2006) { country('Australia') record(type:'speed', 'Production Pickup Truck with speed of 271kph') } car(name:'P50', make:'Peel', year:1962) { country('Isle of Man') record(type:'size', 'Smallest Street-Legal Car at 99cm wide and 59 kg') } } ``` Other languages (eg. [Ruby](http://builder.rubyforge.org/)) have even better ones, though I want to stay with pure Java. There do seem to be some new XML builders for Java, such as [practicalxml](http://sourceforge.net/projects/practicalxml/) and James Murty's [xmlbuilder](http://code.google.com/p/java-xmlbuilder/). What are the more elegant approaches for building XML documents in Java? **Summary:** Jon Doe suggested [dom4j](http://dom4j.sourceforge.net/) and [jdom](http://www.jdom.org/index.html). CurtainDog recommended using JAXB anyway, and jherico clued me in that this was a pertinant suggestion: you could then use Dozer to map between my current JavaBeans and the JAXB JavaBeans. thaggie recommends [JIBX](http://jibx.sourceforge.net/) and agreed with CurtainDog and jherico that binding technologies are actually practical. StaxMan recommends [StaxMate](http://staxmate.codehaus.org/Tutorial). Of the stuff I've looked at, practicalxml and James Murty's xmlbuilder seem to be the most concise builders, though are rather newish. The binding technologies like JAXB seem to offer extra safety/automation. Of the mainstream choices, [dom4j](http://dom4j.sourceforge.net/) seems decent, though still kind of verbose. It offers a "fluent interface" (mutators return a reference to the mutated object so they can be chained together), which I like: ``` public Document createDocument() { Document document = DocumentHelper.createDocument(); Element root = document.addElement( "root" ); Element author2 = root.addElement( "author" ) .addAttribute( "name", "Toby" ) .addAttribute( "location", "Germany" ) .addText( "Tobias Rademacher" ); Element author1 = root.addElement( "author" ) .addAttribute( "name", "James" ) .addAttribute( "location", "UK" ) .addText( "James Strachan" ); return document; } ``` For conciseness, you could wrap a thin facade over this API to provide terse synonyms for some of these methods (eg, attr() instead of addAttribute()). Thanks all! P.S.: Stephan Schmidt worked on a Java [MarkupBuilder](http://codemonkeyism.com/the-best-markup-builder-i-could-build-in-java/), though seems not to have published it.
dom4j or jdom are probably the most elegant, you can write code how you like it. Dom4j has builders if I recall, and yes the code is more verbose. ``` Element.addElement("x").setAttribute("x", "y").xxxxx; ```
Take a look at [XOM](http://www.xom.nu/). It's fast, simple, correct, and isn't verbose.
How to build an XML document in Java concisely?
[ "", "java", "xml", "builder", "" ]
Consider the following. I have two exported constants as follows: ``` // somefile.h extern const double cMyConstDouble; extern const double cMyConstDouble2; ``` and ``` // somefile.cpp const double cMyConstDouble = 3.14; const double cMyConstDouble2 = 2.5*cMyConstDouble; ``` These constants are now referenced some place else to define two static (locally visible) constants: ``` // someotherfile.cpp #include "somefile.h" static const double cAnotherDouble = 1.1*cMyConstDouble; static const double cAnotherDouble2 = 1.1*cMyConstDouble2; printf("cAnotherDouble = %g, cAnotherDouble2 = %g\n", cAnotherDouble, cAnotherDouble2); ``` Which yields the following output: ``` cAnotherDouble = 3.454, cAnotherDouble2 = 0 ``` Why is the second double 0? I'm using .NET 2003 C++ compiler (13.10.3077).
Because cMyConstDouble is declared as extern, compiler is not able to assume its value and does not generate a compile time initialization for cMyConstDouble2. As the cMyConstDouble2 is not compile time initialized, its order of initialization relative to cAnotherDouble2 is random (undefined). See [static initialization fiasco](http://www.parashift.com/c%2B%2B-faq-lite/ctors.html#faq-10.12) for more information.
I'm not going to dip my toe into the issues of extern here, but why do you simply not place the consts in the appropriate header files and forget about "exporting" them using extern? This is how consts are supposed to be used in C++, and why they have internal linkage. In other words: ``` // someheader.h const double cMyConstDouble = 3.14; const double cMyConstDouble2 = 2.5*cMyConstDouble; ``` and #include that file wherever you need them.
Why do some const variables referring to some exported const variables get the value 0?
[ "", "c++", "initialization", "constants", "double", "extern", "" ]
This code is always alerting out `"null"`, which means that the string does not match the expression. ``` var pattern = "^\w+@[a-zA-Z_]+?\.[a-zA-Z]{2,3}$"; function isEmailAddress(str) { str = "azamsharp@gmail.com"; alert(str.match(pattern)); return str.match(pattern); } ```
If you define your regular expression as a string then all backslashes need to be escaped, so instead of '\w' you should have '\\w'. Alternatively, define it as a regular expression: ``` var pattern = /^\w+@[a-zA-Z_]+?\.[a-zA-Z]{2,3}$/; ``` --- BTW, please don't validate email addresses on the client-side. Your regular expression is way too simple to pass for a solid implementation anyway. See the real thing here: **<http://www.ex-parrot.com/~pdw/Mail-RFC822-Address.html>**
this is the one i am using on my page. <http://www.zparacha.com/validate-email-address-using-javascript-regular-expression/> `/^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,6}$/`
JavaScript Regular Expression Email Validation
[ "", "javascript", "regex", "" ]
I want to create a website that the login system shouldn't be handled by cookies, but on (a) table(s) in the local (on the server) SQL DB. Is there a way to do it? Even no partial way? What and where should I save instead of the cookie???
ASP.NET uses Session cookies by default to track user requests. If you use Cookieless sessions, you will find the Session ID being appended in all requests from the browser. In many scenarios, this could also be unacceptable. Even if you decide to hit the database and check for a "LoggedIn" flag upon each request, you still need some way to identify the incoming request as belonging to a particular user. This could be in the form of encrypted values in hidden fields, depending on your security scenario. That said, it's not a much better method than the use of cookies, because *any* data that comes from the client has the potential to have been tampered with. Personally, I think Cookies are great to track user requests as long as you encrypt them properly.
You still need some way of telling the users apart. If you don't use cookies, then you will have to transfer that information in url or allow only one user from a single ip address (this is really stupid) ... or something else. Cookies are not that bad :-).
How to create a database driven login system
[ "", "asp.net", "sql", "cookies", "authentication", "database-driven", "" ]
I'm interested in maintaining a [Maven](http://en.wikipedia.org/wiki/Apache_Maven) 2 repository for my organization. What are the some of the pointers and pitfalls that would help. What are guidelines for users to follow when setting up standards for downloading from or publishing their own artifacts to the repository when releasing their code? What kinds of governance/rules do you have in place for this type of thing? What do you include about it in your developer's guide/documentation? **UPDATE**: We've stood up Nexus and have been very happy with it - followed most of Sal's guidelines and haven't had any trouble. In addition, we've restricted deploy access and automated build/deployment of snapshot artifacts through a Hudson CI server. Hudson can analyze all of the upstream/downstream project dependencies, so if a compilation problem, test failure, or some other violation causes the build to break, no deployment will occur. Be weary of doing snapshot deployments in Maven2/Maven3, as the metadata has changed between the two versions. The "Hudson only" snapshot deployment strategy will mitigate this. We do not use the Release Plugin, but have written some plumbing around the [Versions plugin](http://mojo.codehaus.org/versions-maven-plugin/) when going to move a snapshot to release. We also use m2eclipse and it seems to work very well with Nexus, as from the settings file it can see Nexus and knows to index artifact information for lookup from there. (Though I have had to tweak some of those settings to have it fully index our internal snapshots.) I'd also recommend you deploy a source jar with your artifacts as a standard practice if you're interested in doing this. We configure that in a super POM. I've come across [this Sonatype whitepaper](http://www.sonatype.com/resources/whitepapers/repository-management-stages-of-adoption) which details different stages of adoption/maturity, each with different usage goals for a Maven Repository manager.
I would recommend setting up one nexus server with at least four repositories. I would not recommend artifactory. The free version of nexus is perfectly fine for a dev team of less than 20 in less than three groups. If you have more users than that, do yourself a favor and pay for the Sonatype release. The LDAP integration pays for itself. 1. Internal Release 2. Internal Snapshot 3. **Internal 3rd Party** for code used in house that comes from outside sources, or for endorsed 3rd party versions. Put the JDBC drivers, javax.\* stuff and stuff from clients and partners here. 4. **External Proxies** common proxy for all the usual sources like m2, codehaus etc Configure Nexus to do the following for internal repos 1. Delete old Snapshots on regular intervals 2. Delete Snapshots on release 3. Build index files. This speeds up local builds too **Have a common settings.xml file that uses these four and only these four sources.** If you need to customize beyond this try to keep a *common part* of the settings file and use *profiles for the differences.* Do not let your clients just roll their own settings or you will end up with code that builds on one machine but not on any other machine. **Provide a common proxy for your clients.** In Nexus, you can add a bunch of proxies to the common Maven sources (Apache, JBoss, Codehaus) and have a single proxy exposed to the internal clients. This makes adding and removing sources from your clients much easier. **Don't mix Internal and 3rd party artifacts** in the same repository. Nexus allows you to add jars to an internal repository via a web gui. I recommend this as the way of adding your JDBC drivers and other external code to 3rd party. The UI is quite nice to use when compared to most *enterprise software*. **Define a common parent POM** that defines the Internal snapshot and release repos via the **distributionManagement** tag. I know lots of people tell you not to do this. And while I freely admit that there are all kinds of problems with doing this, it works out OK if the clients will only be building releases and snapshots to be deployed to a single internal repository. **If you have an existing mis-managed Maven repository**, create a 5th repos called *Legacy* and put the whole repos there. Set up a cron task to delete old files from legacy once they are a year old. That gives everyone a year to move off of it and update their poms. **Establish an easy to stick to naming convention for internal artifacts.** I prefer GroupID of *Department.Function.Project* and an ArtifactId for that *componentName*. For internal repositories, com/org/net and the company name are likely to be irrelevant. And wrong if the company changes its name. It is far less likely that the sales, accounting or inventory department will be renamed.
Definitely use [Nexus](http://nexus.sonatype.org/). :P I've used both Nexus and Artifactory. The interface for Nexus is a lot more robust, it's a lot more configurable, and of course, written by [Sonatype](http://www.sonatype.com/), who repesents pretty much everything Maven well. That being said, Artifactory is decent and workable. * [A review of Nexus vs. Artifactory](http://cfossguy.blogspot.com/2008/09/my-artifactory-versus-nexus-experience.html) * [Oh my! Of course, here's a SO quesiton about the matter.](https://stackoverflow.com/questions/364775/should-we-use-nexus-or-artifactory-for-a-maven-repo) * [Sonatype does a feature comparison](http://www.sonatype.com/people/2009/01/contrasting-nexus-and-artifactory/) * [jFrog (maker of Artifactory) does a feature comparison](http://blogs.jfrog.org/2009/01/contrasting-artifactory-and-nexus.html)
Tips for maintaining an internal Maven Repository?
[ "", "java", "repository", "maven-2", "" ]
In a response to this [question](https://stackoverflow.com/questions/920158/avoid-circular-reference-in-domain-model) [runefs](https://stackoverflow.com/users/112407/runefs) suggested that "unless you have a very specific reason for using IList you should considere IEnumerable". Which do you use and why?
`IEnumberable<T>` is read-only, you have to reconstruct the collection to make changes to it. On the other hand, `IList<T>` is read-write. So if you expect a lot of changes to the collection, expose `IList<T>` but if it's safe to assume that you won't modify it, go with `IEnumerable<T>`.
Always use the most restrictive interface that provides the features you need, because that gives you the most flexibility to change the implementation later. So, if `IEnumerable<T>` is enough, then use that... if you need list-features, use `IList<T>`. And preferably use the strongly typed generic versions.
Which interface should I expose a List<T> via?
[ "", "c#", ".net", "c#-3.0", "interface", "ilist", "" ]
I'm pretty sure this is not a duplicate so bear with me for just a minute. How can I programatically (C#) ZIP a file (in Windows) without using any third party libraries? I need a native windows call or something like that; I really dislike the idea of starting a process, but I will if I absolutely have to. A PInovke call would be much better. Failing that, let me tell you what I'm really trying to accomplish: I need the ability to let a user download a collection of documents in a single request. Any ideas on how to accomplish this?
Are you using .NET 3.5? You could use the [`ZipPackage`](http://msdn.microsoft.com/en-us/library/system.io.packaging.zippackage%28v=VS.90%29.aspx) class and related classes. Its more than just zipping up a file list because it wants a MIME type for each file you add. It might do what you want. I'm currently using these classes for a similar problem to archive several related files into a single file for download. We use a file extension to associate the download file with our desktop app. One small problem we ran into was that its not possible to just use a third-party tool like 7-zip to create the zip files because the client side code can't open it -- ZipPackage adds a hidden file describing the content type of each component file and cannot open a zip file if that content type file is missing.
> How can I programatically (C#) ZIP a file (in Windows) without using > any third party libraries? If using the 4.5+ Framework, there is now the [ZipArchive](http://msdn.microsoft.com/en-us/library/system.io.compression.ziparchive%28v=vs.110%29.aspx) and [ZipFile](http://msdn.microsoft.com/en-us/library/system.io.compression.zipfile%28v=vs.110%29.aspx) classes. ``` using (ZipArchive zip = ZipFile.Open("test.zip", ZipArchiveMode.Create)) { zip.CreateEntryFromFile(@"c:\something.txt", "data/path/something.txt"); } ``` You need to add references to: * **System.IO.Compression** * **System.IO.Compression.FileSystem** For .NET Core targeting net46, you need to add dependencies for * **System.IO.Compression** * **System.IO.Compression.ZipFile** Example project.json: ``` "dependencies": { "System.IO.Compression": "4.1.0", "System.IO.Compression.ZipFile": "4.0.1" }, "frameworks": { "net46": {} } ``` For .NET Core 2.0, just adding a simple using statement is all that is needed: * **using System.IO.Compression;**
How do I ZIP a file in C#, using no 3rd-party APIs?
[ "", "c#", "compression", "zip", "download", "" ]
Maybe not really big, but a hundred frames or something. Is the only way to load it in by making an array and loading each image individually? load\_image() is a function I made which loads the images and converts their BPP. ``` expl[0] = load_image( "explode1.gif" ); expl[1] = load_image( "explode2.gif" ); expl[2] = load_image( "explode3.gif" ); expl[3] = load_image( "explode4.gif" ); ... expl[99] = load_image( "explode100.gif" ); ``` Seems like their should be a better way.. at least I hope.
A common technique is spritesheets, in which a single, large image is divided into a grid of cells, with each cell containing one frame of an animation. Often, all animation frames for any game entity are placed on a single, sometimes huge, sprite sheet.
Instead of loading as a grid, stack all the frames in one vertical strip (same image). Then you only need to know how many rows per frame and you can set a pointer to the frame row offset. You end up still having contiguous scan lines that can be displayed directly or trivially chewed off into separate images.
Is there a better way to load in a big animation?
[ "", "c++", "user-interface", "sdl", "sdl-image", "" ]
Using PHP (other languages, using common built-ins are welcome), how can I get a random (or pseudo-random) number that does NOT match a certain criteria? IE: I want `$x = rand(0, 99)` but only if `($x % 9) != 0`. What is a clean acceptable way to constrain random numbers to a criteria like that? As an example, using a `while()` loop, and possibly `break`ing when we have something that meets our criteria, then using the random number after the loop?: ``` while ( ($rand_key = array_rand($array_of_items)) && ($rand_key % 9 == 0) ) { // Do nothing? } ``` Or something like: ``` while ( $rand_key = array_rand($array_of_items) ) { if ( $rand_key % 9 == 0 ) { break; } } ``` Or is there a more concise or appropriate way to accomplish this?
One of the rare cases where a do-while loop actually helps ``` $testData = array( 7, 8, 9 ); do { $rand = array_rand( $testData ); } while ( $testData[$rand] % 9 == 0 ); echo $testData[$rand]; ```
Is that your exact usage case, or just an example? If you're trying (in particular) to get numbers from 0 to 99 excluding exact multiples of 9, I can think of a couple of ways to avoid the awkward looping. People don't like to loop while generating random numbers because you could loop forever. (But of course that won't happen unless you're the extremely unlucky type--the sort of person who happens to get himself in gunfights with Clint Eastwood in spaghetti westerns.) 1. You could have a lookup table that remaps the random numbers you get into the ones you want. 2. Generate 0-88 randomly. Multiply the result by 9 and divide it by 8 and get the integer result (floor, not round). Then add 1. Both of these have predictable timing.
Get random number that does/doesn't match criteria (PHP)
[ "", "php", "random", "" ]
I'm trying to profile a C++ application, that I did not write, to get a sense for where the major computation points are. I'm not a C++ expert and even less so C++ debugging/profiling expert. I believe I am running into a (common?) problem with dynamic libraries. I compile link to [Google CPU Profiler](http://google-perftools.googlecode.com/svn/trunk/doc/cpuprofile.html) using (OS X, G++): ``` env LIBS=-lprofiler ./configure make make install ``` I then run profile the installed application (jags) with: ``` env CPUPROFILE=./jags.prof /usr/local/bin/jags regression.cmd pprof /usr/local/bin/jags jags.prof ``` Unfortunately, I get the error: ``` pprof /usr/local/bin/jags jags.prof Can't exec "objdump": No such file or directory at /usr/local/bin/pprof line 2833. objdump /System/Library/Frameworks/Accelerate.framework/Versions/A/ Frameworks/vecLib.framework/Versions/A/libLAPACK.dylib: No such file or directory ``` The program dynamically links to libLAPACK.dylib. So `prof` does not seem to understand it (?). I thought about trying to statically link, but the documents associated with the program say that it is impossible to statically link in LAPACK or BLAS (two required libraries). Is there a way to have the profiler ignore libLAPACK? I'm okay if it doesn't sample within libLAPACK. Or how might I get profiling to work?
This error was caused by jags being a shell script, that subsequently called profilable code. ``` pprof /usr/local/bin/REAL_EXEC jags.prof ``` fixes the problem.
I don't see a clean way to do it, but maybe there's a hacky workaround -- what happens if you hack the pprof perl script (or better a copy thereof;-), line 2834, so that instead of calling `error` it emits the message and then does `return undef;`?
Profiling C++ with Google Perf tools and Dynamic Libraries
[ "", "c++", "debugging", "profiling", "" ]
When I should use a `while` loop or a `for` loop in Python? It looks like people prefer using a `for` loop (for brevity?). Is there any specific situation which I should use one or the other? Is it a matter of personal preference? The code I have read so far made me think there are big differences between them.
Yes, there is a huge difference between while and for. The **for** statement iterates through a collection or iterable object or generator function. The **while** statement simply loops until a condition is False. It isn't preference. It's a question of what your data structures are. Often, we represent the values we want to process as a `range` (an actual list), or `xrange` (which generates the values) (**Edit**: In Python 3, `range` is now a generator and behaves like the old `xrange` function. `xrange` has been removed from Python 3). This gives us a data structure tailor-made for the **for** statement. Generally, however, we have a ready-made collection: a set, tuple, list, map or even a string is already an iterable collection, so we simply use a **for** loop. In a few cases, we might want some functional-programming processing done for us, in which case we can apply that transformation as part of iteration. The `sorted` and `enumerate` functions apply a transformation on an iterable that fits naturally with the **for** statement. If you don't have a tidy data structure to iterate through, or you don't have a generator function that drives your processing, you must use **while**.
`while` is useful in scenarios where the break condition doesn't logically depend on any kind of sequence. For example, consider unpredictable interactions: ``` while user_is_sleeping(): wait() ``` Of course, you *could* write an appropriate iterator to encapsulate that action and make it accessible via `for` – but how would that serve readability?¹ In all other cases in Python, use `for` (or an appropriate higher-order function which encapsulate the loop). ¹ assuming the `user_is_sleeping` function returns `False` when false, the example code could be rewritten as the following `for` loop: ``` for _ in iter(user_is_sleeping, False): wait() ```
When to use "while" or "for" in Python
[ "", "python", "loops", "" ]
I'm trying to create a soap connection to Magento's web services, however I'm getting an error when I try and create an instance of the soap client class. I can view the wsdl file in firefox without problems and I can watch php make the request for the wsdl in apaches logs but it still fails. Nusoap can connect. ``` $proxy = new SoapClient('someaddress?wsdl'); ``` The error is ``` <b>Fatal error</b>: Uncaught SoapFault exception: [HTTP] Error Fetching http headers in /home/sites/xxx/xxx_main/system/application/views/contentpage_templates/gift_service.php:29 Stack trace: [internal function]: SoapClient-&gt;__doRequest('&lt;?xml version=&quot;...', 'http://cornishw...', 'urn:Mage_Api_Mo...', 1, 0) [internal function]: SoapClient-&gt;__call('call', Array) /home/sites/xxx/xxx_main/system/application/views/contentpage_templates/gift_service.php(29): SoapClient-&gt;call(NULL, 'catalog_categor...', 5, 'giftshop') /home/sites/xxx/xxx_main/system/application/libraries/MY_Loader.php(586): include('/home/sites/cor...') /home/sites/xxx/xxx_main/system/application/libraries/MY_Loader.php(228): MY_Loader-&gt;_ci_load(Array, '') /home/sites/xxx/xxx_main/system/application/modules/contentpage/controllers/contentpage.php(44): MY_Loader-&gt;view('contentpage_tem...', false, true) [internal function]: Contentpage-&gt;index() /home/sites/xxx in <b>/home/sites/xxx/xxx_main/system/application/views/contentpage_templates/gift_service.php</b> on line <b>29</b> ``` Thanks
Try to set : ``` default_socket_timeout = 120 ``` in your `php.ini` file.
Did you try adding ``` 'trace'=>1, ``` to SoapClient creation parameters and then: ``` var_dump($client->__getLastRequest()); var_dump($client->__getLastResponse()); ``` to see what is going on?
Uncaught SoapFault exception: [HTTP] Error Fetching http headers
[ "", "php", "soap", "magento", "wsdl", "" ]
I have a third-party jar file that comes with the javadocs for only part of the API. Is there a way to reverse engineer the jar file to obtain a complete listing of classes and methods?
[`jar tf`](http://docs.oracle.com/javase/7/docs/technotes/tools/windows/jar.html) will list the contents for you. [`javap`](http://docs.oracle.com/javase/7/docs/technotes/tools/windows/javap.html) will allow you to see more details of the classes (see the tools guide). For instance if you have a class named `mypkg.HelloWorld` in a jar `myjar.jar` then run it like ``` javap -classpath myjar.jar mypkg.HelloWorld ``` However, are you sure you want to be using these unpublished APIs? It's usually a really bad idea.
As Scott said, you can use Eclipse to get a lot of what you're looking for. I would recommend getting the [JadClipse plugin](http://jadclipse.sourceforge.net/wiki/index.php/Main_Page) which will decompile the .class files on the fly and show you actual Java code as you browse the classes in the IDE.
How to get method signatures from a jar file?
[ "", "java", "jar", "reverse-engineering", "method-signature", "" ]
I'm currently using the following code to achieve this, but is seems there should be something better... suggestions? It just seems to me there should be a way to skip the foreach... ``` Dictionary<string,string> getValidIds(Dictionary<string,string> SalesPersons,List<string> ids) { Dictionary<string,string> o = new Dictionary<string,string>(); var ie = SalesPersons.Where<KeyValuePair<string, string>>(t => ids.Contains(t.Key)); foreach (var i in ie) { o.Add(i.Key, i.Value); } return o; } ```
Seems to be a lot of fussing about looking things up in the List. If the list only contains a few elements, then no big deal. If the List contains thousands of elements, you're going to want O(1) lookups into it. HashSet can provide this. ``` Dictionary<string, string> getValidIds( Dictionary<string, string> SalesPersons, List<string> ids ) { HashSet<string> idsFast = new HashSet<string>(ids); Dictionary<string, string> result = SalesPersons .Where(kvp => idsFast.Contains(kvp.Key)) .ToDictionary(kvp => kvp.Key, kvp => kvp.Value) return result; } ```
Pretty sure you could just call ToDictionary on the result of the Where call: ``` Dictionary<string, string> GetValidIds(Dictionary<string, string> salesPersons, IList<string> ids) { return salesPersons .Where(p => ids.Contains(p.Key)) .ToDictionary(p => p.Key, p => p.Value); } ```
When using a LINQ Where clause on a Dictionary, how can I return a dictionary of the same type?
[ "", "c#", "linq", "optimization", "" ]
In the following code (inspired by [this](http://www.daniweb.com/code/snippet508.html) snippet), I use a single event handler `buttonClick` to change the title of the window. Currently, I need to evaluate if the Id of the event corresponds to the Id of the button. If I decide to add 50 buttons instead of 2, this method could become cumbersome. Is there a better way to do this? ``` import wx class MyFrame(wx.Frame): def __init__(self): wx.Frame.__init__(self, None, wx.ID_ANY, 'wxBitmapButton', pos=(300, 150), size=(300, 350)) self.panel1 = wx.Panel(self, -1) self.button1 = wx.Button(self.panel1, id=-1, pos=(10, 20), size = (20,20)) self.button1.Bind(wx.EVT_BUTTON, self.buttonClick) self.button2 = wx.Button(self.panel1, id=-1, pos=(40, 20), size = (20,20)) self.button2.Bind(wx.EVT_BUTTON, self.buttonClick) self.Show(True) def buttonClick(self,event): if event.Id == self.button1.Id: self.SetTitle("Button 1 clicked") elif event.Id == self.button2.Id: self.SetTitle("Button 2 clicked") application = wx.PySimpleApp() window = MyFrame() application.MainLoop() ```
You could give the button a name, and then look at the name in the event handler. When you make the button ``` b = wx.Button(self, 10, "Default Button", (20, 20)) b.myname = "default button" self.Bind(wx.EVT_BUTTON, self.OnClick, b) ``` When the button is clicked: ``` def OnClick(self, event): name = event.GetEventObject().myname ```
Take advantage of what you can do in a language like Python. You can pass extra arguments to your event callback function, like so. ``` import functools def __init__(self): # ... for i in range(10): name = 'Button %d' % i button = wx.Button(parent, -1, name) func = functools.partial(self.on_button, name=name) button.Bind(wx.EVT_BUTTON, func) # ... def on_button(self, event, name): print '%s clicked' % name ``` Of course, the arguments can be anything you want.
Best way to get the name of a button that called an event?
[ "", "python", "user-interface", "events", "event-handling", "wxpython", "" ]
I am writing a set of classes: RAR, ZIP and Trip. They all share a common interest: they are archive formats. So, I initially thought about doing this: 1) Write a base abstract class ``` abstract class Archive {} ``` and place it at "libraries/archive/archive.php". 2) Write zip, rar and trip classes ``` class Archive_Zip extends Archive {} ``` and place them at "libraries/archive/zip.php" 3) Access the specific class (e.g. the Zip) like this ``` $this->archive->zip->... ``` This was my initial approach. However, do you think this is a good approach? Should I even abstract them at the first place? What are the pros and cons of just writing a "libraries/zip.php" file (and all others separately)? Do you have any suggestions or arguments against my approach? Is there something bad I have done?
I like Zend Framework approach. Files: ``` lib/Archive.php lib/Archive/Zip.php lib/Archive/Rar.php ``` Code: ``` require_once 'Archive_Zip'; $zip = new Zip(); ``` See this: <http://framework.zend.com/manual/en/coding-standard.naming-conventions.html#coding-standard.naming-conventions.classes>
Since #3 doesn't really follow from #1 or #2 an alternative approach is just to instantiate the object when you need it.. like this: ``` $archive = new Archive_Zip(); ``` Done. No need to complicate it more than necessary.
A question about organizing classes and naming them
[ "", "php", "naming", "" ]
How can I use javascript/jQuery/etc to detect if Flash is installed and if it isn't, display a div that contains information informing the user that they need to install flash?
Use swfobject. it replaces a div with the flash if it is installed. see: <http://code.google.com/p/swfobject/>
If `swfobject` won't suffice, or you need to create something a little more bespoke, try this: ``` var hasFlash = false; try { hasFlash = Boolean(new ActiveXObject('ShockwaveFlash.ShockwaveFlash')); } catch(exception) { hasFlash = ('undefined' != typeof navigator.mimeTypes['application/x-shockwave-flash']); } ``` It works with 7 and 8.
How can I detect if Flash is installed and if not, display a hidden div that informs the user?
[ "", "javascript", "jquery", "asp.net-mvc", "flash", "detection", "" ]
Is there any magic hanging around anywhere that could mean that ``` (object0 == object1) != (object0.equals(object1)) ``` where object0 and object1 are both of a certain type which hasn't overridden Object.equals()?
No. That's exactly the definition of Object.[equals()](http://java.sun.com/javase/6/docs/api/java/lang/Object.html#equals(java.lang.Object)). *...this method returns true if and only if x and y refer to the same object (x == y has the value true) ...* ``` public boolean equals( Object o ) { return this == o; } ```
Yes, if by "The type of `object0` doesn't override `Object.equals()`" you mean the specific type and not a superclass. If `object0` and `object1` are of type B, B extends A, and A overrides `equals(Object obj)` but B doesn't, then it is possible that B doesn't override `equals(Object obj)` but `(object0 == object1) != (object0.equals(object1))`.
In which circumstances Java reference equality could be different to equals() equality for an object of a type which has not overridden equals()?
[ "", "java", "" ]
You would think that if two dictionaries contained the same keys and values they would return the same hash code and be equal right? but they don't - what am i doing wrong? or how do I compare dictionaries in this way? Thanks. Code sameple below /In this case I also want to test the order is the same/equal. ``` SortedDictionary<int,string> sd1 = new SortedDictionary<int,string>(); sd1.Add(1,"one"); sd1.Add(2, "two"); sd1.Add(5, "five"); int sd1Hash = sd1.GetHashCode(); SortedDictionary<int, string> sd2 = new SortedDictionary<int, string>(); sd2.Add(1, "one"); sd2.Add(2, "two"); sd2.Add(5, "five"); int sd2Hash = sd2.GetHashCode(); //This is false bool areEqual = sd1.Equals(sd2); ```
If you want to test that the collections are equal, including their ordering: ``` bool areEqual = sd1.SequenceEqual(sd2); ``` If you wanted to treat the collections as unordered sets: ``` bool areEqual = (sd1.Count == sd2.Count) && (sd1.Intersect(sd2).Count() == sd1.Count); ``` *(`SequenceEqual` and `Intersect` can also take an `IEqualityComparer` parameter, if required.)* As several other answers have stated, `SortedDictionary` doesn't override the default implementations of `Equals` or `GetHashCode`. The default implementation of `Equals` will use reference equality and return `false` because you're comparing two separate objects.
You can check out MSDN for this issue: The default implementation of Equals supports reference equality for reference types, and bitwise equality for value types. Reference equality means the object references that are compared refer to the same object. Bitwise equality means the objects that are compared have the same binary representation. So, since the SortedDictionary contains references, they will be compared. and those are obviously different. You can find more info on: <http://msdn.microsoft.com/en-us/library/bsc2ak47.aspx>
Dictionary(TKey, TValue) GetHashCode and Equals - How do they work?
[ "", "c#", "" ]
I have quite a simple problem but can't find a solution for it. I have a logger with a file handler added, but it still spams the hell out of my console. How could I get the logger to solely route all output to a file, with NO console outputs?
Remove all handlers (using [Logger.getHandlers()](http://java.sun.com/j2se/1.5.0/docs/api/java/util/logging/Logger.html#getHandlers()) and calling [Logger.removeHandler()](http://java.sun.com/j2se/1.5.0/docs/api/java/util/logging/Logger.html#removeHandler(java.util.logging.Handler)) for each handler) from the root logger before adding your file handler.
Old question but to help other developers: You can also just use `logger.setUseParentHandlers(false)` on your logger.
Java Logger only to file, no screen output
[ "", "java", "logging", "" ]
I am running CentOS 5.2 and using yum to manage packages. I have had little luck installing php-posix but know with almost 100% certitude that it is a real and available package...somewhere. Has anyone had luck installing it? FWIW, I am using the following: `sudo yum install -y php-posix` **Update:** I've realized that this may be an issue with my host (Slicehost) as I do in fact have cli, posix, and pcntl enabled for my PHP version (5.2.9)
You can try and see if it's in the testing repository. To see if it's in that repository. ``` yum --disablerepo=\* --enablerepo=c5-testing list available \*php\* ``` And to install it. ``` yum --enablerepo=c5-testing install php-posix ``` Be aware though, that the PHP version it needs may be higher than you currently have.
While the question was for centos, notice that for fedora the `php-posix` package is provided by `php-process` [from fedora 11](http://forums.famillecollet.com/viewtopic.php?id=35). I assume this change also will hit centos at some point.
How does one easily add posix support to PHP using yum?
[ "", "php", "posix", "package", "centos", "yum", "" ]
**[DISCLAIMER: My development machine is running OS X Tiger, so my question and experiences are specific to that. But I would not mind hearing feedback on Webkit for Windows.]** I've been a longtime Firebug user, but I've grown tired of it's twitchiness. I'm talking specifically about when it will not stop on breakpoints, lose the current line in the debugger pane, or slow execution to a crawl. I briefly played around with the debugger in Safari's Web Inspector, and it just feels more solid. Has anyone else switched to the Safari debugger? If so, were you glad you did? Are there any reasons I shouldn't consider it?
I much prefer Safari's debugger to FireBug. I totally agree that it seems more solid. The only thing I don't like about WebInspector in Safari is search. It takes ages for it to search. And to make matters worse, it insists on searching all the scripts that has been loaded instead of just the one you're looking at. Anothter thing where WebInspector can't compete just yet is when it comes to inspecting dom-elements and changing styles on the fly. The times I need to play around with the css styles are more or less the only times I choose to use FireBug instead.
I recently started using the Safari debugger (on a WebKit nightly build, which will be about the same as the version now shipping with Safari 4) when Firebug was messing me around, and was absolutely delighted with it. Highly recommended.
Firebug vs. Safari Javascript debugger
[ "", "javascript", "macos", "" ]
This: ``` typedef HRESULT (*PFN_HANDLE)(ClassName&); ``` It's used like this: ``` DWORD ClassName::Wait(PFN_HANDLE pfnh_foo) { while (!done) { waitCode = WaitForMultipleObjects(paramA, paramB, paramC, paramD) if (waitCode == WAIT_OBJECT_0) { pfnh_foo(*this); } else done; } return waitCode; } ``` It appears that Wait does nothing except block when it gets to WaitForMultipleObjects and then after that does this strange pfnh\_foo thing and either loops back around to wait again or exits
Your `wait()` function basically [waits for multiple objects](http://msdn.microsoft.com/en-us/library/ms687025(VS.85).aspx) and then invoke function using [function pointer](http://en.wikipedia.org/wiki/Function_pointer) `PFN_HANDLE` if the wait is successful ( indicated by return value `WAIT_OBJECT_0`). ``` pfnh_foo(*this); ``` This calls the function pointed by pfnh\_foo with argument \*this. Lets say we have function: ``` HRESULT someFunction(ClassName& myClassInstance) { //blah .. blah } ``` Wait will be invoked like this: ``` PFN_HANDLE pfnh_foo = &someFunction; //function pointer to someFunction wait(pfnh_foo); ```
pfnh\_foo is a function pointer - it's running a function, with your class as a parameter
What does this mean?
[ "", "c++", "" ]
I have an enum representing all material assembly codes in the system: ``` public enum EAssemblyUnit { [Description("UCAL1")] eUCAL1, [Description("UCAL1-3CP")] eUCAL13CP, [Description("UCAL40-3CP")] eUCAL403CP, // ... } ``` In legacy code in another part of the system, I have objects labeled with strings that match the enum descriptions. Given one of those strings, what's the cleanest way to get the enum value? I envision something like: ``` public EAssemblyUnit FromDescription(string AU) { EAssemblyUnit eAU = <value we find with description matching AU> return eAU; } ```
You'd need to iterate through all the static fields of the enum (that's how they're stored in reflection) finding the Description attribute for each one... when you spot the right one, get the value of the field. For example: ``` public static T GetValue<T>(string description) { foreach (var field in typeof(T).GetFields()) { var descriptions = (DescriptionAttribute[]) field.GetCustomAttributes(typeof(DescriptionAttribute), false); if (descriptions.Any(x => x.Description == description)) { return (T) field.GetValue(null); } } throw new SomeException("Description not found"); } ``` (This is generic just to make it reusable for different enums.) Obviously you'd want to cache the descriptions if you're doing this even slightly frequently, e.g.: ``` public static class DescriptionDictionary<T> where T : struct { private static readonly Dictionary<string, T> Map = new Dictionary<string, T>(); static DescriptionDictionary() { if (typeof(T).BaseType != typeof(Enum)) { throw new ArgumentException("Must only use with enums"); } // Could do this with a LINQ query, admittedly... foreach (var field in typeof(T).GetFields (BindingFlags.Public | BindingFlags.Static)) { T value = (T) field.GetValue(null); foreach (var description in (DescriptionAttribute[]) field.GetCustomAttributes(typeof(DescriptionAttribute), false)) { // TODO: Decide what to do if a description comes up // more than once Map[description.Description] = value; } } } public static T GetValue(string description) { T ret; if (Map.TryGetValue(description, out ret)) { return ret; } throw new WhateverException("Description not found"); } } ```
``` public EAssemblyUnit FromDescription(string AU) { EAssemblyUnit eAU = Enum.Parse(typeof(EAssemblyUnit), AU, true); return eAU; } ```
How can I get an enum value from its description?
[ "", "c#", "enums", "" ]
Is there a way to test what fonts are installed or maybe a way I can read out all of them? I want to do a survey in our product to see what fonts I can use on our projects.
There is a script that renders a bunch of DIVs in different fonts, then checks to see if the resulting DIV has the right dimensions for the given font. <http://www.lalit.org/lab/javascript-css-font-detect>
It is possible, so long as Flash is available. See <http://www.maratz.com/blog/archives/2006/08/18/detect-visitors-fonts-with-flash/>
Is there a way to check what fonts are installed on machines via the web?
[ "", "javascript", "jquery", "css", "fonts", "" ]
I'm calling a class that does not seem to be executing any of its methods. Consider the following file (db-com.php): ``` echo "entered db-com.php"; class DBCom { /** * @var string Holds the query string. * If the blank constructor is used, make sure to use the parametrized functions. */ var $queryString; /** * @var resource Holds the MySQL Resource returned by mysql_query function */ var $queryResult; /** * @var array Holds the entire array of the result. */ var $queryArray; function __construct() { $this->queryString = $this->queryResult = $this->queryArray = ''; } function __construct($qS) { $this->queryString = $qS; $this->queryResult = mysql_query($this->queryString); $this->queryArray = ''; } /** * * @return array An array containing all the elements of the requested query. */ function get_query_array() { if($this->queryString == '' || $this->queryString == "") { die("Query String is Empty. Cannot Proceed."); } for ( $i = 0 ; $fetchedArray = mysql_fetch_array( $this->queryResult ) ; $i++) { $this->queryArray[$i] = $fetchedArray; } return $this->queryArray; } } ``` When in another file I write: ``` require ( 'some_path/db-com.php' ); ``` it doesn't even enter this file. i.e. even the first `echo` statement doesn't get displayed. This is not happening with any other class files. Only this type of class involving SQL functions. So I even started a clean blank file, tested first that control enters it or not (it did) and then wrote all of this, saved it under a different name, and included it, and again this mysterious error popped out. Where have I gone wrong?
You have two `__construct()` methods. You can't overload methods like that in PHP. You probably have `display_error`s turned off, so that is why you can't see the error message: > Fatal error: Cannot redeclare > DBCom::\_\_construct() in > C:\test.php on line 23
Are you doing `<?php ?>`
Control not entering into PHP class file
[ "", "php", "mysql", "class", "" ]
I'm trying to do : ``` document.getElementById("header-text").innerHTML = "something interesting"; ``` It's working fine with every browser except Opera (I'm running the latest version). Browsing the internet I found people saying that Opera does not support innerHTML. That doesn't sound right. Any pointers? Thanks **Edit**: Here is the id I'm trying to get ``` <div id="header-text" class="picture-text"> <!--[if gt IE 5]>ugly hack<![endif]--> Some text generated server side <!--[if gt IE 5]>ugly hack<![endif]--> </div> ``` **Edit2**: I have the same issue with : ``` <div id="header-text" class="picture-text"> Static text </div> ``` **Edit3**: ``` <body onload="intialize();"> function intialize() { operaHeaderFix(); } function operaHeaderFix(){ if(window.opera) { /*opera specific action*/ document.getElementById("picture-line-wrapper").style.position="relative"; document.getElementById("picture-line-wrapper").style.top="0px"; document.getElementById("picture-line-wrapper").style.marginTop="-230px"; document.getElementById("picture-line").style.padding="1px"; document.getElementById("header-text").innerHTML = "<div style='margin:220px 0px 0px 20px;'>"+document.getElementById("header-text").innerHTML+"TEST</div>"; } } ``` **Edit4**: If I remove the if(window.opera), it will run fine in FF and IE
***FOUND THE ISSUE:*** The wrapping node was not properly closed. ``` <div att1="value" att2="value" <div id="header-text">...</div> </div> ``` AFAIK, FF and IE were politely fixing the tag... but Opera wasn't, thus the child DIV wasn't really an element in the DOM. --- Should work fine. What is the element with the id "header-text"? Are you sure there is only one match, and it has editable content? Can you post some of the markup so we can test? From PPK's site, there doesn't seem to be any Opera issues: <http://www.quirksmode.org/dom/innerhtml.html> ***Update:*** Running this code in Opera 9.6.4 on XP works fine for me. ``` <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <title>innerHTML test</title> <script> function doIt(){ document.getElementById("header-text").innerHTML = "something interesting"; } </script> </head> <body> <div id="header-text" class="picture-text"> Static text </div> <input type="button" value="Change It" onclick="doIt();"/><br/> </body> </html> ```
I ran into a somewhat related issue and found it to be related to HTML encoded values. For example, when the innerHTML contained "&nbsp;" instead of a space, the innerHTML would come back slightly different (which I confirmed by testing the length of the innerHTML). Here is what I found when trying to get the innerHTML of a tag that contained a single DIV wrapping an encoded non-breaking space (<div>&nbsp;</div>): ``` <div> </div> ``` The example above shows how Opera 10.26 would return innerHTML, and when I checked the length it would return 12 in Opera ``` <div>&nbsp;</div> ``` This is how all other browsers I used would return innerHTML (IE6/7/8, Firefox 3.x, Chrome, etc.), and when I checked the length it would return 17 in all these other browsers.
.innerHTML opera issue?
[ "", "javascript", "cross-browser", "opera", "" ]
I'm trying to extract only certain elements of a string using regular expressions and I want to end up with only the captured groups. For example, I'd like to run something like `(is|a)` on a string like `"This is a test"` and be able to return only `"is is a"`. The only way I can partially do it now is if I find the entire beginning and end of the string but don't capture it: ``` .*?(is|a).*? replaced with $1 ``` However, when I do this, only the characters preceding the final found/captured group are eliminated--everything after the last found group remains. ``` is is a test. ``` How can I isolate and replace only the captured strings (so that I end up with `"is is a"`), in both PHP and Perl? Thanks! **Edit:** I see now that it's better to use `m//` rather than `s///`, but how can I apply that to PHP's `preg_match`? In my real regex I have several captured group, resulting in `$1`, `$2`, `$3` etc -- `preg_match` only deals with one captured group, right?
If all you want are the matches, the there is no need for the `s///` operator. You should use `m//`. You might want to expand on your explanation a little if the example below does not meet your needs: ``` #!/usr/bin/perl use strict; use warnings; my $text = 'This is a test'; my @matches = ( $text =~ /(is|a)/g ); print "@matches\n"; __END__ C:\Temp> t.pl is is a ``` **EDIT:** For PHP, you should use [`preg_match_all`](http://us.php.net/manual/en/function.preg-match-all.php) and specify an array to hold the match results as shown in the documentation.
You can't replace only captures. `s///` always replaces everything included in the match. You need to either capture the additional items and include them in the replacement or use assertions to require things that *aren't* included in the match. That said, I don't think that's what you're really asking. Is [Sinan's answer](https://stackoverflow.com/questions/1029159/how-can-i-replace-only-the-captured-elements-of-a-regex#1029214) what you're after?
How can I replace only the captured elements of a regex?
[ "", "php", "regex", "perl", "" ]
When static members are inherited, are they static for the entire hierarchy, or just that class, i.e.: ``` class SomeClass { public: SomeClass(){total++;} static int total; }; class SomeDerivedClass: public SomeClass { public: SomeDerivedClass(){total++;} }; int main() { SomeClass A; SomeClass B; SomeDerivedClass C; return 0; } ``` would total be 3 in all three instances, or would it be 2 for `SomeClass` and 1 for `SomeDerivedClass`?
3 in all cases, since the `static int total` inherited by `SomeDerivedClass` is exactly the one in `SomeClass`, not a distinct variable. Edit: actually *4* in all cases, as @ejames spotted and pointed out in his answer, which see. Edit: the code in the second question is missing the `int` in both cases, but adding it makes it OK, i.e.: ``` class A { public: static int MaxHP; }; int A::MaxHP = 23; class Cat: A { public: static const int MaxHP = 100; }; ``` works fine and with different values for A::MaxHP and Cat::MaxHP -- in this case the subclass is "not inheriting" the static from the base class, since, so to speak, it's "hiding" it with its own homonymous one.
The answer is actually *four* in all cases, since the construction of `SomeDerivedClass` will cause the total to be incremented *twice*. Here is a complete program (which I used to verify my answer): ``` #include <iostream> #include <string> using namespace std; class SomeClass { public: SomeClass() {total++;} static int total; void Print(string n) { cout << n << ".total = " << total << endl; } }; int SomeClass::total = 0; class SomeDerivedClass: public SomeClass { public: SomeDerivedClass() {total++;} }; int main(int argc, char ** argv) { SomeClass A; SomeClass B; SomeDerivedClass C; A.Print("A"); B.Print("B"); C.Print("C"); return 0; } ``` And the results: ``` A.total = 4 B.total = 4 C.total = 4 ```
Are static fields inherited?
[ "", "c++", "inheritance", "static", "" ]
I'm developing an embedded application using GCC/G++ compiled for arm-eabi. Due to resource constraints, I'm trying to disable the standard C++ exception handling. I'm compiling the code with "-fno-exceptions -nostartfiles -ffreestanding". When a global instance of a class exists, and that class contains an instance of another class as a member, then a lot of exception handling code is being linked in. This wouldn't be so bad, except that it's also bringing in lots of stdio stuff, like printf, fopen, fclose and other FILE functions. This application has no filesystem, and even if it did, these functions waste too much code space. I understand that even with -fno-exceptions, G++ links in an operator new that uses exceptions, because the library doesn't have a non-exception-using operator new (except new(nothrow)). I created replacements for operator new and delete, and these are linked into the output as well as the unwanted standard-library functions. What puzzles me is that I'm not calling new anywhere. It's only when a global object contains another object that all this code is linked in. For example: ``` class UartA { ... private: Ringbuffer* rxbuf; }; class UartB { ... private: Ringbuffer rxbuf; }; ``` If a global instance of UartA is created, the exception handling, operator new, and stdio stuff are not linked in. This is what I want. If a global instance of UartB is created (where rxbuf is an instance instead of a pointer), the unwanted code is linked in. Neither UartA nor UartB use operator new, exceptions or stdio. They differ only by the type of rxbuf. Can you suggest how to prevent linking the extra code? Also, why is this being linked in for UartB, but not UartA?
I think the closest you can get is compiling *and* linking with -fno-exceptions and -fno-rtti. If there's a better way to get rid of the rest, I'd be glad to hear it myself. As far as getting rid of new, try -nostdlib.
since you are basically doing the things that an OS developer would do to get a standalone c or c++ environment. You may want to look into just using a custom linker script. You just need to be careful because things like global constructors no longer happen automatically..but you will also not get anything you didn't explicitly ask for (and it isn't hard to write the code to call the global constructors). Here's the linker script from my OS. ``` OUTPUT_FORMAT("elf32-i386") ENTRY(start) virt = 0xc0100000; /* 3.1 gig */ phys = 0x00100000; /* 1 meg */ SECTIONS { .text virt : AT(phys) { code = .; _code = .; __code = .; *(.text) *(.gnu.linkonce.t*) . = ALIGN(4096); } .rodata : AT(phys + (rodata - code)) { rodata = .; _rodata = .; __rodata = .; *(.rodata*) *(.gnu.linkonce.r*) __CTOR_LIST__ = .; LONG((__CTOR_END__ - __CTOR_LIST__) / 4 - 2) *(.ctors) LONG(0) __CTOR_END__ = .; __DTOR_LIST__ = .; LONG((__DTOR_END__ - __DTOR_LIST__) / 4 - 2) *(.dtors) LONG(0) __DTOR_END__ = .; . = ALIGN(4096); } .data : AT(phys + (data - code)) { data = .; _data = .; __data = .; *(.data) *(.gnu.linkonce.d*) . = ALIGN(4096); } .tbss : AT(phys + (tbss - code)) { tbss = .; _tbss = .; __tbss = .; *(.tbss) *(.tbss.*) . = ALIGN(4096); } .bss : AT(phys + (bss - code)) { bss = .; _bss = .; __bss = .; *(.bss) *(.bss.*) *(COMMON) *(.gnu.linkonce.b*) . = ALIGN(4096); } end = .; _end = .; __end = .; } ``` It probably does more than you need (aligns sections to 4k boundaries, has all symbols at > 3GB mark) but is a good starting place. You can use it like this: ``` ld -T link_script.ld *.o -lc -o appname ``` the "-lc" should link in libc as well if that's what you want.
How can I stop g++ from linking unwanted exception-handling code?
[ "", "c++", "exception", "gcc", "g++", "" ]
I would really like to be able to run our test suite on Xvfb so that swing windows don't keep popping up in the way of my work. Unfortunately I cannot seem to find a way to get the java runtime to use the display specified in the DISPLAY environment variable. I suppose this is because the Mac JDK is hardwired to use the (non-X-based) Mac display. I can't find any switches for the java command that say to use X either. Thanks in advance for any help you can give! Matt
I don't know if there is a way to get Apple's JDK to use X11, but there is the alternative of using [SoyLatte](http://landonf.bikemonkey.org/static/soylatte/), which is a Mac Java implementation that only works with X11.
Try to start your application from within the X11 terminal. This worked for <http://mcis.polymtl.ca/makao.html> for me on MacOS 10.14.5
How to display java swing on X11 when running on Mac
[ "", "java", "macos", "swing", "x11", "" ]
I have two arrays: ``` var a = new Array(1,2,3,4); var b = new Array(5,3,2,6); ``` I want to find out which elements are in array `a` but not in array `b` and which elements are in `b` but not in `a`? I know one way is to iterate through them each, but is there a more efficient way? Thank you for your time.
You could try the following: ``` var aNotInB = $.grep(a, function($e) { return $.inArray($e, b) == -1; }); var bNotInA = $.grep(b, function($e) { return $.inArray($e, a) == -1; }); ``` You could define this as a jquery function: ``` $.disjoin = function(a, b) { return $.grep(a, function($e) { return $.inArray($e, b) == -1; }); }; var aNotInB = $.disjoin(a,b); var bNotInA = $.disjoin(b,a); ```
You have to look at each element of both array to get the difference of them. So there is no other way than iterating both array: ``` Array.prototype.diff = function(otherArray) { var diff = [], found; for (var i=0; i<this.length; i++) { found = false; for (var j=0; j<otherArray.length; j++) { if (this[i] == otherArray[j]) { found = true; break; } } if (!found) { diff.push(this[i]); } } return diff; }; var a = [1,2,3,4], b = [5,3,2,6]; var aDiffB = a.diff(b), bDiffA = b.diff(a); ``` You can skip some comparisons when the arrays are sorted and start with the inner loop with the element after the last match and break it if the value is larger: ``` Array.prototype.diff = function(otherArray) { var diff = [], found, startAt = 0, a = this.sort(), b = otherArray.sort(); for (var i=0; i<a.length; i++) { found = false; for (var j=startAt; j<b.length; j++) { if (a[i] > b[j]) { break; } if (a[i] == b[j]) { found = true; startAt = j + 1; break; } } if (!found) { diff.push(a[i]); } } return diff; }; ``` But sorting both array does also cost.
jQuery Disjoint
[ "", "javascript", "jquery", "arrays", "" ]
How can I "reorder" the keys in a multi-array? For example, I have: ``` $arr["abc"][0] = "val1"; $arr["abc"][1] = "val2"; $arr["abc"][2] = "val3"; $arr["xyz"][0] = "val4"; $arr["xyz"][1] = "val5"; $arr["xyz"][2] = "val6"; ``` And I want it to be: ``` $arr[0]["abc"] = "val1"; $arr[0]["xyz"] = "val4"; $arr[1]["abc"] = "val2"; $arr[1]["xyz"] = "val5"; $arr[2]["abc"] = "val3"; $arr[2]["xyz"] = "val6"; ``` My current effort is: ``` foreach ($arr as $param => $num) foreach ($num as $val) $newArr[$num][$param] = $val; ``` but it doesn't seem to be working. Any help would be appreciated. EDIT: Specifically, I'm trying to loop through all elements submitted on `$_FILES`, as they all need the same thing done to them. By default, when there is more than one `<input type="file" name="filedata[]" />` in a form, they go to `$_FILES["filedata"]["name"][$index]`. (`"name"` or any other parameter), so I cant just loop through every `$_FILES["filedata"]` to get at everything; thus, I need the keys of `$_FILES["filedata"]` reversed.
I think you need to still grab the keys in the second foreach. Try something like: ``` foreach($arr as $k1 => $v1) { foreach ($v1 as $k2 => $v2) { $newArray[$k2][$k1] = $v2 } } ```
Straightforward enough with two `foreach` loops: ``` // Original version: $arr = array(); $arr["abc"][0] = "val1"; $arr["abc"][1] = "val2"; $arr["abc"][2] = "val3"; $arr["xyz"][0] = "val4"; $arr["xyz"][1] = "val5"; $arr["xyz"][2] = "val6"; print_r($arr); $newarray = array(); // Swap around the keys foreach ($arr as $key1 => $val1) { foreach ($val1 as $key2 => $val2) { $newarray[$key2][$key1] = $val2; } } print_r($newarray); ``` Here's the display: ``` // Display of $arr: //Array //( // [abc] => Array // ( // [0] => val1 // [1] => val2 // [2] => val3 // ) // // [xyz] => Array // ( // [0] => val4 // [1] => val5 // [2] => val6 // ) // //) //Display of $newarray: //Array //( // [0] => Array // ( // [abc] => val1 // [xyz] => val4 // ) // // [1] => Array // ( // [abc] => val2 // [xyz] => val5 // ) // // [2] => Array // ( // [abc] => val3 // [xyz] => val6 // ) // //) ```
Moving around key order in a multi-dimensional array
[ "", "php", "arrays", "" ]
Is it by any means possible to read the browser session id using javascript?
Yes. As the session ID is either transported over the URL (`document.location.href`) or via a cookie (`document.cookie`), you could check both for the presence of a session ID.
The following can be used to retrieve JSESSIONID: ``` function getJSessionId(){ var jsId = document.cookie.match(/JSESSIONID=[^;]+/); if(jsId != null) { if (jsId instanceof Array) jsId = jsId[0].substring(11); else jsId = jsId.substring(11); } return jsId; } ```
Read Session Id using Javascript
[ "", "javascript", "session", "" ]
I have been reading through the documentation on the [JavaScriptMVC](http://javascriptmvc.com/) framework and it looks interesting. I am wondering if anybody here has used the framework, and with what success. So please share your experience with [JavaScriptMVC](http://javascriptmvc.com/), if you have any. If you can suggest another MVC javascript framework that is fine to. Best regards, Egil.
I have no experience with JavascriptMVC. However another really famous MVC framework for Javascript is ActiveJS <http://www.activerecordjs.org/> which came out about a year ago. It's by Aptana the people who make Aptana Studio and Jaxer (server side javascript). I do believe that would probably hold more merrit as Jaxer is amazing technology so I have no doubt Aptana have thought about this a lot. I also use a jQuery project called Ajaxy which offers Controllers to Ajax requests in my own projects. <http://github.com/balupton/AJAXY/>
I love JavaScriptMVC. Of course, I am a contributor. Many people have had success with JavaScriptMVC (a few are listed on the homepage). I've used it on 100k lines-of-code projects to simple pages I've made for my friend's parents. When we give trainings on it, I can tell it requires a shift in how you think about application architecture, specifically with it's focus on Thin Server Architecture. It also is another set of 'rules' to learn. But the great thing is that if you and your team learn and follow these rules, it becomes really easy to maintain and fix other people's code.
Please share your experience with JavaScriptMVC, alternatives
[ "", "javascript", "model-view-controller", "javascriptmvc", "" ]
Windows API has a set of function for heap creation and handling: HeapCreate, HeapAlloc, HeapDestroy and etc. I wonder what is the use for another heap in a program? From fragmentation point of view, you will get external fragmentation where memory is not reused among heaps. So even if low-fragmentation heaps are used, stil there is a fragmentation. Memory management of additional heaps seems to be low-level. So they are not easy to use. In addition, additional heap can probably be emulated using allocations from heap and managing allocated memory. So what is the usage? Did you use it?
One use case might be a long-running complex process that does a lot of memory allocation and deallocation. If the user wants to interrupt the process, then an easy way to clean up the memory currently allocated might be to have everything on a private heap and then simply destroy the heap. I have seen this technique used in an embedded system (which wasn't using Windows, so it didn't use those exact API functions). The custom memory allocator had a feature to "mark" a specific state of the heap and then "rewind" to that point if a process was aborted.
One reason that is only important in rare situations, but immensely important there: memory allocated by `new/malloc` isn't executable on modern Windows systems. Hence if you write for example a JIT, you will have to use `HeapCreate` with `HEAP_CREATE_ENABLE_EXECUTE`.
When HeapCreate function is used or in what cases do you need a number of heaps?
[ "", "c++", "windows", "memory-management", "" ]
I know to never trust user input, since undesirable input could be compromise the application's integrity in some way, be it accidental or intentional; however, is there a case for calling Page.IsValid even when no validation controls are on the page (again, I know its bad practice to be trusting user input by omitting validation)? Does Page.IsValid perform any other kinds of validation? I looked at MSDN, and the docs seem to suggest that Page.IsValid is only effective if there are validation controls on the page, or the Page.Validate method has been called. A friend of mine suggested that I always check Page.IsValid in the button click handlers every time even if there are no validation controls or explicit Page.Validate calls.
I would be the first to tell you that "*All input is evil until proven otherwise.*" However, in this case, I think your friend is mistaken because by his/her logic we could probably come up with a hundred other properties that should be checked or set, even though the defaults are okay. Checking `Page.IsValid` only makes sense if you have a "CausesValidation" scenario - a button that submitted the form has its `CausesValidation` property set to True. This would automatically call `Page.Validate` and all Validation controls belonging to the same `ValidationGroup` would be checked for validity. **Edit:** Just checked it using Reflector and the function will always return True if the Page does not have any Validators(ValidatorCollection is null).
You can check the validity of a Page by checking the Page.IsValid property, your purpose to check the Page.IsValid might vary like * If you have Validators which has the *EnableClientScript* property set to false * If you have a *server side validated Validator*. * Before performing a critical operation in a PostBack event handler body like *Save*, *Delete*, *Authenticate*... * Do/display different things depending on the validity of page... * Any thing you can think of... So when/where can you call Page.IsValid 1. If the page is in *post back* 2. If the *post back* is caused by an input control with the *CausesValidation* property set to *true*. 3. After a call is made to the *Page.Validate*, i.e *after the Page.Load event*. You can check Page.IsValid in the page life cycle if the place/time invoked satisfies the above criteria; otherwise the Page.IsValid will result in the *System.Web.HttpException* being thrown. You should use Page.IsValid *where it makes sense*; like in the postback event handlers of input controls(with CausesValidation=true) and require the state of the page to be valid to perform their task correctly. (if you have server side validated validators or validators with client side validation switched off it becomes a *MUST*). ``` protected void btnSave_Click(object sender, EventArgs e) { //Note that there might be ServerSideValidation which evaluated to false. if (!Page.IsValid) return; CurrentEntity.Save(); } ``` Finally note that Page.IsValid only checks for validation errors in the validator controls on your page, it all depends on what your validator controls do.
Should I always call Page.IsValid?
[ "", "c#", "asp.net", ".net", "validation", "" ]