Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
I have two nearly identical javascript functions that are used to initiate a jquery $.get call. The arguments to the function are passed to the script being called. The problem is that one set of calls requires an additional argument that the other does not. To accomplish this I'm using the two nearly identical javascript functions I've mentioned. Here they are: ``` function process(url, domid, domain, scan_id) { $.get(url, { domain: domain, scan_id: scan_id }, function(data) { $(domid).html(data); }); } function process_type(url, domid, type, domain, scan_id) { $.get(url, { domain: domain, type: type, scan_id: scan_id }, function(data) { $(domid).html(data); }); } ``` As you can see, the 2nd function merely accepts an additional argument called 'type' which is then passed through the $.get call. I want to combine these two functions, but I'm not sure how I can optionally include that 3rd argument in that ( array / object / whatever it is in { } ( yes, javascript noob) ) that's being passed in $.get. EDIT just to say.... damn, you guys are good. :D
Since all you're doing with everything but url and domid is passing it to the `$.get`, why not do this? ``` function process_type(url, domid, args) { $.get(url, args, function(data) { $(domid).html(data); }); } // call it without type process_type('myurl', 'domid', {domain:'..', scanid:'...'}); // call it with type process_type('myurl', 'domid', {type: '..', domain:'..', scanid:'..'}); ```
all parameters in javascript are optional, you can use the parameters array inside of a function to access parameters passed ordinally like so: ``` function myFunction(option1) { var option2 = arguments[1]; if(arguments[0] == option1) alert("Happy Day, Option1 = " + option1 + ", Option2 = " + option2); } myFunction("Hello", "World"); ``` Produces: Happy Day, Option1 = Hello, Option2 = World Hopefully this illustrates how you can use the arguments array to improve some code. ``` function process_type(url, domid, domain, scan_id) { var myOptions = { domain: domain, scan_id: scan_id }; if(arguments[4]) myOptions["type"] = arguments[4]; $.get(url, myOptions, function(data) { $(domid).html(data); }); } ``` Then you can call it with the last parameter being the type as optional, if the parameter is passed it is used if not it is omitted. Also since the actual parameter is optional in the first place you can also add the name to the end of the function definition and use the same if but instead of `arguments[4]` you'd do `if(type) myOptions["type"] = type;` ``` function process_type(url, domid, domain, scan_id, type) { var myOptions = { domain: domain, scan_id: scan_id }; if(type) myOptions["type"] = type; $.get(url, myOptions, function(data) { $(domid).html(data); }); } ``` This Call would include type ``` process_type("xxx", "xxx", "xxx", "xxx", "xxx"); ``` where this call would not ``` process_type("xxx", "xxx", "xxx", "xxx"); ```
Javascript Functions and optional arguments
[ "", "javascript", "jquery", "arguments", "" ]
I used to work on netbeans to build Java applications but now: i am using eclipse. I was was wondering if there a a free good plug-in to help me with swing windows.??
[Jigloo - CloudGarden](http://www.cloudgarden.com/jigloo/index.html)(free non-commercial) [Visual Editor Project](http://www.eclipse.org/vep/WebContent/main.php) AND [JForm](http://www.formdev.com/buy/) (pay)
I'm assuming you want a GUI designer. The best plug-in for this is the excellent [Swing Designer](http://www.instantiations.com/windowbuilder/swingdesigner/index.html). Definitely worth a look.
can I build swing applications on eclipse?
[ "", "java", "eclipse", "swing", "" ]
A web page displays the following:- * Bob * Fred * John However when the user (that would be me) prints the web page I want multiple repeats of this output with slight variations to be printed on separate pages :- * **Bob** * Fred * John `>page break here<` * Bob * **Fred** * John `>page break here<` * Bob * Fred * **John** In reality the page content is larger (although well within a standard A4 page worth) and the number of output pages is about 20. I'd prefer an elegant cross-browser solution but ultimately a solution that works on Internet Explorer 7 is acceptable. I'm using ASP.NET MVC with jQuery (although a straight JavaScript solution is fine). **Edit:** Page-Break-XXX css style is going be part of the answer, but I'm particularly interested in a means to dynamically create the print version HTML from the screen version. Note I don't want to navigate to a 'printer friendly' page and then print that. I just want to hit the browsers print button and magic happens.
Ok, so taking into account the comments etc to my post something like this: For ease of display here, I'm using on page styles, but you can easily use off page references. Declaring the following styles: ``` <!-- media="print" means these styles will only be used by printing devices --> <style type="text/css" media="print"> .printable{ page-break-after: always; } .no_print{ display: none; } </style> <!-- media="screen" means these styles will only be used by screen devices (e.g. monitors) --> <style type="text/css" media="screen"> .printable{ display: none; } </style> <!-- media types can be combined with commas to affect multiple devices --> <style type="text/css" media="screen,print"> h1{ font-family: Arial, Helvetica, sans-serif; font-size: large; font-weight: bold; } </style> ``` Then, you're going to need to do some heavy lifting in your view to get HTML looking **something** like this: ``` <!-- Intial display for screen --> <div class="no_print"> <!-- Loop through users here using preferred looping/display method --> <ul> <li>Bob</li> <li>Fred</li> <li>John</li> </ul> </div> <!-- Now loop through each user, highlighting as you go, but for printer* --> <div class="printable"> <ul> <li><b>Bob</b></li> <li>Fred</li> <li>John</li> </ul> </div> <div class="printable"> <ul> <li>Bob</li> <li><b>Fred</b></li> <li>John</li> </ul> </div> <div class="printable"> <ul> <li>Bob</li> <li>Fred</li> <li><b>John</b></li> </ul> </div> ``` Now for an "appropriate display method". I'm just getting started with MVC, so you've probably got a better method of doing this, but for now I'd probably use a RenderPartial method like this: ``` <% /* Using RenderPartial to render a usercontrol, we're passing in the Model here as the Model for the control, depends on where you've stored your objects really, then we create a new anonymous type containing the properties we want to set. */ // Display the main list Html.RenderPartial("~/Views/Shared/Controls/UserList.ascx", ViewData.Model, new {HighlightUser = null, IsPrintable = false}); // Loop through highlighting each user foreach (var user in ViewData.Model) { Html.RenderPartial("~/Views/Shared/Controls/UserList.ascx", ViewData.Model, new {HighlightUser = user, IsPrintable = true}); } %> ``` Your user control can then handle the bulk of the display, setting the class of the containing divs (or whatever element you use) as appropriate, and bolding up the user based on the one passed in - as I said, there's possibly a better way of doing the partial stuff. Obviously, you probably want completely different rendering of the users for display and print - I guess you're probably adding quite a bit of jQuery goodness hiding and displaying stuff, etc, that you are actually going to display on the printed version, so you probably want two differnt user controls, and can then get away with not passing in the IsPrintable property. Also, as it stands, this will print a blank page at the end, due to the "page-break-after" style on all divs - you'd possibly want to note that you're on the last div, and have a different style on that, unless you have information that you'd like on that last page.
I'm not sure you can do it all via CSS, but here's some to get you started. To get a page break in CSS when printing use one of: * [page-break-before](http://www.w3schools.com/Css/pr_print_pagebb.asp) * [page-break-after](http://www.w3schools.com/Css/pr_print_pageba.asp) These take values of: ``` auto // Default. Insert a page break before/after the element if necessary always // Insert a page break before/after the element avoid // Avoid inserting a page break before/after the element left // Insert page breaks before/after the element until it reaches a blank left page right // Insert page breaks before/after the element until it reaches a blank right page ``` If you're prepared to have some sort of "Print" page that lists the information as you want, with those styles on the repeated elements, you should be good to go.
Single-page display, multi-page print problem
[ "", "javascript", "jquery", "html", "css", "asp.net-mvc", "" ]
For small sets or maps, it's usually much faster to just use a sorted vector, instead of the tree-based `set`/`map` - especially for something like 5-10 elements. LLVM has some classes [in that spirit](http://llvm.org/docs/ProgrammersManual.html#ds_sequential), but no real adapter that would provide a `std::map` like interface backed up with a `std::vector`. Any (free) implementation of this out there? **Edit**: Thanks for all the alternative ideas, but I'm really interested in a vector based set/map. I do have specific cases where I tend to create huge amounts of sets/maps which contain usually less than 10 elements, and I do really want to have less memory pressure. Think about for example neighbor edges for a vertex in a triangle mesh, you easily wind up with 100k sets of 3-4 elements each.
I just stumbled upon your question, hope its not too late. I recommend a great (open source) library named [Loki](http://loki-lib.sourceforge.net/). It has a vector based implementation of an associative container that is a drop-in replacement for std::map, called [AssocVector](https://github.com/snaewe/loki-lib/blob/master/include/loki/AssocVector.h). It offers better performance for accessing elements (and worst performance for insertions/deletions). The library was written by [Andrei Alexandrescu](http://en.wikipedia.org/wiki/Andrei_Alexandrescu) author of [Modern C++ Design](http://en.wikipedia.org/wiki/Modern_C%2B%2B_Design). It also contains some other really nifty stuff.
If you can't find anything suitable, I would just wrap a std::vector to do sort() on insert, and implement find() using lower\_bound(). It should be straight forward, and just as efficient as a custom solution.
Is there already some std::vector based set/map implementation?
[ "", "c++", "optimization", "" ]
Having written a [small article](http://www.codeproject.com/KB/testing/bddnbehave.aspx) on BDD, I got questions from people asking whether there are any cases of large-scale use of BDD (and specifically NBehave). So my question goes to the community: do you have a project that used BDD successfully? If so, what benefits did you get, and what could have been better? Would you do BDD again? Would you recommend it to other people?
We've used somewhat of BDD at the code level in different scenarios (open source and ND projects). 1. Telling the view in MVC scenario, what kind of input to accept from user ([DDD and Rule driven UI Validation in .NET](http://abdullin.com/journal/2009/1/29/ddd-and-rule-driven-ui-validation-in-net.html)) ``` result = view.GetData( CustomerIs.Valid, CustomerIs.From(AddressIs.Valid, AddressIs.In(Country.Russia))); ``` 2. Telling the service layer, about the exception handling behavior ([ActionPolicy](http://abdullin.com/journal/2008/12/1/net-exception-handling-action-policies-application-block.html) is injected into the decorators): ``` var policy = ActionPolicy .Handle<WebException>() .Retry(3); ``` Using these approaches has immensely reduced code duplication, made the codebase more stable and flexible. Additionally, it made everything more simple, due to the logical encapsulation of complex details.
I was on a small team that used BDD on a website. The way we used it was essentially TDD, but the tests are simply written as behaviors using a DSL. We did not get into large upfront design of behaviors, but we did create a large number of them, and used them exactly as you would tests. As you might expect, it worked much as TDD, generally good. Phrasing the tests as behaviors was nice when interacting with the customers and made for a pretty decent document, but I kind of wish the behaviors were written in English and the tests programmed instead of trying to come up with some difficult intermediate language that doesn't fit either purpose perfectly. It would still be BDD, just without this cute trick of trying to twist the language into a language delineated by a random\_looking.set of\_Punctuation rather\_than simple.spaces, but that was only my grumpy-old-programmer attitude, everyone else was 100% happy with it. The site is available and fully operational, so I'd call it a success: [Have a look](http://www.genetree.com/)
Any BDD success stories out there?
[ "", "c#", ".net", "bdd", "nbehave", "" ]
I have an unmanaged C++ DLL which merely exports a single class (not COM...it's just a simple C++ class) as its interface. I want to use this class in C# but am told that it cannot merely be imported into C#. What is the right way to use this class in my C# application?
Simple way assuming class Foo: 1. Create a C++/CLI project, call this FooWrapper. 2. Make FooWrapper depend on the unmanaged dll (however you normally would). 3. Create a managed class ManagedFoo which contains a single private instance field of type Foo\*. 4. provide public wrapping functions in ManagedFoo which forward on to the underlying instance field. 5. Optionally (though recommended): * convert parameters from .net idioms (strings and the like) to C++ idioms (std::string or char\*) * catch unmanaged exceptions and throw managed ones instead Then you make your c# code depend on the FooWrapper project/dll and ensure that the unmanaged dll is properly deployed with it, how that is done depends on the unmanaged dll but in the same directory is normally sufficient. If the functions do not rely on instances of the class then even simpler is P/Invoke
This answer might be overkill for a single class library, but SWIG is a good solution for "wrapping" C/C++ classes for use from other languages. It works well with C#. *See* [<http://www.swig.org/>](http://www.swig.org/).
Using C++ Class DLL in C# Application
[ "", "c#", "dll", "c++-cli", "unmanaged", "" ]
I have build an application to parse Xml file for integrating data in mssql database. I'm using Visual c# express. There's a way to make service with express edition or I a have to get Visual Studio to do it?
Absolutely you can. You can even do it with `csc`. The only thing in VS is the **template**. But you can reference the System.ServiceProcess.dll yourself. Key points: * write a class that inherits from `ServiceBase` * in your `Main()`, use `ServiceBase.Run(yourService)` * in the `ServiceBase.OnStart` override, spawn whatever new thread etc you need to do the work (`Main()` needs to exit promptly or it counts as a failed start) ## Sample Code Very basic template code would be: **Program.cs**: ``` using System; using System.ServiceProcess; namespace Cron { static class Program { /// <summary> /// The main entry point for the application. /// </summary> static void Main() { System.ServiceProcess.ServiceBase.Run(new CronService()); } } } ``` **CronService.cs**: ``` using System; using System.ServiceProcess; namespace Cron { public class CronService : ServiceBase { public CronService() { this.ServiceName = "Cron"; this.CanStop = true; this.CanPauseAndContinue = false; this.AutoLog = true; } protected override void OnStart(string[] args) { // TODO: add startup stuff } protected override void OnStop() { // TODO: add shutdown stuff } } } ``` **CronInstaller.cs**: ``` using System.ComponentModel; using System.Configuration.Install; using System.ServiceProcess; [RunInstaller(true)] public class CronInstaller : Installer { private ServiceProcessInstaller processInstaller; private ServiceInstaller serviceInstaller; public CronInstaller() { processInstaller = new ServiceProcessInstaller(); serviceInstaller = new ServiceInstaller(); processInstaller.Account = ServiceAccount.LocalSystem; serviceInstaller.StartType = ServiceStartMode.Manual; serviceInstaller.ServiceName = "Cron"; //must match CronService.ServiceName Installers.Add(serviceInstaller); Installers.Add(processInstaller); } } ``` And a .NET service application is not installed the same way as normal service application (i.e. you can't use `cron.exe /install` or some other command line argument. Instead you must use the .NET SDK's `InstallUtil`: ``` InstallUtil /LogToConsole=true cron.exe ``` ## Resources * [Creating a Windows Service in .NET](https://web.archive.org/web/20120306013942/http://www.codeguru.com:80/Csharp/Csharp/cs_network/windowsservices/article.php/c6027) by Mark Strawmyer * [Writing a Useful Windows Service in .NET in Five Minutes](https://web.archive.org/web/20151107171013/http://blogs.msdn.com:80/b/bclteam/archive/2005/03/15/396428.aspx) by Dave Fetterman * [Installing and Uninstalling Services](https://www.microsoft.com/en-us/download/details.aspx?id=55979) * [Walkthrough: Creating a Windows Service Application in the Component Designer](https://www.microsoft.com/en-us/download/details.aspx?id=55979)
You could try Visual Web Developer Express along with the coding4fun developer kit library for web services (via managed code wrappers):- <http://www.microsoft.com/express/samples/c4fdevkit/default.aspx>
How can I make service apps with Visual c# Express?
[ "", "c#", "service", "" ]
The box this query is running on is a dedicated server running in a datacenter. AMD Opteron 1354 Quad-Core 2.20GHz 2GB of RAM Windows Server 2008 x64 (Yes I know I only have 2GB of RAM, I'm upgrading to 8GB when the project goes live). So I went through and created 250,000 dummy rows in a table to really stress test some queries that LINQ to SQL generates and make sure they're not to terrible and I noticed one of them was taking an absurd amount of time. I had this query down to 17 seconds with indexes but I removed them for the sake of this answer to go from start to finish. Only indexes are Primary Keys. ``` Stories table -- [ID] [int] IDENTITY(1,1) NOT NULL, [UserID] [int] NOT NULL, [CategoryID] [int] NOT NULL, [VoteCount] [int] NOT NULL, [CommentCount] [int] NOT NULL, [Title] [nvarchar](96) NOT NULL, [Description] [nvarchar](1024) NOT NULL, [CreatedAt] [datetime] NOT NULL, [UniqueName] [nvarchar](96) NOT NULL, [Url] [nvarchar](512) NOT NULL, [LastActivityAt] [datetime] NOT NULL, Categories table -- [ID] [int] IDENTITY(1,1) NOT NULL, [ShortName] [nvarchar](8) NOT NULL, [Name] [nvarchar](64) NOT NULL, Users table -- [ID] [int] IDENTITY(1,1) NOT NULL, [Username] [nvarchar](32) NOT NULL, [Password] [nvarchar](64) NOT NULL, [Email] [nvarchar](320) NOT NULL, [CreatedAt] [datetime] NOT NULL, [LastActivityAt] [datetime] NOT NULL, ``` Currently in the database there is 1 user, 1 category and 250,000 stories and I tried to run this query. ``` SELECT TOP(10) * FROM Stories INNER JOIN Categories ON Categories.ID = Stories.CategoryID INNER JOIN Users ON Users.ID = Stories.UserID ORDER BY Stories.LastActivityAt ``` Query takes 52 seconds to run, CPU usage hovers at 2-3%, Membery is 1.1GB, 900MB free but the Disk usage seems out of control. It's @ 100MB/sec with 2/3 of that being writes to tempdb.mdf and the rest is reading from tempdb.mdf. Now for the interesting part... ``` SELECT TOP(10) * FROM Stories INNER JOIN Categories ON Categories.ID = Stories.CategoryID INNER JOIN Users ON Users.ID = Stories.UserID SELECT TOP(10) * FROM Stories INNER JOIN Users ON Users.ID = Stories.UserID ORDER BY Stories.LastActivityAt SELECT TOP(10) * FROM Stories INNER JOIN Categories ON Categories.ID = Stories.CategoryID ORDER BY Stories.LastActivityAt ``` All 3 of these queries are pretty much instant. Exec plan for first query. <http://i43.tinypic.com/xp6gi1.png> Exec plans for other 3 queries (in order). <http://i43.tinypic.com/30124bp.png> <http://i44.tinypic.com/13yjml1.png> <http://i43.tinypic.com/33ue7fb.png> Any help would be much appreciated. Exec plan after adding indexes (down to 17 seconds again). <http://i39.tinypic.com/2008ytx.png> I've gotten a lot of helpful feedback from everyone and I thank you, I tried a new angle at this. I query the stories I need, then in separate queries get the Categories and Users and with 3 queries it only took 250ms... I don't understand the issue but if it works and at 250ms no less for the time being I'll stick with that. Here's the code I used to test this. ``` DBDataContext db = new DBDataContext(); Console.ReadLine(); Stopwatch sw = Stopwatch.StartNew(); var stories = db.Stories.OrderBy(s => s.LastActivityAt).Take(10).ToList(); var storyIDs = stories.Select(c => c.ID); var categories = db.Categories.Where(c => storyIDs.Contains(c.ID)).ToList(); var users = db.Users.Where(u => storyIDs.Contains(u.ID)).ToList(); sw.Stop(); Console.WriteLine(sw.ElapsedMilliseconds); ```
Try adding an index on Stories.LastActivityAt. I think the clustered index scan in the execution plan may be due to the sorting. Edit: Since my query returned in an instant with rows just a few bytes long, but has been running for 5 minutes already and is still going after I added a 2K varchar, I think Mitch has a point. It is the volume of that data that is shuffled around for nothing, but this can be fixed in the query. Try putting the join, sort and top(10) in a view or in a nested query, and then join back against the story table to get the rest of the data just for the 10 rows that you need. Like this: ``` select * from ( SELECT TOP(10) id, categoryID, userID FROM Stories ORDER BY Stories.LastActivityAt ) s INNER JOIN Stories ON Stories.ID = s.id INNER JOIN Categories ON Categories.ID = s.CategoryID INNER JOIN Users ON Users.ID = s.UserID ``` If you have an index on LastActivityAt, this should run very fast.
So if I read the first part correctly, it responds in 17 seconds with an index. Which is still a while to chug out 10 records. I'm thinking the time is in the order by clause. I would want an index on LastActivityAt, UserID, CategoryID. Just for fun, remove the order by and see if it returns the 10 records quickly. If it does, then you know it is not in the joins to the other tables. Also it would be helpful to replace the \* with the columns needed as all 3 table columns are in the tempdb as you are sorting - as Neil mentioned. Looking at the execution plans you'll notice the extra sort - I believe that is the order by which is going to take some time. I'm assuming you had an index with the 3 and it was 17 seconds... so you may want one index for the join criteria (userid, categoryID) and another for lastactivityat - see if that performs better. Also it would be good to run the query thru the index tuning wizard.
Query against 250k rows taking 53 seconds
[ "", "sql", "linq-to-sql", "query-optimization", "" ]
This is probably a really basic problem but I can't seem to find any other articles on it. Anyway, I have written a small bouncing ball program in Java to try and expand my basic skills. The program is just a simple bouncing ball that will drop and *hopefully* bounce for a while. The original program worked fine but now I have tried to add gravity into the program. The gravity actually works fine for a while but then once the bounces get really small the animation becomes erratic for a very short time then the position of the ball just constantly decreases. I've tried to figure out the problem but I just can't see it. Any help would be most welcome. ``` public final class Ball extends Rectangle { float xspeed = 1.0f; float yspeed = 1.0f; float gravity = 0.4f; public Ball(float x, float y, float width, float height) { super(x, y, width, height); } public void update(){ yspeed += gravity; move(xspeed, yspeed); if(getX() < 0){ xspeed = 1; } if(getX() + getWidth() > 320){ xspeed = -1; } if(getY() < 0){ yspeed = 1; } if(getY() + getHeight() > 200 && yspeed > 0){ yspeed *= -0.98f; } if(getY() + getHeight() > 200 && yspeed < 0){ yspeed *= 0.98f; } } public void move(float x, float y){ this.setX(getX()+x); this.setY(getY()+y); } ``` } EDIT: Thanks that seems to have sorted the erratic movement. I'm still struggling to see how I can stop my ball moving down when it has stopped bouncing. Right now it will move stop bouncing then continue moving down passed the "floor". I think it's to do with my yspeed += gravity line. I just can't see how I'd go about stopping the movement down.
When you do ``` yspeed += gravity; ``` you are *assuming* that the ball has space move through a distance dx = v\_i \* t + 1/2 (-g) t^2. When you are very near the floor this may not be true. It fail if: * You are near enough the the floor and moving down * You are very near the floor and have low velocity (like when the ball has lost most of it's energy) This bug causes your simulation to *stop conserving energy*, resulting in the erratic behavior you see at low amplitude. You can reduce the problem by using smaller time steps, and you can get rid of it outright if you do test computation to notice when you're out of room and to select a safe time step for *that* iteration (i.e. always use your default unless there is a problem, then calculate the best time step). However, the basic approximation you're using here has other problems as well. Look in any numeric analysis text for a discussion of solving differential equations numerically.
I suspect it's because when the ball bounces, it will actually be slightly below the "ground", and at low speeds, it won't move back above the ground in one tick - so the next update() will see it still below the ground, and bounce again - but *downwards* this time, so the cycle continues. You need to move the ball back up to ground level when it bounces, something like this: ``` if(getY() + getHeight() > 200){ yspeed *= -0.981; setY(200 - getHeight()); } ```
Bouncing Ball in Java
[ "", "java", "graphics", "physics", "" ]
I need to create an RPM package from an ANT script that runs on a Windows computer. This package must contain the result classes from the build plus some other, additional resources. I guess there should be some program somewhere that can be invoked from the command line to create this package. The reason why I want to do this under windows is that we have a script that builds installers for several different platforms, and everything is already configured for windows so I want to avoid the pain of migrating everything to linux. Do you know how could this be achieved? EDIT: I've used a separate Linux machine to do this. I copy all files using the scp task, then execute the rpm command remotely using the ssh task. If this task returns a success code, I copy the resulting rpm back with scp.
I'm not aware of any packages to do this, but that could just be my ignorance speaking. Two suggestions: Set up a Linux machine (separate PC or virtual machine) and kit the rpm remotely via scripts (see [ssh](http://sshwindows.sourceforge.net/)/scp/[samba](http://en.wikipedia.org/wiki/Samba_(software))). This strikes me as a safe approach that avoids full build environment migration. A more adventurous approach would be to write your own RPM files using Java. [The RPM file format](http://www.google.co.uk/search?hl=en&client=firefox-a&rls=org.mozilla:en-GB:official&hs=qg7&q=+site:rpm.org+rpm+file+format) seems to be a header followed by one of a number of standard archive formats. Some analysis of the archive contents would be needed, so this approach might be quite time consuming in the short term (though it would probably result in faster builds).
Also consider the redline-rpm java library & ant task. <https://github.com/craigwblake/redline>
Create RPM package from ANT script under Windows
[ "", "java", "ant", "installation", "rpm", "" ]
I have a program (written in C#) that reads/writes its data directly (direct file access without server) to firebird database files. For a better exchange I want to (un)compress them on import/export for a better exchange over the internet without the need of an external program to (un)compress them. I know [#ziplib](http://www.sharpdevelop.com/OpenSource/SharpZipLib/Default.aspx) which supports Zip, GZip, Tar and BZip2. What else free compression libraries for C# do you know? Is there a .NET library which supports LZMA so i can read/write ".7z" files?
There is a good article written by Peter Bromberg: [7Zip (LZMA) In-Memory Compression with C#](https://web.archive.org/web/20081207080706/http://www.eggheadcafe.com:80/tutorials/aspnet/064b41e4-60bc-4d35-9136-368603bcc27a/7zip-lzma-inmemory-com.aspx) > Shows a simple C# > `SevenZip.Compression.Lzma.SevenZipHelper` > class to enable high-compression of > in-memory objects with C#. Adds a new > 7Zip format LZMA Cookie Compression > class to the previously published > CookieCompression utility.
7-zip has a free source code, public domain C# SDK for the LZMA algorithm: <http://www.7-zip.org/sdk.html>
Free compression library for C# which supports 7zip (LZMA)
[ "", "c#", "compression", "7zip", "lzma", "" ]
I have a class containing a worker thread which receives data from a queue in a loop. Another part of the app sinks an event from this class, which the class raises for each queue item. These events are fired asynchronously, so at busy times the other part of the app can be processing several events at once. This should be fine but we've discovered a scenario where this can cause problems. We need a quick solution while the main issue gets addressed. Does the framework provide a simple way I can force the worker thread to wait while each event gets processed (so they are processed sequentially)? If not, what's the easiest way to implement this?
A simple answer would be to lock() on a single object in the event handler. All of the theads would wait to get the lock.
The [ManualResetEvent class](http://msdn.microsoft.com/en-us/library/system.threading.manualresetevent(VS.71).aspx) might help you here, unless I'm not understanding your question. You can use it to block the firing of the next event until the last one completes.
C# .NET 3.5 : How to invoke an event handler and wait for it to complete
[ "", "c#", ".net", "asynchronous", "events", "worker", "" ]
For example, not to build queries by string manipulation, and the like.
looks there are no such files...
I'm not aware of any such checks, but if you want to go that road you either have the option presented above by VonC or you might take a different path and take a look at AspectJ declare error and/or declare warning. The main difference is that using AspectJ you'll be able to impose these rules upon compilation. Anyways, if you are more familiar with PMD maybe it would be better to stay on that land. ./alex
Do you know of PMD or Checkstyle rules that will enforce hibernate best practices?
[ "", "java", "hibernate", "checkstyle", "pmd", "" ]
A question that came to one of my colleagues mind, what is the best way to check if a query string is an int. I suggested using the classic Int.Parse and try and catch, also TryParse was suggested. Actually i can't think of any other ways. Any ideas?
[`Int32.TryParse`](http://msdn.microsoft.com/en-us/library/system.int32.tryparse.aspx) is going to be your best bet.
TryParse is probably your best bet, since it will allow for different formats for the string, as well as tell you through a boolean value whether or not it is valid.
The optimal way to check if a query string is an int?
[ "", "c#", "asp.net", "" ]
I'm using the new System.Xml.Linq to create HTML documents (Yes, I know about HtmlDocument, but much prefer the XDocument/XElement classes). I'm having a problem inserting `&nbsp;` (or any other HTML entity). What I've tried already: 1. Just putting text in directly doesn't work because the & gets turned int &. `new XElement("h1", "Text&nbsp;to&nbsp;keep&nbsp;together.");` 2. I tried parsing in the raw XML using the following, but it barfs with this error: XElement.Parse("Text to keep together."); --> Reference to undeclared entity 'nbsp'.` 3. Try number three looks like the following. If I save to a file, there is just a space, the `&#160;` gets lost. --- ``` var X = new XDocument(new XElement("Name", KeepTogether("Hi Mom!"))); private static XNode KeepTogether(string p)` { return XElement.Parse("<xml>" + p.Replace(" ", "&#160;") + "</xml>").FirstNode; } ``` I couldn't find a way to just shove the raw text through without it getting escaped. Am I missing something obvious?
> I couldn't find a way to just shove the raw text through without it getting escaped. Just put the Unicode character in that &nbsp; refers to (U+00A0 NO-BREAK SPACE) directly in a text node, then let the serializer worry about whether it needs escaping to &#160; or not. (Probably not: if you are using UTF-8 or ISO-8859-1 as your page encoding the character can be included directly without having to worry about encoding it into an entity reference or character reference). ``` new XElement("h1", "Text\u00A0to\u00A0keep\u00A0together"); ```
Replacing the & with a marker like ##AMP## solved my problem. Maybe not the prettiest solution but I got a demo for a customer in 10 mins so...I don't care :) Thx for the idea
How to put in text when using XElement
[ "", "c#", "html", "linq", "" ]
How do I get the internal serial number of a USB-Stick or USB-HardDrive in C#?
Try this: ``` // add a reference to the System.Management assembly and // import the System.Management namespace at the top in your "using" statement. // Then in a method, or on a button click: ManagementObjectSearcher theSearcher = new ManagementObjectSearcher("SELECT * FROM Win32_DiskDrive WHERE InterfaceType='USB'"); foreach (ManagementObject currentObject in theSearcher.Get()) { ManagementObject theSerialNumberObjectQuery = new ManagementObject("Win32_PhysicalMedia.Tag='" + currentObject["DeviceID"] + "'"); MessageBox.Show(theSerialNumberObjectQuery["SerialNumber"].ToString()); } ``` *Source: [http://social.msdn.microsoft.com/forums/en-US/Vsexpressvcs/thread/f4447ed3-7e5f-4635-a28a-afff0b620156/](http://social.msdn.microsoft.com/forums/en-US/Vsexpressvcs/thread/f4447ed3-7e5f-4635-a28a-afff0b620156)*
A solution using Win32 [is described here](https://web.archive.org/web/20090328094546/http://www.emmet-gray.com/Articles/USB_SerialNumbers.htm) Edit: the original link seems to have gone missing. The above is a cached copy, and the author also wrote some sample code in VB.Net which is [still online here](http://www.emmet-gray.com/Files/AdminTools/USB_SerialNumber.zip).
How to get serial number of USB-Stick in C#
[ "", "c#", "usb", "usb-drive", "" ]
I have a hosted site and I'm having trouble configuring Joomla (running Joomla + php + mySQL on IIS7 + win server 2008). I have a similar configuration running on a local machine (Joomla + php + mySQL on IIS7 + vista x64), so I was at least able to follow instructions showed in various tutorials on how to set this up. This symptom with the hosted site is that I can't turn on any SEO settings in Joomla (not even the first setting, "Search Engine Friendly URLs"). I get either 404 (file not found) or the URL appears correctly rewritten but it's always the home page's content that is displayed. I had a similar issue on my home machine and it turns out to have been because I wasn't using FastCGI to host php, so I decided to investigate that on the hosted site. Anyway, I noticed in the web.config file of the directory hosting joomla on the hosted site the following line: ``` <add name="Plesk_Handler_3522909676" path="*.php" verb="*" modules="IsapiModule" scriptProcessor="c:\program files (x86)\parallels\plesk\additional\pleskphp5\php5isapi.dll" resourceType="Either" /> ``` From past experience, I know that php has some issues when not running under fastCGI. I noticed the web.config in the root folder used the following line instead: ``` <add name="Plesk_Handler_0286090609" path="*.php" verb="*" modules="CgiModule" scriptProcessor="c:\program files (x86)\parallels\plesk\additional\pleskphp5\php-cgi.exe" resourceType="Either" /> ``` I copied that in the web.config in the joomla directory, and got different behavior... but still not working. If I load a .php file in the joomla directory that runs phpInfo(), under Server API it says CGI/FastCGI . Is that **positive confirmation** that FastCGI is being used? Why does the handler in the web config point to modules="CgiModule" instead of modules="FastCgiModule" (I'm not even sure that exists, but I just find the mention of CgiModule suspicious). It's a hosted site, so as far as I know I don't have access to ApplicationHost.config file...
Here's a simple test: 1. Create a phpinfo.php file with ``` <?php phpinfo(); ?> ``` inside; 2. Request <http://yoursite.com/phpinfo.php/foobar?foo=bar> 3. Check the output of phpinfo and look for \_SERVER["REQUEST\_URI"]. If this variable is missing, then CGI is used. If the variable is present and correctly set to /phpinfo.php/foobar?foo=bar, then either ISAPI or FastCGI is used. Look near the top of the output for Server API; it should be set to either ISAPI (which means ISAPI is being used) or CGI/FastCGI (which means FastCGI is being used, since we already ruled out CGI).
php\_sapi\_name() or PHP\_SAPI, both work. <http://php.net/manual/en/function.php-sapi-name.php> ``` <?php if (php_sapi_name() != 'cgi-fcgi'){ echo 'I knew fastcgi wasn\'t working.'; }else{ echo 'Holy crap, something worked for once.'; } ```
How to know for sure if FastCGI is being used to run php scripts
[ "", "php", "iis", "iis-7", "fastcgi", "" ]
I have a List containing a lot of paths. I have a specific path I want to check against this list to see if there are any paths there that uses this path, ie: ``` f.StartsWith(r.FILENAME) && f != r.FILENAME ``` What would be the fastest way of doing this? edit: Complete function from answer below: ``` static bool ContainsFragment(string[] paths, string fragment) { // paths **must** be pre-sorted via Array.Sort(paths); if (paths.Length == 0) return false; int index = Array.BinarySearch(paths, fragment); if (index >= 0 && index+1 < paths.Length) { //we found it if (paths[index + 1].StartsWith(fragment) && paths[index + 1].EndsWith(".manifest")) { return true; } } return false; } ```
The *fastest* way is probably with binary search: ``` static bool ContainsFragment(string[] paths, string fragment) { // paths **must** be pre-sorted via Array.Sort(paths); if (paths.Length == 0) return false; int index = Array.BinarySearch(paths, fragment); // we want the index of the *next highest* path if (index < 0) { // no match index = ~index; } else { // exact match index++; // for strict substring (non-equal) } return index < paths.Length && paths[index].StartsWith(fragment); } ``` But the cost of sorting the array will outweigh any benefit if you are only doing it a few times; in which case, just scan the array - either with LINQ etc, or just: ``` bool found = false; for(int i = 0 ; i < paths.Length ; i++) { if(paths[i].StartsWith(fragment) && paths[i].Length != fragment.Length) { found = true; break; } } ```
``` var matches = list.Where(f => f.StartsWith(r.FILENAME) && f != r.FILENAME); ``` Or if you only care about existence: ``` bool any = list.Any(f => f.StartsWith(r.FILENAME) && f != r.FILENAME); ``` This is assuming you're using .NET 3.5, admittedly - otherwise there are similar methods in `List<T>` and you can use an anonymous method.
Searching for the beginning of a string in an array in C#
[ "", "c#", ".net", "arrays", "string", "" ]
So I've been running into a debate at work about what the proper role of a scripting language is in game development. As far as I can tell there are two schools of thought on this: 1) The scripting language is powerful and full featured. Large portions of game code are written in the language and code is only moved into C++ when performance dictates that it's necessary. This is usually something like Lua or Unrealscript. 2) This scripting language is extremely limited. Almost all game code is in C++ and the language is only there to expose the underlying functionality to designers. My frustration comes from seeing approach number two frequently abused, with large systems implemented in a language that does not have the features that make that code maintainable. So I started out supporting approach number one, but after talking to some designers I realized that many of them seem to prefer number two, and its mostly programmers who prefer one. So I'm still left wondering which approach is better. Am I just seeing bad code and blaming the tool instead of the programmer, or do we need really need a more complex tool?
I think designers need to see a language suitable for them. That's not negotiable: they have to spend their time designing, not programming. If scripting allows fast development of product-worthy game code, then the programmers should be doing it too. But it has to be product-worthy: doing everything twice doesn't save time. So you have to keep scripting in its place. If a developer can script the inventory system in a week, or write it in C++ in a month, then you want full-featured scripting, if only to give you more time to hand-optimise the parts that might conceivably hit performance limits. So not the inventory, or the high-score table, or the key-mapping system, or high-level game logic like what the characters are supposed to be doing. That can all be scripted if doing so saves you any time at all to spend on speeding up the graphics and the physics: programmers need to be able to work out exactly what the bottlenecks are, and senior programmers can make a reasonable prediction what won't be. Designers probably shouldn't know or care whether the programmers are using the scripting language to implement game code. They shouldn't have an opinion whether (1) is good or bad. So even if the programmers are right to want (1), why is this inconveniencing the designers? How have they even noticed that the scripting language is full-featured, if all they ever need is a fairly small number of standard recipes? Something has gone wrong, but I don't think it's that Lua is too good a language. One possibility is that using the same scripting language for both, becomes an obstacle to drawing a sharp line between the interfaces used by designers, and the interfaces internal to the game code. That, as I said at the top, is not negotiable. Even if they're using the same scripting language, programmers still have to provide the designers with the functionality that they need to do their job. Just because designers use Lua to code up AI strategies and conversation trees, and Lua is full-featured language capable of writing a physics engine, doesn't mean your designers are expected to write their own physics engine. Or use more than 10% of Lua's capabilities. You can probably do both (1) and (2), mind. There's no reason you can't give the programmers Lua, and the designers some miniature under-featured DSL which is "compiled" into Lua with a Lua script.
The compile-link-run-test cycle for compiled C++ code when you're dealing with something as complex as a video game is very, very slow. Using a scripting engine allows you to make large functional changes to the game without having to compile the program. This is a massive, massive time savings. As you say, things that need optimization can be moved into C++ as required. AAA engines are highly driven by scripting. Torque, used for Tribes II (and many other games!) is scripted, Unreal has Unrealscript and so on. Scripting isn't just for mods, it's key to efficient development.
The role of scripting languages in game Programming
[ "", "c++", "scripting", "" ]
How can I login to AD without logout from current user and get new logged user's rights. (OS: Windows XP) ### Note: Not to Modify AD or something like this.Only wanna to login with another user from C# and getting new login's permissions/rights. (I wanna use this rights not only in current thread but also whole explorer. Like deleting files, creating directories, changing Network options.) Is this possible?
You can use impersonation to change thread identity to a different user, given a valid username and password. There is no way to change the user identity for the whole shell other than logging in as a different user manually, but anything executed on the thread you impersonate on will receive the new rights. The .NET 1.1 way, using P/Invoke: * [Windows Impersonation using C#](http://www.codeproject.com/KB/cs/cpimpersonation1.aspx) * [A small C# Class for impersonating a User](http://www.codeproject.com/KB/cs/zetaimpersonator.aspx) The .NET 2+ way, using Thread.CurrentPrincipal: * [How To Impersonate A User Given Her Token](http://alt.pluralsight.com/wiki/default.aspx/Keith.GuideBook/HowToImpersonateAUserGivenHerToken.html) * [Directly Accessing a Principal Object](http://msdn.microsoft.com/en-us/library/wefzhcez.aspx)
Maybe [this article](http://alt.pluralsight.com/wiki/default.aspx/Keith.GuideBook/HowToImpersonateAUserGivenHerToken.html) might be helpful. It is a tutorial on [`WindowsImpersonationContext`](http://msdn.microsoft.com/en-us/library/system.security.principal.windowsimpersonationcontext.aspx).
How can I login to Active Directory with C#?
[ "", "c#", ".net", "authentication", "active-directory", "" ]
Can I have nested try-catch blocks? For example: ``` void f() { try { //Some code try { //Some code } catch(ExceptionA a) { //Some specific exception handling } //Some code } catch(...) { //Some exception handling } }//f ```
Yes perfectly legal. Though it would be best to move inner ones into another method so it looks cleaner and your method(s) are smaller
As already stated, it is possible, but you have to see the 'fall-through'-scheme in this. If in the first try-catch-block your exception is caught, it will not get caught by the outer catch-block. However if it does not get caught by the inner catch-block, it will try to find a matching exception-handler in the outer catch-block. You can also explicitely raise the exception further to the next exception-handler by using `throw;` in your inner exception-handler. For example this code: ``` try { try { throw std::runtime_error("Test"); } catch (std::runtime_error& e) { std::cerr << "Inner Exception-Handler: " << e.what() << std::endl; throw; } } catch (std::exception& e) { std::cerr << "Outer Exception-Handler: " << e.what() << std::endl; } ``` Will result in: ``` Inner Exception-Handler: Test Outer Exception-Handler: Test ``` This works because [std::runtime\_error is derived from std::exception](http://cplusplus.com/reference/std/stdexcept/runtime_error.html). You should also note that in such a trivial example it is also possible to just write the catch-blocks after each other, but if you want to execute other code after the first catch-block you will have to nest them.
Can I have nested try-catch blocks in C++?
[ "", "c++", "exception", "nested", "" ]
In web applications user login information is usually stored in a session but how about windows applications? Is using a singleton the right thing to do? Should I just use a static property? Lets say that I store the login information in a static property ApplicationController. LoggedInUser. When a user logs in successfully, that property is set. Before a successful login, LoggedInUser returns null. Then when calling for an example OrdersService from my OrderListPresenter-class, I use the LoggedInUser as a parameter. ``` var service = new OrdersService(); var orderCollection = service.GetOrdersByUserID( ApplicationController.LoggedInUser.ID); ``` Ok, this works but it also makes writing the unit tests somewhat harder. I don't like working with singletons / static members from my unit tests. Maybe I could inject the ApplicationController to every class which needs to access logged in user? Any other ideas? What do you think is the best way to handle this?
Injection is a good answer. You'll probably find other things useful to put in an `ApplicationController`, and it makes it easy to unit-test.
I would create a CurrentContext object which contains a CurrentUser field and pass it around to all my presenters. [Avoid singleton](http://misko.hevery.com/2008/08/17/singletons-are-pathological-liars/), that could be problematic to unit test or if you decide to expand your application later on.
Storing login information in a Windows Application
[ "", "c#", "winforms", "session", "authentication", "" ]
Where can I get started writing a media server in C# like PlayOn <http://www.themediamall.com/playon> UPDATE: I have learned that PlayOn is a is a DLNA/UPnP media server but I am still looking for C# example implementation of this type of server. I am placing a bounty and will award it if you can point me to some sample code that I can use to server photos and/or video content to a media client like XBOX 360, Playstation 3, Media Center, or Media Center Extenders
After more research I have learned that PlayOn is a is a [DLNA](http://www.dlna.org/industry/certification/guidelines/)/[UPnP](http://en.wikipedia.org/wiki/UPnP_AV_MediaServers) media server. There is not lots of information on it but there are a few. If anyone can reference an example that would be awesome. here some links I found after discovering I was looking for [DLNA](http://www.dlna.org/industry/certification/guidelines/)/[UPnP](http://en.wikipedia.org/wiki/UPnP_AV_MediaServers) [Creating a DLNA server/service in VB.NET](https://stackoverflow.com/questions/274470/creating-a-dlna-server-service-in-vb-net) [C# UPNP/DNLA Media Server Library](https://stackoverflow.com/questions/418451/c-upnp-dnla-media-server-library)
[This](https://stackoverflow.com/questions/544152/connect-my-360-to-an-application) question may also help point you in the right direction. Specifically the accepted answer point to the [Platinum UPnP library](http://www.plutinosoft.com/blog/projects/platinum). Whilst it's a C++ library, it looks promising and i'm sure it could be integrated with a C# solution or at least give you ideas for your own implementation.
Where can I get started writing a media server in C# like PlayOn
[ "", "c#", "asp.net", "media", "upnp", "dlna", "" ]
I'm currently involved in a project developing applications primarily for Linux (Fedora 10). However, it might be the case later on that we will have to port these applications to Mac OS X and Windows and we don't want to be caught out by choosing the wrong GUI toolkit.\* For a variety of legacy reasons we are locked into using Java. We are in the process of deciding between using Qt Jambi and SWT for the GUI. I haven't much experience in using either of them so I'm doing some small prototypes to try and get a feel for them. So far (just developing on Linux) there isn't much difference between them. However, there's a limit to the depth I can go in a short time. This is why I'm asking for help. The particular features of interest to us are: * Frameless windows * custom shaped windows (i.e. not rectangular) * aesthetically pleasing Does anyone have any experiences and/or insights into these two libraries that might trip us up later? * Agile programming people will no doubt jump on the phrase "might be ... later on" and say we shouldn't worry about it. However, in the absence of other deciding factors between the toolkits, future extensibility options will do. I promise not to write any cross-platform specific code until I have to :) **Update 11 Feb:** Thanks for the great answers. For those that are curious, we will probably go with Jambi. It was mostly the style sheet functionality that won me over as they make easy a lot of the custom widget shape stuff we need to do. The Qt suite of examples showed that frameless, custom-shaped windows do indeed work on different platforms, so we shouldn't be caught short down the track. The LGPL release was why we were considering Jambi at all :)
I agree with Vinegar: Don't rule out Swing. I've developed both with Swing and with SWT, but not with Qt. With Swing, your code will be automatically cross-platform. With SWT, your code is cross-platform with a little effort, although not that much effort. Are you going to implement a local application, an Applet, or a Web Start application? The advantage of SWT is that it uses all native widgets. (familiar Look-and-feel.) The disadvantage of SWT is that it uses all native widgets. (not as many widgets as Swing has) Whether this is more an advantage or a disadvantage depends on what you are doing and what your goals are. This means that Swing has a greater breadth of widgets. However, there are a few things that SWT does that Swing doesn't do as well (or at all) -- such as launch the system's native browser and execute JavaScript scripts in this browser. If you consider SWT, consider it carefully. If you have certain needs (such as executing JavaScript in a browser window that was launched by your application), then it may be your best choice. However, if Swing can entirely meet your needs, it may be a better choice. Hopefully someone else can provide information about Qt Jambi. Note that support should be a consideration in your decision. With SWT, there is a smaller community supporting it. With Swing, a larger community, but this does not mean that fixes will get more quickly into a development release. With Qt Jambi and with SWT, if a bug is fixed, you just distribute updated libraries with your application. With Swing, you have to wait for an updated JRE. Neither is necessarily a dealbreaker, but it has to be considered. Licensing fees may or may not be a consideration. SWT and Swing, of course, do not have licensing fees Jambi I don't know about either way, but it may depend on your intended use -- for example, are you distributing a GPL application, or a commercially licensed one. Good luck.
I have no experience with SWT, yet I was working with Jambi/Qt, Swing and GTK as well. The only problem with Qt/Jambi is licensing in my opinion (you must either publish your soft under GPL or buy commercial license). You can't start writing software for free and then "see what happens". You must be sure that your software will be success, because you have to buy licenses. This in many times is not a case. Regards. Ooops, I overlook those comments, thanks for the reply. This is great news! Good move from Nokia. @cursa that wasn't said, so also note that Qt/Jambi is more than widget toolkit. You have classes for networking, strings manipulation (along with regexp engine), mutexes, 2d vector & raster graphics, openGL and many more. This gives real boost to application development. I also recommend downloading Qt package to Jambi noobies, because of very nice help browser called Assistant which Jambi is lacking. All the API of Qt and Jambi is the same (except slots and signals), even documentation is unchanged so you can use it interchangeably.
Qt Jambi vs SWT for cross-platform GUI development
[ "", "java", "user-interface", "cross-platform", "swt", "jambi", "" ]
I would like to be able to get a list of all Spring application contexts from the web applications running in my servlet container. This so so that I can re-initialise the contexts without restarting or reloading my container or webapps. Is this possible? If so, how? Is there anyway to get a list of all the servlet contexts running on a servlet container instance through the Servlet API?
**[Edit: This doesn't really help, as each web.xml would have to have the same listener]** You could have a [ServletContextAttributeListener](http://java.sun.com/javaee/5/docs/api/javax/servlet/ServletContextAttributeListener.html) listen out for insertions of the standard [WebApplicationContext](http://static.springframework.org/spring/docs/2.5.x/api/org/springframework/web/context/WebApplicationContext.html#ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE) attribute, and then notify some centralised monitor? Not tested: ``` public class SpringWACListener implements ServletContextAttributeListener { public void attributeAdded(ServletContextAttributeEvent scab) { if (WebApplicationContext. ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE. equals(scab.getName()) { myCentralisedMonitor.notify("added"); } } // same for others } ```
No - to both questions. Access to all servlet contexts would be a security problem. You would be able to inspect and/or manipulate other webapps. The only one knowing all servlet contexts is the container itself. But this is internal implementation, there is no api. Spring context access is similar, but if you mean all spring contexts in one webapp, they will create a hierarchy - those for controllers for example. Implementing an `org.springframework.context.ApplicationListener` as bean in the root spring context (as initialized by the `org.springframework.web.context.ContextLoaderListener` configured in the `web.xml`) can notify you about contexts started, stopped, closed or refreshed.
Is there a way to get a list of all the Spring application contexts running in the JVM?
[ "", "java", "spring", "servlets", "" ]
Is there any way to override the line numbers in Java (e.g., by using some kind of preprocessor directive)? I am "compiling" a high-level language, down to Java byte code using Janino. I need compiler errors to report the line from the original file, not the generated Java code. C# has the #line directive, and I've successfully exploited it to map line numbers from a source file to the compiled result. I need the same for Java. Thanks!
Using Janino you can derive from `Scanner` and override the `location()` method. This method returns a Location object. You can override the `read()` method to look for annotations, within comments for instance (added during code generation), that hold line number information. You simply pass *your* scanner to the `SimpleCompiler.cook()` method and you can control what filename, line and column get reported on error.
I've never seen it used for other than JSP, but [JSR-45](http://jcp.org/aboutJava/communityprocess/review/jsr045/index.html) was designed to be used for this purpose for any source language. The process involves creating a second file in a special format ("SMAP") that maps line numbers in the original source to line numbers in the generated Java source code.
Overriding line number in generated Java source
[ "", "java", "annotations", "code-generation", "janino", "" ]
I want to print a table mixed with string and float values, as tab delimited output printout. Sure I can get the job done: ``` >>> tab = [['a', 1], ['b', 2]] >>> for row in tab: ... out = "" ... for col in row: ... out = out + str(col) + "\t" ... print out.rstrip() ... a 1 b 2 ``` But I have a feeling there is a better way to do it in Python, at least to print each row with specified delimiter, if not the whole table. Little googling (from [here](http://skymind.com/~ocrow/python_string/)) and it is already shorter: ``` >>> for row in tab: ... print "\t".join([str(col) for col in row]) ... a 1 b 2 ``` Is there still a better, or more Python-ish, way to do it?
Your shorter solution would work well as something quick and dirty. But if you need to handle large amounts of data, it'd be better to use `csv` module: ``` import sys, csv writer = csv.writer(sys.stdout, delimiter="\t") writer.writerows(data) ``` The benefit of this solution is that you may easily customize all aspects of output format: delimiter, quotation, column headers, escape sequences...
I don't think it's going to get much better than your second code snippet... maybe, if you really want, ``` print "\n".join("\t".join(str(col) for col in row) for row in tab) ```
What is the best way to print a table with delimiters in Python
[ "", "python", "coding-style", "" ]
Is there a FREE library which will allow me to open a pdf and show it on a winform project. I know I could open it in adobe reader or something but it always seems so bloated to me and I would be relying on it being installed. Is there a nice lightweight alternative where I could just include a dll in my project or similar avoiding external dependencies. I don't need much functionality just view, change page zoom.. I have seen a few libraries but they seem to be about creating PDF's not viewing.
The ActiveX control installed with acrobat reader should work, either drop it in via the designer or use something like [this](http://www.codeproject.com/KB/dotnet/AxForms.aspx). This will require the relevant version of the reader is installed on the client but since you indicate that you could just launch that anyway this should not be a problem. reader
I'm not sure what you call a 'dependency' since you'll always have to rely on some external code to render the PDF unless you bundle the whole PDF rendering source inside your project. There are some commercial renderers and *very few* free ones. If you want to avoid dependencies that you can't bundle then maybe you could have a look at the [source code](http://code.google.com/p/sumatrapdf/) for [SumatraPDF](http://blog.kowalczyk.info/software/sumatrapdf/), an OpenSource PDF viewer for windows that uses [MuPDF](http://www.mupdf.com/). There is also [Poppler](http://freedesktop.org/wiki/Software/poppler), a rendering engine that uses [Xpdf](http://www.foolabs.com/xpdf/home.html) as a rendering engine. All of these are great but they will require a fair amount of commitment to make make them work and interface with .Net. Most other open source libraries are only used for creating and managing PDF pages and I don't know any that actually does rendering; it's such a hard problem to solve right. You may still want to consider using [GhostScript](http://pages.cs.wisc.edu/~ghost/) as an interpreter because rendering pages is a fairly simple process. The drawback is that you will need to either re-package it to install it with your app, or make it a pre-requisite (or at least a part of your install process). It's not a big challenge, and it's certainly easier than having to massage the other rendering engines into .Net. Have a look at [this SO question](https://stackoverflow.com/questions/541891/pdf-previewing-and-viewing/550475#550475) I answered today. It contains some more information and a link to some [working .Net code](http://community.devexpress.com/forums/p/55582/188207.aspx#188207) I posted on another forum a few months ago.
.NET open PDF in winform without external dependencies
[ "", "c#", ".net", "" ]
I am trying to create a link list, but I am having trouble creating objects inside a function and assigning pointers to their addresses, since I believe they go out of scope when the function exits. Is this true? And, if so, how can I create an object outside the main and still use it?
Create the objects with the new operator. ie ``` void foo( myObject* bar1, myObject* bar2 ) { bar1 = new myObject(); bar2 = new myObject(); // do something } int main( int argc, char* argv[] ) { myObject* thing1; myObject* thing2; foo( thing1, thing2 ); // Don't forget to release the memory! delete thing1; delete thing2; return 0; } ```
You are correct, local variables will go out of scope at the end of the function block. You need to create pointers to the objects and allocate them with [new](http://msdn.microsoft.com/en-us/library/kewsb8ba.aspx). And don't forget to delete the object when you remove it from your list. If you don't want to deal with the hassles and bugs that come with pointers, see [boost::shared\_ptr](http://www.boost.org/doc/libs/1_38_0/libs/smart_ptr/shared_ptr.htm) instead.
Returning the addresses of objects created outside the main() function
[ "", "c++", "visual-c++", "pointers", "" ]
I'm looking for an open source implementation, preferably in python, of **Textual Sentiment Analysis** (<http://en.wikipedia.org/wiki/Sentiment_analysis>). Is anyone familiar with such open source implementation I can use? I'm writing an application that searches twitter for some search term, say "youtube", and counts "happy" tweets vs. "sad" tweets. I'm using Google's appengine, so it's in python. I'd like to be able to classify the returned search results from twitter and I'd like to do that in python. I haven't been able to find such sentiment analyzer so far, specifically not in python. Are you familiar with such open source implementation I can use? Preferably this is already in python, but if not, hopefully I can translate it to python. Note, the texts I'm analyzing are VERY short, they are tweets. So ideally, this classifier is optimized for such short texts. BTW, twitter does support the ":)" and ":(" operators in search, which aim to do just this, but unfortunately, the classification provided by them isn't that great, so I figured I might give this a try myself. Thanks! BTW, an early demo is [here](http://twitgraph.appspot.com/?show_inputs=1&duration=30&q=youtube+annotations) and the code I have so far is [here](http://code.google.com/p/twitgraph/) and I'd love to opensource it with any interested developer.
With most of these kinds of applications, you'll have to roll much of your own code for a statistical classification task. As Lucka suggested, NLTK is the perfect tool for natural language manipulation in Python, so long as your goal doesn't interfere with the non commercial nature of its license. However, I would suggest other software packages for modeling. I haven't found many strong advanced machine learning models available for Python, so I'm going to suggest some standalone binaries that easily cooperate with it. You may be interested in [The Toolkit for Advanced Discriminative Modeling](http://tadm.sf.net), which can be easily interfaced with Python. This has been used for classification tasks in various areas of natural language processing. You also have a pick of a number of different models. I'd suggest starting with Maximum Entropy classification so long as you're already familiar with implementing a Naive Bayes classifier. If not, you may want to look into it and code one up to really get a decent understanding of statistical classification as a machine learning task. The University of Texas at Austin computational linguistics groups have held classes where most of the projects coming out of them have used this great tool. You can look at the course page for [Computational Linguistics II](http://comp.ling.utexas.edu/jbaldrid/courses/2006/cl2/) to get an idea of how to make it work and what previous applications it has served. Another great tool which works in the same vein is [Mallet](http://mallet.cs.umass.edu/). The difference between Mallet is that there's a bit more documentation and some more models available, such as decision trees, and it's in Java, which, in my opinion, makes it a little slower. [Weka](http://www.cs.waikato.ac.nz/ml/weka/) is a whole suite of different machine learning models in one big package that includes some graphical stuff, but it's really mostly meant for pedagogical purposes, and isn't really something I'd put into production. Good luck with your task. The real difficult part will probably be the amount of knowledge engineering required up front for you to classify the 'seed set' off of which your model will learn. It needs to be pretty sizeable, depending on whether you're doing binary classification (happy vs sad) or a whole range of emotions (which will require even more). Make sure to hold out some of this engineered data for testing, or run some tenfold or remove-one tests to make sure you're actually doing a good job predicting before you put it out there. And most of all, have fun! This is the best part of NLP and AI, in my opinion.
Good luck with that. Sentiment is enormously contextual, and tweeting culture makes the problem worse because *you aren't given the context* for most tweets. The whole point of twitter is that you can leverage the huge amount of shared "real world" context to pack meaningful communication in a very short message. If they say the video is bad, does that mean bad, or *bad*? > A linguistics professor was lecturing > to her class one day. "In English," > she said, "A double negative forms a > positive. In some languages, though, > such as Russian, a double negative is > still a negative. However, there is no > language wherein a double positive can > form a negative." > > A voice from the back of the room > piped up, "Yeah . . .right."
Sentiment analysis for Twitter in Python
[ "", "python", "machine-learning", "nlp", "open-source", "sentiment-analysis", "" ]
I use this type of construct often. ``` response = new LocationResponse (); response.LocationDetails = new LocationDetail[4]; response.LocationDetails[0] = new LocationDetail(); response.LocationDetails[0].site = "ABCDE"; ... ``` The piece I don't fully understand is this piece: **response.LocationDetails[0] = new LocationDetail();** Why does each individual element of the array have to be instantiated? If you leave it out, you get undefined exceptions.
Well if an array elements were automatically instantiated, you would be locked into which classes you defined the array with. You wouldn't be able to use arrays of abstract classes or interfaces or any object which doesn't have a default constructor. This is just naming a few problems with automatically instantiating objects in an array.
You don't need to instantiate LocationDetail if it is a value type (struct). You have to instantiate it if it's a class because the default value for a reference type is null. This code works: ``` public struct LocationDetail { private string site; public string Site { get { return site; } set { site = value; } } } static void Main(string[] args) { LocationResponse response = new LocationResponse(); response.LocationDetails = new LocationDetail[4]; response.LocationDetails[0].Site = "ABCDE"; Console.Write(response.LocationDetails[0].Site); } ```
C# - Why do you need to instantiate each array element?
[ "", "c#", "arrays", "" ]
I have a piece of data. At the moment, it's an XML file, but the architecture may change. So let's assume for the moment it's a C# Class. When I store the data on disk or in the database, I need to add some sort of signature or fingerprint or checksum or whatever to ensure that no one can modify the data. The caveat: even an administrator or developer with access to all source code should not be able to modify it. I assume that since someone with full code access can create a new signature easily (the signing needs to be done programatically, so no manual passphrase entry), the signature somehow needs to contain some additional data. Ideally I should be able to extract this data back from the signature, for example the date of signing and some strings. My general approach is to use symmetric encryption. I generate a Hash, i.e. SHA-512 from all the fields and then encrypt that hash and my additional data with to get my signature, using the hash as password. To decrypt, my function would generate the hash from the actual data in the file, and try to decrypt the signature. That would not be tamper-proof though as it's easy to generate a signature where the signing date and additional information is still intact. As I am not an expert on the field, I believe that I am trying to re-invent the wheel, and that it's not a very good wheel. I just wonder if there is some standard approach? I believe that part of my request is impossible (after all, if someone controls the entire environment, that person also controls the system time), but I still wonder how this is generally tackled?
It sounds to me like you want a combination of a [digital signature](http://www.rsa.com/rsalabs/node.asp?id=2182) with a [secure digital timestamp](http://www.rsa.com/rsalabs/node.asp?id=2347). In brief, after signing your data, you call a third party web service to provide an official timestamp and their own digital signature linking that timestamp to your signature value, thus providing evidence that the original signature (and thus the original data) was created on or before that date. With this scheme, even if the original signing key is later compromised, revoked or otherwise invalidated, any signatures that were made before the invalidation are still valid thanks to the timestamp. A tamper-resistant hardware signature device may help. If the target hardware is fairly recent it may have some support already on the motherboard in the form of a [TPM](http://en.wikipedia.org/wiki/Trusted_Platform_Module), but there are plenty of vendors out there willing to charge an arm and a leg for their own [hardware security modules](http://en.wikipedia.org/wiki/Hardware_Security_Module), or somewhat less for a [smart card](http://en.wikipedia.org/wiki/Smart_card). Sufficient security may not be achievable by technology alone. You may need independent validation of the system. You may need remote CCTV monitoring and recording of the machine's location or other physical security measures to detect or stop tampering. You may need third-party code escrow, review and signing to ensure that the code loaded on the machine is what was intended, and to deter and/or detect the insertion of backdoor logic into the code. The bottom line is that how much money, time and effort you need to spend on this depends very much on what you stand to lose if records are forged.
You need both a [digital signature](http://en.wikipedia.org/wiki/Digital_signature) and a [trusted timestamp](http://en.wikipedia.org/wiki/Trusted_timestamping). The trusted timestamp gets a third-party involved to validate the message. Then any attacker doesn't have 'full control' of the whole system.
Generating a Tamper Proof Signature of some data?
[ "", "c#", ".net", "" ]
In a Web Service context, I have the following class which inherit from the class Mammal. The Mammal class is defined in a proxy. I cannot change the definition of that class. Because I need to add some methods to the class Mammal on the client side, I inherited Mammal and created Giraffe. ``` namespace TestApplication { public class Giraffe : Mammal { public Giraffe() { } } } ``` When I call a WebMethod which expect an object of type Mammal, I get the following exception telling me that Giraffe isn't expected. ``` Error: System.InvalidOperationException: There was an error generating the XML document. ---> System.InvalidOperationException: The type Giraffe was not expected. Use the XmlInclude or SoapInclude attribute to specify types that are not known statically. at Microsoft.Xml.Serialization.GeneratedAssembly.XmlSerializationWriterPaymentRequestAuthorization.Write6_Tender(String n, String ns, Tender o, Boolean isNullable, Boolean needType) at Microsoft.Xml.Serialization.GeneratedAssembly.XmlSerializationWriterPaymentRequestAuthorization.Write12_PaymentRequestAuthorization(String n, String ns, PaymentRequestAuthorization o, Boolean isNullable, Boolean needType) at Microsoft.Xml.Serialization.GeneratedAssembly.XmlSerializationWriterPaymentRequestAuthorization.Write13_PaymentRequestAuthorization(Object o) --- End of inner exception stack trace --- ``` Is there a workaround that? I cannot really add the XmlInclude...
To add methods, you should be using partial classes. Try adding a second class file with (in the right namespace etc): ``` partial class Mammal { public void ExtraMethod() {...} } ``` The `partial` keyword tells the compiler to allow the class to be split over multiple files - ideal for code-generation scenarios. It does, however, demand the `partial` keyword in every file; the members are simply combined (except for partial methods in C# 3.0 which have their own subtle behaviour). I *hope* that wsdl.exe (or whatever) includes this!
If you just want to add methods to a class you cannot change, just create extension methods. ``` public static class MammalExt { public static void ExtraMethod(this Mammal mammal) {...}} ``` Though if mammal is a proxy generated class it should be a partial class.
WebService, WebMethod and Inheritance
[ "", "c#", "web-services", "inheritance", "asmx", "" ]
Hi I have the following piece of code to upload a file to Sharepoint. It uses HTTP PUT: ``` public static string UploadFile(string destUrl, string sourcePath) { try { Uri destUri = new Uri(destUrl); FileStream inStream = File.OpenRead(sourcePath); WebRequest req = WebRequest.Create(destUri); req.Method = "PUT"; req.Headers.Add("Overwrite", "F"); req.Timeout = System.Threading.Timeout.Infinite; req.Credentials = CredentialCache.DefaultCredentials; Stream outStream = req.GetRequestStream(); string status = CopyStream(inStream, outStream); if (status == "success") { outStream.Close(); WebResponse ores = req.GetResponse(); return "success"; } else { return status; } } catch (WebException we) { return we.Message; } catch (System.Exception ee) { return ee.Message; } } ``` When I run this code I get the exception: > "The remote server returned an error: (409) Conflict." Does anyone have any ideas as to where I am going wrong? Thanks, Alex
I've had this issue when I was referencing the url of the document library and not the destination file itself. i.e. try <http://server> name/document library name/new file name.doc
No clue. But why dont you use Remote Procedure Calls (RPC) thats how i usually do it. I found this example that might get you started <http://geek.hubkey.com/2007/11/upload-file-to-sharepoint-document.html>
Uploading files to Sharepoint (WSS 3.0) document library using HTTP PUT
[ "", "c#", "sharepoint", "http", "upload", "" ]
I'm writing a program in C# that has a custom collection. The custom collection performs some useful aggregate functions (AllSuccessful, %Successful, etc) over it's members which are of type ResultInfo. I have several classes that derive from ResultInfo (UploadResultInfo, XUploadResultInfo, and YUploadResultInfo), and would like to have additional collections that inherit from ResultInfoCollection that have additional aggregate functions. The only problem with doing this as specified is that it leaves a useless ``` public void Add(ResultInfo item) { } ``` on the collection. **Clarification: This method takes an argument of type ResultInfo, but a ResultInfo added to an UploadResultInfoCollection will throw an error.** Is there an elegant way of solving my problem? I've considered generics but I don't quite know how that would work.
To define a generic class that handles any child of ResultInfo you just define it like ``` public class MyCollection<T> : ICollection<T> where T : ResultInfo { ... the required methods ... just use "T" instead of "ResultInfo" ... public void Add(T item) {} } ``` Later on you can use it by ``` MyCollection<FooResultInfo> coll = new MyCollection<FooResultInfo>(); ``` Just try using them, they are not too difficult and learning by doing is the best way ...
I'm not sure how you are left with a useless Add method. If the collection populates itself, you can make the Add method private. If you want your "inherited" additional collections to not expose the Add method, use composition instead of inheritance.
How to design a inherited collection
[ "", "c#", "oop", "inheritance", "collections", ".net-2.0", "" ]
I am just getting started with WCF and would like to set up a distributable networked system as follows: (but am not sure if it is possible.) I have a .net client that has business logic. It will need various data from various sources so I would like to add a 'server' that contains an in-memory cache but also WCF capabilities to send/receive and publish/subscribe from data sources for data that is not cached. I think it should be possible for these server applications to be identical in terms of code, but highly configurable so that requests could be dealt with in a peer to peer fashion, or traditional client-server as required. I *think* it could be done so that essentially a server sends a request to wherever it has the endpoint configured and gets a response. Essentially a server would be configured as below: ``` Server A ======== Operation 1 - Endpoint I Operation 2 - Endpoint II Server B ======== Operation 1 - Endpoint IV Operation 2 - Endpoint III ``` The configuration would be stored for each server in app.config and loaded into memory at startup. So each WCF operation would have its own WCF config (in terms of endpoints etc.) and it would send particular requests to different places according to that configuration. From what I have read of WCF I think this is possible. I don't know have enough experience to know if this is a standard WCF pattern that I am describing (if so please let me know). Otherwise, my main question is, how do I programatically configure each operation (as above) in WCF? Please let me know if I have not explained myself clearly. Thanks in advance for any help, Will
I don't know if this exactly will get you what you are looking for, but I this is what I use to add my WCF endpoints to my Windows Service. This is the code that the service runs to load all the wcf services: ``` IDictionary<string, ServiceHost> hosts; NetTcpBinding binding; CustomBinding mexBinding; private void AddService(Type serviceImp, Type serviceDef, string serviceName) { ServiceHost host = new ServiceHost(serviceImp); string address = String.Format(baseAddress, wcfPort, serviceName); string endAdd = address; string mexAdd = address + "/mex"; ServiceMetadataBehavior behavior = new ServiceMetadataBehavior(); host.Description.Behaviors.Add(behavior); host.AddServiceEndpoint(serviceDef, binding, endAdd); host.AddServiceEndpoint(typeof(IMetadataExchange), mexBinding, mexAdd); host.Open(); hosts.Add(serviceDef.Name, host); } ``` There's a `baseAddress` string that I didn't copy in, but it just has the net.tcp address for the endpoint. Likewise for the `wcfPort`. Different baseAddresses and ports are used for debug, testing and production. Just in case it isn't clear, `serviceImp` is the service implementation and `serviceDef` is the interface that defines the contract. Hope this helps. **EDIT** - Here are some references I used to help me figure all of this stuff out: [Creating WCF Service Host Programmatically](https://web.archive.org/web/20111211204643/http://geekswithblogs.net/hinshelm/archive/2007/05/30/creating-wcf-service-host-programmatically.aspx) [Net.Tcp Port Sharing Sample, Part 2](https://learn.microsoft.com/en-us/archive/blogs/drnick/) [Service Station: WCF Addressing In Depth](https://learn.microsoft.com/en-us/archive/msdn-magazine/2007/june/service-station-wcf-addressing-in-depth)
As far as I know you can't specify configuration on per operation basis. The lowest level is the interface level. The simplest (ugly) solution would be to put each operation in a separate interface.
Programatically configure individual WCF operations with different WCF configurations
[ "", "c#", ".net", "wcf", "configuration", "" ]
I'm building a query with a `GROUP BY` clause that needs the ability to count records based only on a certain condition (e.g. count only records where a certain column value is equal to 1). ``` SELECT UID, COUNT(UID) AS TotalRecords, SUM(ContractDollars) AS ContractDollars, (COUNTIF(MyColumn, 1) / COUNT(UID) * 100) -- Get the average of all records that are 1 FROM dbo.AD_CurrentView GROUP BY UID HAVING SUM(ContractDollars) >= 500000 ``` The `COUNTIF()` line obviously fails since there is no native SQL function called `COUNTIF`, but the idea here is to determine the percentage of all rows that have the value '1' for MyColumn. Any thoughts on how to properly implement this in a MS SQL 2005 environment?
You could use a `SUM` (not `COUNT`!) combined with a `CASE` statement, like this: ``` SELECT SUM(CASE WHEN myColumn=1 THEN 1 ELSE 0 END) FROM AD_CurrentView ``` Note: in my own test `NULL`s were not an issue, though this can be environment dependent. You could handle nulls such as: ``` SELECT SUM(CASE WHEN ISNULL(myColumn,0)=1 THEN 1 ELSE 0 END) FROM AD_CurrentView ```
I usually do what Josh recommended, but brainstormed and tested a slightly hokey alternative that I felt like sharing. You can take advantage of the fact that COUNT(ColumnName) doesn't count NULLs, and use something like this: ``` SELECT COUNT(NULLIF(0, myColumn)) FROM AD_CurrentView ``` NULLIF - returns NULL if the two passed in values are the same. Advantage: Expresses your intent to COUNT rows instead of having the SUM() notation. Disadvantage: Not as clear how it is working ("magic" is usually bad).
Sql Server equivalent of a COUNTIF aggregate function
[ "", "sql", "sql-server-2005", "" ]
I was intrigued by [this answer](https://stackoverflow.com/questions/542929/highlighting-unmatched-brackets-in-vim/543881#543881) to my question about [getting vim to highlight unmatched brackets](https://stackoverflow.com/questions/542929/highlighting-unmatched-brackets-in-vim) in python code. Specifically, I'm talking about the second part of his answer where he mentions that the C syntax highlighting is actually flagging as an error any instance of curly braces inside parens. It is an unobtrusive cue that you have unclosed parens when all of your downstream curly braces light up in red. That trick works because C syntax doesn't allow curly braces inside parentheses. To satisfy my (morbid?) curiosity, can I do something similar with python code? Is there anything in python syntax that isn't legal inside parentheses? Note: I'm not trolling for a better answer to my other question (there are plenty of good answers there already). I'm merely curious if this trick is even possible with python code.
Any Python statement (import, if, for, while, def, class etc.) cannot be in the parentheses: ``` In [1]: (import sys) ------------------------------------------------------------ File "<ipython console>", line 1 (import sys) ^ <type 'exceptions.SyntaxError'>: invalid syntax ```
Here's an exact answer: * <http://docs.python.org/reference/expressions.html#grammar-token-expression_list> * <http://docs.python.org/reference/compound_stmts.html#function>
Is there anything that cannot appear inside parentheses?
[ "", "python", "vim", "syntax", "syntax-highlighting", "" ]
I have a very simple piece of code (just for testing): ``` import smtplib import time server = 'smtp.myprovider.com' recipients = ['johndoe@somedomain.com'] sender = 'me@mydomain.com' message = 'Subject: [PGS]: Results\n\nBlaBlaBla' session = smtplib.SMTP(server) session.sendmail(sender,recipients,message); ``` This works but the problem is that e-mail clients don't display a sender. I want to be able to add a sender name to the e-mail. Suggestions?
`smtplib` doesn't automatically include a `From:` header, so you have to put one in yourself: ``` message = 'From: me@example.com\nSubject: [PGS]: Results\n\nBlaBlaBla' ``` (In fact, `smtplib` doesn't include *any* headers automatically, but just sends the text that you give it as a raw message)
You can utilize the [email.message.Message](http://docs.python.org/library/email.message.html#email.message.Message) class, and use it to generate mime headers, including `from:`, `to:` and `subject`. Send the `as_string()` result via SMTP. ``` >>> from email import message >>> m1=message.Message() >>> m1.add_header('from','me@no.where') >>> m1.add_header('to','myself@some.where') >>> m1.add_header('subject','test') >>> m1.set_payload('test\n') >>> m1.as_string() 'from: me@no.where\nto: myself@some.where\nsubject: test\n\ntest\n' >>> ```
Specify a sender when sending mail with Python (smtplib)
[ "", "python", "email", "" ]
Sometimes I'll be working with, say, a list of thousands of items in IDLE, and accidently print it out to the shell. When this happens, it crashes or at least very significaly slows down IDLE. As you can imagine, this is extremely inconvenient. Is there a way to make it, rather than printing the entire thing, just give me a summarised [1, 2, ...] output? Any help would be much appreciated.
As above, try a custom print function like: ``` def my_print(obj): if hasattr(obj, '__len__') and len(obj) > 100: print '... omitted object of %s with length %d ...' % (type(obj), len(obj)) else: print obj ```
Use [IPython](http://ipython.scipy.org/moin/FrontPage) as shell instead.
How can I stop IDLE from printing giant lists?
[ "", "python", "ide", "editor", "python-idle", "" ]
I have a code that creates file(s) in user-specified directory. User can point to a directory in which he can't create files, but he can rename it. I have created directory for test purposes, let's call it `C:\foo`. I have following permissions to `C:\foo`: * Traversing directory/Execute file * Removing subfolders and files * Removing * Read permissions * Change permissions * Take ownership I don't have any of the following permissions to `C:\foo`: * Full Control * File creation * Folder creation I have tried following approaches, so far: `os.access('C:\foo', os.W_OK) == True` st = os.stat('C:\foo') mode = st[stat.ST\_MODE] mode & stat.S\_IWRITE == True I believe that this is caused by the fact that I can rename folder, so it is changeable for me. But it's content - not. Does anyone know how can I write code that will check for a given directory if current user has permissions to create file in that directory? In brief - I want to check if current user has **File creation** and **Folder creation** permissions for given folder name. EDIT: The need for such code arisen from the Test case no 3 from 'Certified for Windows Vista' program, which states: > 1. The application must not allow the Least-Privileged user to save any files to Windows System directory in order to pass this test case. Should this be understood as 'Application may try to save file in Windows System directory, but shouldn't crash on failure?' or rather 'Application has to perform security checks before trying to save file?' Should I stop bothering just because Windows Vista itself won't allow the Least-Privileged user to save any files in %WINDIR%?
I recently wrote a App to pass a set of test to obtain the ISV status from Microsoft and I also add that condition. The way I understood it was that if the user is Least Priveledge then he won't have permission to write in the system folders. So I approached the problem the the way Ishmaeel described. I try to create the file and catch the exception then inform the user that he doesn't have permission to write files to that directory. In my understanding an Least-Priviledged user will not have the necessary permissions to write to those folders, if he has then he is not a Least-Priveledge user. > Should I stop bothering just because Windows Vista itself won't allow the Least-Privileged user to save any files in %WINDIR%? In my opinion? Yes.
I wouldn't waste time and LOCs on checking for permissions. Ultimate test of file creation in Windows is the creation itself. Other factors may come into play (such as existing files (or worse, folders) with the same name, disk space, background processes. These conditions can even change between the time you make the initial check and the time you actually try to create your file. So, if I had a scenario like that, I would just design my method to not lose any data in case of failure, to go ahead and try to create my file, and offer the user an option to change the selected directory and try again if creation fails.
How to check if a file can be created inside given directory on MS XP/Vista?
[ "", "python", "windows", "winapi", "windows-vista", "permissions", "" ]
I was wondering if there's an easy way in C++ to read a number of file names from a folder containing many files. They are all bitmaps if anyone is wondering. I don't know much about Windows programming so I was hoping it can be done using simple C++ methods.
Boost provides a [`basic_directory_iterator`](http://www.boost.org/doc/libs/1_38_0/libs/filesystem/doc/reference.html#Class-template-basic_directory_iterator) which provides a C++ standard conforming input iterator which accesses the contents of a directory. If you can use Boost, then this is at least cross-platform code.
C++17 includes a **standard** way of achieve that <http://en.cppreference.com/w/cpp/filesystem/directory_iterator> ``` #include <fstream> #include <iostream> #include <filesystem> namespace fs = std::filesystem; int main() { fs::create_directories("sandbox/a/b"); std::ofstream("sandbox/file1.txt"); std::ofstream("sandbox/file2.txt"); for(auto& p: fs::directory_iterator("sandbox")) std::cout << p << '\n'; fs::remove_all("sandbox"); } ``` Possible output: ``` sandbox/a sandbox/file1.txt sandbox/file2.txt ```
Read file names from a directory
[ "", "c++", "windows", "file", "file-io", "" ]
Is it possible to download all the files from a directory listing? Eg., the following link leads to a listing. <http://www.arthika.net/1234TB/new/Kuruvi/> Please point me to some related API's to download all the files from such listings (if possible). Thanks
``` wget -r -l 1 http://url.example.com/directory/ ```
Assuming you mean programmatically from Java you can look at the java.net.URL.connect method. Here is an example of using it from the [Java Tutorial](http://java.sun.com/docs/books/tutorial/networking/urls/connecting.html), along with an [example of reading from a URL](http://java.sun.com/docs/books/tutorial/networking/urls/readingWriting.html).
Download files from a directory listing
[ "", "java", "api", "download", "directory-listing", "" ]
Greetings everyone, going to need some help in clearing this exception. I get the following when debugging my compiled program in Microsoft Visual C++ 6.0: ``` Loaded 'ntdll.dll', no matching symbolic information found. Loaded 'C:\WINDOWS\system32\kernel32.dll', no matching symbolic information found. Loaded 'C:\WINDOWS\system32\tsappcmp.dll', no matching symbolic information found. Loaded 'C:\WINDOWS\system32\msvcrt.dll', no matching symbolic information found. Loaded 'C:\WINDOWS\system32\advapi32.dll', no matching symbolic information found. Loaded 'C:\WINDOWS\system32\rpcrt4.dll', no matching symbolic information found. First-chance exception in SA.exe: 0xC0000005: Access Violation. ``` Here are the relevant screenshots from the debugger. Showing ostream.h: http://img237.imageshack.us/my.php?image=accessviolation.png'>http://img237.imageshack.us/img237/1116/accessviolation.th.png' border='0'/> Showing main.ccp: http://img509.imageshack.us/my.php?image=accessviolation2.png'>http://img509.imageshack.us/img509/3619/accessviolation2.th.png' border='0'/> I've tried to scour my code for null pointers and have also tried to ignore the exception with no luck. Here are the three main components of my script: main.ccp ``` #include <iostream> #include "SA.h" using namespace std; // For the use of text generation in application int main() { SimAnneal Go; cout << "Quadratic Function" << endl << "Solving method: Simulated Annealing" << endl; cout << "\nSelect desired Initial Temperature:" << endl << "> "; cin >> Go.T_initial; cout << "\nSelect desired number of Temperature Iterations:" << endl << "> "; cin >> Go.N_max; cout << "\nSelect desired number of step Iterations:" << endl << "> "; cin >> Go.N_step; cout << "\nSelect desired Absolute Temperature:" << endl << "> "; cin >> Go.T_abs; Go.LoadCities(); Go.Initialize(); Go.SA(); system ("PAUSE"); return 0; } ``` SA.h ``` #ifndef SA_H #define SA_H class SimAnneal { double S_order [15]; double S_trial [15]; int SwapNum1; int SwapNum2; double CityArray [15][15]; double E_initial; double E_current; double T; void Metropolis (double, int, int); void Next_State (double, int); double Schedule (double, int); double ObjFunction (double CityOrder []); void EquateArray (); void OrderInt (); void OrderTrial (); void OrderList (double array[]); void WriteResults (double, double, double, double, double); public: int N_step; int N_max; double T_initial; double T_abs; void SA (); void Initialize (); void LoadCities (); }; double Random_Number_Generator(double nHigh, double nLow); #endif ``` SA.cpp ``` #include <math.h> #include <iostream> #include <fstream> #include <iterator> #include <iomanip> #include <time.h> #include <cstdlib> #include "SA.h" using namespace std; void SimAnneal::SA() { T = T_initial; E_current = E_initial; for ( int N_temperatures = 1 ; N_temperatures <= N_max ; N_temperatures++ ) { Metropolis(T, N_step, N_temperatures); T = Schedule(T, N_temperatures); if (T <= T_abs) break; } cout << "\nResults:" << endl << "Distance> " << E_current << endl << "Temperature> " << T << endl; OrderList(S_order); } void SimAnneal::Metropolis(double T_current, int N_Steps, int N_temperatures) { for ( int i=1; i <= N_step; i++ ) Next_State(T_current, N_temperatures); } void SimAnneal::Next_State (double T_current, int i) { OrderTrial(); double EXP = 2.718281828; double E_t = ObjFunction(S_trial); double E_c = ObjFunction(S_order); double deltaE = E_t - E_c; if ( deltaE <= 0 ) { EquateArray(); E_current = E_t; } else { double R = Random_Number_Generator(1,0); double Ratio = 1-(float)i/(float)N_max; double ctrl_pram = pow(EXP, (-deltaE / T_current)); if (R < ctrl_pram*Ratio) { EquateArray(); E_current = E_t; } else E_current = E_c; } } double SimAnneal::Schedule (double Temp, int i) { double CoolingRate = 0.9999; return Temp *= CoolingRate; } double SimAnneal::ObjFunction (double CityOrder []) { int a, b; double distance = 0; for (int i = 0; i < 15 - 1; i++) { a = CityOrder [i]; b = CityOrder [i + 1]; distance += CityArray [a][b]; } return distance; } void SimAnneal::Initialize () { int a, b; double distance = 0; OrderInt(); for (int i = 0; i < 15 -1; i++) { a = S_order [i]; b = S_order [i + 1]; distance += CityArray [a][b]; } E_initial = distance; } void SimAnneal::EquateArray () { for (int i = 0; i < 15; i++) { S_order [i] = S_trial [i]; } } void SimAnneal::OrderInt () { for (int i = 0; i <15; i++) { S_order [i] = i; } } void SimAnneal::OrderTrial () { for (int i = 0; i < 15; i++) { S_trial [i] = S_order [i]; } SwapNum1 = (int)Random_Number_Generator(15, 0); SwapNum2 = (int)Random_Number_Generator(15, 0); for (int n = 0; n <= 100000; n++) { SwapNum2 = (int)Random_Number_Generator(15, 0); if ( SwapNum1 != SwapNum2 ) break; } S_trial [SwapNum1] = S_order [SwapNum2]; S_trial [SwapNum2] = S_order [SwapNum1]; } void SimAnneal::OrderList (double array[]) { cout << "Array List : " << endl; for (int i = 0; i < 15; i++) { cout << " > " << array[i] << endl; } cout << "End of array" << endl; } void SimAnneal::LoadCities () { int x, y; for (y = 0; y < 15; y++) { for (x = 0; x < 15; x++) { if (x == y) { CityArray[x][y] = 0.0; } else if (x != y) { CityArray[x][y] = Random_Number_Generator(7, 1); } } } for (y = 0; y < 15; y++) { for (x = 0; x < 15; x++) { if (y > x) CityArray[y][x] = CityArray[x][y]; } } } double Random_Number_Generator(double nHigh, double nLow) { double fr = ((rand() % ((int)nHigh*1000 - (int)nLow*1000 + 1)) + nLow) / 1000; return fr; } ``` Any Assistance would be much appriciated. I'm all out of ideas myself.
The code you posted wouldn't even compile: 1) ``` cin >> Go.Write; ``` There's no such variable in the `SimAnneal` class. 2) ``` Go.SA(Go.Write) ``` Your `SA` method doesn't accept any parameters. Another thing is, why don't you run your project in debug mode directly in VC++ 6.0? The VS on the screenshots is clearly 200\*X\*. According to the screenshots, you're crashing on the line: ``` cout << "Quadratic Function" << endl << "Solving method: Simulated Annealing" << endl; ``` Which doesn't make much sense, unless your output stream is mutilated in some way. Have you tried watching the console before the crash occurs?
a = S\_order [i]; b = S\_order [i + 1]; distance += CityArray [a][b]; <--- This looks suspicious. When i = 14, b = 15...clearly outside the range... my 2 cents
Access Violation
[ "", "c++", "debugging", "memory", "" ]
I have a JS script that will be hosted on my server and that others will embed in their html, i.e. ``` ...<code for http://yoursite.example.com /> <script type="text/javascript" src="http://mysite.example.com/awesome.js" /> ...<code for http://yoursite.example.com /> ``` My script declares an object with a bunch of properties accessible for use as a Javascript `Object()`, i.e. ``` <script type="text/javascript"> //From http://mysite.example.com/awesome.js alert(Awesome.Name); </script> ``` Due to the load time variance, it seems I need to signal that the "Awesome" object in my script is ready. I need this to stand on its own, so no dependencies on specific JS frameworks. Do I need to publish my own custom JS event, or does the simple fact that my script is loaded get captured by one of the existing page-level events? How else should I be doing this? UPDATE: as a point of reference, if I include the JS in an HTML page running from `http://mysite.example.com`, the Awesome object is available and populated. When the JS file is included from another domain, the object is undefined at runtime.
The javascript content of `<script>` tags is executed procedurally, so this ``` <script type="text/javascript" src="http://mysite.com/awesome.js" /> <script type="text/javascript"> alert(Awesome.Name); </script> ``` will only alert the contents of `Awesome.Name` if found in any *previous* script tag. To understand if everything has been fully loaded on the page, you have to use the DOMContentLoaded, for firefox, and "onreadystatechange" for ie. Also you can simply check the *load* event on the **window** object if you don't care about checking the DOM (could be easier). ``` if ( document.addEventListener ) { document.addEventListener( "DOMContentLoaded", function(){ doSomething(); }, false ); } else if ( document.attachEvent ) { // IE document.attachEvent("onreadystatechange", function(){ if ( document.readyState === "complete" ) { doSomething(); } }); } ```
If your script needs the DOM to be loaded before your object is instantiated, you should look at some frameworks and see how they handle this, then implement it in your code. If you don't need the DOM to be loaded, then I would let the user worry about the timing of using your object based on when it is loaded. Generally, your object should be available to be be used as soon as your script has been loaded, which means that the object ought to be available right after the `script` tag that includes it.
Best way to signal my JS script is loaded
[ "", "javascript", "dom-events", "unobtrusive-javascript", "" ]
Apologies if this has been asked already. I've seen answers regarding static SQLs, but in this case I'd like to use PDO->prepare() for a query string that is built dynamically at runtime. Breaking down into a simple example: ``` $TempSQL = "SELECT field1, field2, field3 FROM table WHERE "; if ($numberParams == 1) { $TempSQL = $TempSQL . " field1 = '$val1' "; } else { $TempSQL = $TempSQL . " field2 = '$val2' "; $TempSQL = $TempSQL . " AND field3 = '$val3' "; } db->query($TempSQL); ``` How do I rewrite this as a db->prepare()? Should I build the statement->execute(array(':param' => $var))) on the fly as well? Is there a better / neater way?
Perhaps something like this. (untested) ``` $TempSQL = "SELECT field1, field2, field3 FROM table WHERE "; $args=array(); if ($numberParams == 1) { $TempSQL = $TempSQL . " field1 = :val1" $args[':val1']=$val1; } else { $TempSQL = $TempSQL . " field2 = :val2 and field3 = :val3"; $args[':val2']=$val2; $args[':val3']=$val3; } $stmt=$db->prepare($TempSQL); $stmt->execute($args); ```
Based on your example, a neater way would be a loop instead of switching. db->prepare() allows you to replace patterns (on php.net, the example is putting a colon in front of the field name) using bindParam() or an array on the [PDOStatement->exec()](https://www.php.net/manual/en/pdostatement.execute.php). You can use the [? from examples 3 and 4](https://www.php.net/manual/en/pdostatement.execute.php) instead of naming the field values. It still requires that all the fields be known for the SQL statement.
How do I build a parameterized PDO statement in PHP for a dynamic query?
[ "", "php", "mysql", "pdo", "sql-injection", "" ]
I am looking for an open source Java spell checking library which has dictionaries for at least the following languages: French, German, Spanish, and Czech. Any suggestion?
You should check out [Jazzy](http://jazzy.sourceforge.net/) its used in some high profile Java applications. Two problems with it: 1. It has not been updated since 2005. 2. There is only English dictionary on their SourceForge page. There are some third party dictionaries floating around. I had one for French, last time I used jazzy.
Another good library is JLanguageTool <http://www.languagetool.org/usage/> It has a pretty simple api and does both spelling and grammar checking/suggestions. ``` JLanguageTool langTool = new JLanguageTool(Language.AMERICAN_ENGLISH); langTool.activateDefaultPatternRules(); List<RuleMatch> matches = langTool.check("Hitchhiker's Guide tot he Galaxy"); for (RuleMatch match : matches) { System.out.println("Potential error at line " + match.getEndLine() + ", column " + match.getColumn() + ": " + match.getMessage()); System.out.println("Suggested correction: " + match.getSuggestedReplacements()); } ``` You can also use it to host your own spelling and grammar web service.
Looking for Java spell checker library
[ "", "java", "nlp", "spell-checking", "languagetool", "" ]
I tried to flag a collection property on a class as Obsolete to find all the occurances and keep a shrinking list of things to fix in my warning-list, due to the fact that we need to replace this collection property with something else. --- **Edit**: I've submitted this through Microsoft Connect, [issue #417159](https://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=417159). **Edit 16.11.2010**: Verified that this now works in the C# 4.0 compiler, both when compiling for .NET 3.5 and 4.0. I get 4 warnings in the posted code, including the one with the comment "Not OK?". --- However, to my surprise, the list only contained a few occurances, far fewer than I knew there were, and spotchecks tells me that for some reason, the usage of the property isn't always flagged as obsolete by the compiler in the warning list. Here's an example program, ready to compile in Visual Studio 2008. Note the four lines near the end tagged with #1-#4, of these, I'd expect all of them to report that the property used was obsolete, but #3 isn't, and it seems that if I just move on to the collection properties or methods directly, the usage of the property itself isn't flagged as obsolete. Note that #3 and #4 is referencing the same property, and #4 is flagged as using an obsolete property, whereas #3 isn't. Tests shows that if, in the expression, I access properties or methods of the collection the property returns, the compiler doesn't complain. Is this a bug, or is this a "hidden gem" of the C# compiler I wasn't aware of? ``` using System; using System.Collections.Generic; namespace TestApp { public abstract class BaseClass { [Obsolete] public abstract String Value { get; } [Obsolete] public abstract String[] ValueArray { get; } [Obsolete] public abstract List<String> ValueList { get; } } public class DerivedClass : BaseClass { [Obsolete] public override String Value { get { return "Test"; } } [Obsolete] public override String[] ValueArray { get { return new[] { "A", "B" }; } } [Obsolete] public override List<String> ValueList { get { return new List<String>(new[] { "A", "B" }); } } } public class Program { public static void Main(String[] args) { BaseClass bc = new DerivedClass(); Console.Out.WriteLine(bc.Value); // #1 - OK Console.Out.WriteLine(bc.ValueArray.Length); // #2 - OK Console.Out.WriteLine(bc.ValueList.Count); // #3 - Not OK? List<String> list = bc.ValueList; // #4 - OK } } } ```
Hmm... looks like a compiler bug to me! It fails the following (ECMA 334v4): > 24.4.3 The Obsolete attribute The attribute Obsolete is used to mark > types and members of types that should > no longer be used. If a program uses a > type or member that is decorated with > the Obsolete attribute, then the > compiler shall issue a warning or > error in order to alert the developer, > so the offending code can be fixed. > Specifically, the compiler shall issue > a warning if no error parameter is > provided, or if the error parameter is > provided and has the value false. The > compiler shall issue a compile-time > error if the error parameter is > specified and has the value true. In particular, when marked true it should issue an error, and it doesn't. Good find! You could report it on "connect", or if you don't want the pain of setting up a login, let me know and I'll happily log it (referencing your post here; no attempt to "steal" anything). (update) Reduced code to reproduce: ``` using System; using System.Collections.Generic; static class Program { static void Main() { int count = Test.Count; } [Obsolete("Should error", true)] public static List<string> Test { get {throw new NotImplementedException();} } } ``` Note that mono 2.0 gets it right, as does the MS C# 2.0 compiler. It is only the MS C# 3.0 (.NET 3.5) compiler that is broken.
This is a genuine bug. Unfortunately due to a refactoring clean up that missed this case. I fixed this for the C# 4.0 compiler release coming up in VS 2010/NDP 4.0 but there are no plans to fix it now in Orcas and unfortunately there is no work around I know of to deal with this. I hate to say it but you will need to upgrade to the NDP 4 csc.exe or VS2010 when they become available to fix this issue. I'm thinking about posting an entry on my fresh new msdn blog about this. Makes a good anecdotal example of how refactoring can break your code. Ian Halliday C# Compiler SDE Microsoft
Why are C# collection-properties not flagged as obsolete when calling properties on them?
[ "", "c#", "properties", "obsolete", "" ]
Is there a function for FILE (fopen?) that allows me to just read one int from a binary file? So far I'm trying this, but I'm getting some kind of error I can't see cause the program just crashes without telling me. ``` void opentest() { FILE *fp = fopen("dqmapt.mp", "r"); int i = 0; int j = 0; int k = 0; int * buffer; if (fp) { buffer = (int *) (sizeof(int)); i = (int) fread(buffer,1, (sizeof(int)), fp); fscanf(fp, "%d", &j); fclose(fp); } printf("%d\n", i); printf("%d\n", j); } ```
Now that you have changed your question, let me ask one. What is the format of the file you are trying to read? For a binary file there are some changes required how you open the file: ``` /* C way */ FILE *fp = fopen("text.bin", "rb"); /* note the b; this is a compound mode */ /* C++ way */ std::ifstream ifs("test.txt", ios::in | ios::binary); ``` Reading in the contents is easy. But remember, your file has 2 integers at the begining -- width, height which determine how many more to read i.e. another width \* height number of integers. So, your best bet is to read the first two integers first. You will need to use two buffers -- one for the width and height and then depending on their value another one to read the rest of the file. So, lets read in the first two integers: ``` char buf[ 2 * sizeof(int) ]; /* will store width and height */ ``` Read in the two integers: ``` /* C way */ fread(buf, sizeof(int), 2, fp); /* the syntax changes, FILE pointer is last */ /* C++ way*/ ifs.read(buf, sizeof buf); ``` Now, the tricky part. You have to convert the stuff to double. This again depends on your system endianness -- whether a simple assignment works or whether a byte swapping is necessary. As another poster has pointed out `WriteInt()` writes integers in big-endian format. Figure out what system you are on. And then you can proceed further. `FILE` is a C datastructure. It is included in C++ for C compatibility. You can do this: ``` /* The C way */ #include <stdio.h> #include <stdlib.h> int main(void) { FILE *fp = fopen("test.txt", "r"); int i = 0; if (fp) { fscanf(fp, "%d", &i); fclose(fp); } printf("%d\n", i); } ``` You can use the `std::ifstream` thing to open a file for reading. You have to read in the contents using some other incantation to read the file contents and extract the desired information out of it yourself. ``` /* The C++ way */ #include <fstream> #include <iostream> int main() { std::ifstream ifs("test.txt"); int i = 0; if (ifs.good()) { ifs >> i; } std::cout << i << std::endl; } ``` Note you can use the C style functions in C++ as well, though this is the least recommended way: ``` /* The C way in C++ */ #include <cstdio> #include <cstdlib> int main() { using namespace std; FILE *fp = fopen("test.txt", "r"); int i = 0; if (fp) { fscanf(fp, "%d", &i); fclose(fp); } printf("%d\n", i); } ``` [**Note:** Both examples assume you have a text file to read from]
Do you want to read a textual representation of an int? Then you can use fscanf, it's sort of the opposite of printf ``` int n; if( fscanf(filePointer, "%d", &n) == 1 ) // do stuff with n ``` If you want to read some binary data and treat it as an int, well that's going to depend how it was written in the first place. --- I am not a Java programmer, so this is just based on what I've read in the [docs](<http://java.sun.com/j2se/1.4.2/docs/api/java/io/DataOutputStream.html#writeInt(int))>. That said, it says > Writes an int to the underlying output stream as four bytes, high byte first. If no exception is thrown, the counter written is incremented by 4. So it's a big endian four byte integer. I don't know if it's two's complement or not, but that's probably a safe assumption (and can probably be found somewhere in the java docs/spec). Big endian is the same as network byte order, so you can use `ntohl` to convert it the endianness of your C++ platform. Beyond that, you just need to read the four bytes, which can be done with `fread`.
C++ FILE readInt function? (from a binary file)
[ "", "c++", "file", "binary", "" ]
Within the gridview I have, I'm trying to make it so when the user checks a check box for the row the row is highlighted. Now, this GridView is striped (meaning even rows have one background color and odd rows have another). This code to do it is floating around the net in various forms... ``` var color = ''; function changeColor(obj) { var rowObject = getParentRow(obj); var parentTable = document.getElementById("gvCategories"); if(color == ''){ color = getRowColor(); } if(obj.checked){ rowObject.style.backgroundColor = 'Yellow'; } else{ rowObject.style.backgroundColor = color; color = ''; } // private method function getRowColor(){ if(rowObject.style.backgroundColor == '') return parentTable.style.backgroundColor; else return rowObject.style.backgroundColor; } } // This method returns the parent row of the object function getParentRow(obj){ do{ obj = obj.parentElement; } while(obj.tagName != "TR") return obj; } ``` That's a straight copy and paste from here... <http://aspadvice.com/blogs/azamsharp/archive/2007/06/26/Highlight-GridView-Rows-Using-CheckBox.aspx> This is fine if your GridView isn't striped. However, as I mentioned earlier mine is striped. The problem here is if you uncheck a box depending on the order in which you selected items the row background color can revert to the incorrect color. I've tried thinking of some algorithm to do this but I've had little luck. My initial thought was some trickery with a stack, but I quickly realized that would require users to uncheck back in the reverse order they checked items. The only other thing I can think of is somehow checking if the row index is odd or even, and if it's odd revert to a specific color and if it's even revert to a specific color. However, I'm not sure how to check for specific indexes of a gridview from javascript. I'm ultimately going to be using jQuery for this so any advice regarding javascript with or without jquery is fine. Any ideas at all on how to achieve this? **EDIT:** So I'm still not having any luck, I thought I'd post what I currently have. ``` function highlightRow(object) { if ($(object).attr("checked") == true) { alert('is checked!'); // this will fire $(object).parent('tr').addClass("highlightedRow"); } else { alert('is not checked!'); $(object).parent('tr').removeClass("highlightedRow"); } } ``` As the comment there says, I can tell if an item is being checked or not but the class toggle just doesn't seem to be being applied. The highlighted row is declared after the classes it should be overriding in the CSS file. Does this provide any extra info as to what may be going wrong?
I finally had some time to come back to this issue and I figured it out. For some reason this bit here... ``` $(object).parent('tr') ``` wasn't grabbing the row. I honestly didn't investigate much into why since this led me to the real issue. What was happening was the already set background color styling was not being overridden by the styling being set via... ``` .addClass('highlight'); ``` So, giving the 'highlight' class background styling the important tag did the trick. ``` .SpatialDataHighlightedRow { background-color: #DDDDDD !important; } ```
I think you'd have better luck applying and removing a class that sets the background color when the checkbox is checked. That way you can simply remove the class when it is unchecked and the original CSS will be applied. Just make sure that the "highlighted" class appears after the other classes in your CSS file so that it overrides their settings. This should be easy (easier) to do with jQuery. The following assumes that the class `rowCheckbox` has been applied to all of the checkboxes, but you could select them however you want. It relies on the `highlight` class being defined to override the background color for selected rows. Your normal row coloring would also be applied via classes. ``` $(document).ready( function() { $('.rowCheckbox').click( function() { if (this.checked) { $(this).parent('tr').addClass('highlight'); } else { $(this).parent('tr').removeClass('highlight'); } }); }); ```
highlighting gridview rows for striped gridview from checkbox
[ "", "javascript", "jquery", "gridview", "checkbox", "" ]
I currently have a technical point of difference with an acquaintance. In a nutshell, it's the difference between these two basic styles of Java exception handling: Option 1 (mine): ``` try { ... } catch (OneKindOfException) { ... } catch (AnotherKind) { ... } catch (AThirdKind) { ... } ``` Option 2 (his): ``` try { ... } catch (AppException e) { switch(e.getCode()) { case Constants.ONE_KIND: ... break; case Constants.ANOTHER_KIND: ... break; case Constants.A_THIRD_KIND: ... break; default: ... } } ``` His argument -- after I used copious links about user input validation, exception handling, assertions and contracts, etc. to back up my point of view -- boiled down to this: "It’s a good model. I've used it since me and a friend of mine came up with it in 1998, almost 10 years ago. Take another look and you'll see that the compromises we made to the academic arguments make a lot of sense." Does anyone have a knock-down argument for why Option 1 is the way to go?
When you have a switch statement, you're less object oriented. There are also more opportunities for mistakes, forgetting a "`break;`" statement, forgetting to add a case for an `Exception` if you add a new `Exception` that is thrown. I also find your way of doing it to be MUCH more readable, and it's the standard idiom that all developers will immediately understand. For my taste, the amount of boiler plate to do your acquaintance's method, the amount of code that has nothing to do with actually handling the Exceptions, is unacceptable. The more boilerplate code there is around your actual program logic, the harder the code is to read and to maintain. And using an uncommon idiom makes code more difficult to understand. But the deal breaker, as I said above, is that when you modify the called method so that it throws an additional `Exception`, you will automatically know you have to modify your code because it will fail to compile. However, if you use your acquaintance's method and you modify the called method to throw a new variety of `AppException`, your code will not know there is anything different about this new variety and your code may silently fail by going down an inappropriate error-handling leg. This is assuming that you actually remembered to put in a default so at least it's handled and not silently ignored.
* the way option 2 is coded, any *unexpected* exception type will be swallowed! (this can be fixed by re-throwing in the default case, but that is arguably an ugly thing to do - much better/more efficient to not catch it in the first place) * option 2 is a manual recreation of what option 1 most likely does under the hood, i.e. it ignores the preferred syntax of the language to use older constructs best avoided for maintenance and readability reasons. In other words, option 2 is reinventing the wheel using uglier syntax than that provided by the language constructs. clearly, both ways work; option 2 is merely obsoleted by the more modern syntax supported by option 1
Java exception handling idioms ... who's right and how to handle it?
[ "", "java", "exception", "" ]
**Background** I have an abstract class, something like ``` class IConverter{ public: virtual void DoConvertion() = 0; }; ``` There will be many concrete classes which just implements *DoConvertion* method. ``` class TextConverter : public IConverter{ public: virtual void DoConvertion(){ // my code goes here } }; class ImageConverter : public IConverter{ public: virtual void DoConvertion(){ // my code goes here } }; ``` There will be many concrete implementation like this. I have created a header file say, *CharacterConverter.h* which has the abstract class *IConverter*. **Question** Since my concrete classes just implement the *DoConvertion* method, is it required to create separate header files for each concrete class? I mean is it required to create *ImageConverter.h*, *TextConverter.h* and so on for all concrete classes? All these header files is going to contain the same code like *IConverter* abstract class. Any thoughts?
Something you might consider, depending on the rest of your design, is a factory, where your abstract class has a static method (or multiple static methods, depending on how you implement it) that constructs the appropriate subclass and returns it as an IConverter\*. With this, you can expose only the abstract definition in the header file, and have all the concrete class definitions and implementations in a single .cpp file along with the super class implementation. This gets a bit unwieldy if your subclass are large, but with smaller classes it reduces the number of files you have to manage. But, as others have pointed out, it's ultimately a judgment call. The only performance issues would be related to compiling; more cpp files might take (slightly) longer to compile and more header files might increase dependency analysis. But there's no requirement that every header file have a matching cpp and vice verse. Based on the comments, I'd recommend a structure like this: IConverter.h ==> definition of IConverter Converters.h ==> definitions of all subclasses IConverter.cpp ==> include IConverter.h and Converters.h, contain implementation of IConverter abstract functionality (static factory method and any inheritable functionality) TextConvter.cpp, ImagerConverter.cpp, etc. ==> seperate cpp files for each subclass, each containing IConverter.h and Converters.h This allows you to only include the IConverter.h in any clients that use the factory and generic functionality. Putting all the other definitions in a single header allows you to consolidate if they're all basically the same. Separate cpp files allow you to take advantage of the compiler benefits mentioned by Brian. You could inline the subclass definitions in header files as mentioned, but that doesn't really buy you anything. Your compiler is usually smarter than you are when it comes to optimizations like inline.
It is not required. It's basically a judgment call. If the implementation is simple for each class you can put them all in one .h and one .cpp If the implementations are a bit longer, then it's probably cleaner to use a separate .h and .cpp file for each. Some advantages of using a different .h/.cpp for each class: * It will keep the code organized and clean * Reduced compiling work: A change in one of the implementations won't need to recompile all others * Faster compiling time: Several compilers can compile multiple files at once such as Visual Studio's /MP switch. With several files you'll have a faster compile time. * Other files can include only what they need instead of everything * Faster link time: Linking time will be reduced due to incremental linking * Using version control you can look back on only the changes to a particular derived class, instead of having to go through all changes made to the massive 1 .h/.cpp file to find that one change in a particular derived class.
Separate header files for concrete classes - C++
[ "", "c++", "abstract-class", "header-files", "" ]
What is the best way of rotating a bufferedimage about its center where the gradient is 1 degree? I know there is AffineTransform, but that causes shearing and weird stretching or black spots that should be blank. *edit* The sizes of images I am dealing with are icon sizes, so typically 24x24 up to 48x48 pixels
The quality of rotation for such a small angle will vary greatly with the size of the image. How big is your image? [After the OP edited the question to indicate the size of the image] IMO the image is too small for any meaningful rotation other than in multiples of 90 degrees (assuming its a square). I am afraid this needs to be done manually by a graphic designer to get the best possible quality. [Another alternative] Keep a high res version of the image around. Apply all your transformations to this image and then scale down to obtain an icon.
Have you tried setting the anti-aliasing of your graphics context? ``` g2d.setRenderingHint( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON ); ```
BufferedImage Rotation
[ "", "java", "image-manipulation", "" ]
I'm loading an external page into an IFRAME, which contains an advertisment that I don't want to let load. Is there a way I can set a URL/domain blacklist for any content inside an IFRAME?
I'm assuming you're developing on the server-side, some kind of Web app. What I'd reach for in this situation is something like `Perl::HTTP::Proxy`. Instead of pointing your IFRAME directly at the external site, point it to a `proxy` process (page, servlet, PHP script, doesn't matter) on your own site. This code fetches the content of the URL given to it and filters out the offending ad code before serving the modified response. I can't comment on the legality or ethics of doing this; depending on the situation, someone might not be happy that you're serving their content but not showing the ads they're getting money for.
No, if you could alter an external page then it could lead to XSS attacks. You'll have to rely on things like AdBlock Plus, etc.
Block URL using IFrame
[ "", "javascript", "html", "iframe", "" ]
I'm trying to extend all dom elements so i can get and remove their children. The function is below (works in FF and Chrome). Is there an equivalent in IE7 to extend the base dom object? ``` if (!Element.get) { Element.prototype.get = function(id) { for (var i = 0; i < this.childNodes.length; i++) { if (this.childNodes[i].id == id) { return this.childNodes[i]; } if (this.childNodes[i].childNodes.length) { var ret = this.childNodes[i].get(id); if (ret != null) { return ret; } } } return null; } } Element.prototype.removeChildren = function() { removeChildren(this); } ``` Thanks!
No. There will be some limited support [in IE8](http://msdn.microsoft.com/en-us/library/dd282900(VS.85).aspx), but 'till then you're better off finding another place to hang your functions.
Here is a simple workaround that will be sufficient in 99% of cases. It may as well be completed as required by your script : ``` if ( !window.Element ) { Element = function(){}; var __createElement = document.createElement; document.createElement = function(tagName) { var element = __createElement(tagName); if (element == null) {return null;} for(var key in Element.prototype) element[key] = Element.prototype[key]; return element; } var __getElementById = document.getElementById; document.getElementById = function(id) { var element = __getElementById(id); if (element == null) {return null;} for(var key in Element.prototype) element[key] = Element.prototype[key]; return element; } } ```
Element.prototype in IE7?
[ "", "javascript", "dom", "internet-explorer-7", "extend", "" ]
What is the best/most efficient way to store old dates (pre-1753) in SQL Server 2005? I am not concerned with storing times - just dates. SQL Server's datetime data type can only hold dates back to January 1, 1753. The MSDN documentation states that there are date and datetime2 data types, but SQL Server Management Studio does not seem to support them (Error: invalid data type). How inefficient would it be to store dates as strings or ints of the form "YYYYMMDD"? I do a lot of querying and sorting on two date fields in my table (StartDate and EndDate). UPDATE: There have been some suggestions below to store year, month, and date in separate fields. What is the benefit of storing the parts in different fields rather than in a single integer field?
The [`date`](http://msdn.microsoft.com/en-us/library/bb675168.aspx) type is definitely what you want to use. It's range is "January 1, 1 A.D. through December 31, 9999 A.D." It also just stores date information, without the time part. Are you, perhaps, using SSMS 2005, rather than 2008, or connected to a 2005 instance? That type was [introduced in SQL Server 2008](http://msdn.microsoft.com/en-us/library/bb675168.aspx). If you have the ability to use a 2008 database, I would think that it unquestionably the way to go.
I've never done this but maybe you could store the date as an integer representing number of days since whatever minimum date suits you. Then you could either create a lookup table that maps those integers to a year, month, and day, or you could write user defined functions to convert from an integer to a date or vice versa. That should be fairly efficient in terms of selecting and sorting.
Best way to store old dates in SQL Server
[ "", "sql", "sql-server", "sql-server-2005", "datetime", "date", "" ]
I'm pretty sure that a Windows service gets C:\winnt (or similar) as its working directory when installed using InstallUtil.exe. Is there any way I can access, or otherwise capture (at install time), the directory from which the service was originally installed? At the moment I'm manually entering that into the app.exe.config file, but that's horribly manual and feels like a hack. Is there a programmatic way, either at run time or install time, to determine where the service was installed from?
You can use reflection to get the location of the executing assembly. Here's a simple routine that sets the working directory to the location of the executing assembly using reflection: ``` String path = System.Reflection.Assembly.GetExecutingAssembly().Location; path = System.IO.Path.GetDirectoryName(path); Directory.SetCurrentDirectory(path); ```
Do you mean you want the directory containing the assembly? If so, that's easy: use [`Assembly.Location`](http://msdn.microsoft.com/en-us/library/system.reflection.assembly.location.aspx). I wouldn't try to *change* the working directory of the process though - I wouldn't be surprised if that had nasty side effects, if indeed you're allowed to do it.
How do I find the install directory of a Windows Service, using C#?
[ "", "c#", "windows", "windows-services", "" ]
This question is inspired by [this recent question](https://stackoverflow.com/questions/491293/why-cant-i-set-the-background-color-of-a-selecfted-listboxitem-in-wpf) and other situations I've encountered in my WPF development. How do I know whether it is enough to set a style on a control to override some default behavior vs creating a new control template? More concretely, in the question above, the author wants to change the look of a ListBoxItem when it is selected. (See code reprinted below). Everything works, except the Background property. How is one supposed to know that they should override the Control Template for this? ``` <Style TargetType="{x:Type ListBoxItem}"> <Setter Property="Content" Value="{Binding Path=Name}"/> <Setter Property="Margin" Value="2"/> <Style.Triggers> <Trigger Property="IsSelected" Value="True"> <Setter Property="FontWeight" Value="Bold"/> <Setter Property="FontSize" Value="18"/> <Setter Property="Background" Value="Yellow"/> <Setter Property="Foreground" Value="Red"/> </Trigger> </Style.Triggers> </Style> ```
Styles can be thought of very closely to CSS styles in HTML. If all you want to do is change the basic properties of a control such as Background, Foreground or whatever properties it exposes then a Style is exactly what you need. Styles also allow you to apply triggers so for animations, a style is also sufficient. If you're finding you want to change the intrinsice behaviours / inner workings on a control then a control template is what you want. For example, if you want to change how a button is laid out by adding some sort of grid behaviour, then using a control template is the way forward.
As to whether to use a style or template Ray provided a great response. As to how to solve your problem without creating a template, maybe I can help. The background color is being set by the SystemColors. Using Blend and creating a template you can see the exact xaml. So if NO TEMPLATES! is a requirement you can always change what that resource is. Example : ``` <ListBox> <ListBox.Resources> <SolidColorBrush x:Key="{x:Static SystemColors.HighlightBrushKey}" Color="Yellow" /> <Style TargetType="{x:Type ListBoxItem}"> <Setter Property="Content" Value="{Binding Path=Name}"/> <Setter Property="Margin" Value="2"/> <Style.Triggers> <Trigger Property="IsSelected" Value="True"> <Setter Property="FontWeight" Value="Bold"/> <Setter Property="FontSize" Value="18"/> <Setter Property="Foreground" Value="Red"/> </Trigger> </Style.Triggers> </Style> </ListBox.Resources> <ListBoxItem>Test 1</ListBoxItem> <ListBoxItem>Test 2</ListBoxItem> <ListBoxItem>Test 3</ListBoxItem> </ListBox> ``` That will give you the background color for that given ListBox and not screw up anything else in the app.
How do I know whether to use a style or override a control template?
[ "", "c#", "wpf", "" ]
I am not sure if this is possible in mySQL. Here are my tables:- Categories table: * id * name * parent\_id (which points to Categories.id) I use the above table to map all the categories and sub-categories. Products table: * id * name * category\_id The category\_id in the Products table points to the sub-category id in which it belongs. e.g. If I have Toys > Educational > ABC where ABC is product, Toys is Category and Educational is sub Category, then ABC will have category\_id as 2. Now the problem is that I want to use a SQL query to display all the products (in all the sub-categories and their sub-categories.. n level) for a particular category. e.g.: ``` select * from categories,products where category.name = 'Toys' and .... ``` The above query should display the products from Educational also and all other sub categories and their subcategories. Is this possible using a mySQL query? If not what options do I have? I would like to avoid PHP recursion. **Update:** Basically I want to display the top 10 products in the main category which I will be doing by adding a hits column to products table.
What I've done in previous projects where I've needed to do the same thing, I added two new columns. * i\_depth: int value of how deep the category is * nvc\_breadcrumb: complete path of the category in a breadcrumb type of format And then I added a trigger to the table that houses the category information to do the following (all three updates are in the same trigger)... ``` -- Reset all branches UPDATE t_org_branches SET nvc_breadcrumb = NULL, i_depth = NULL -- Update the root branches first UPDATE t_org_branches SET nvc_breadcrumb = '/', i_depth = 0 WHERE guid_branch_parent_id IS NULL -- Update the child branches on a loop WHILE EXISTS (SELECT * FROM t_branches WHERE i_depth IS NULL) UPDATE tobA SET tobA.i_depth = tobB.i_depth + 1, tobA.nvc_breadcrumb = tobB.nvc_breadcrumb + Ltrim(tobA.guid_branch_parent_id) + '/' FROM t_org_branches AS tobA INNER JOIN t_org_branches AS tobB ON (tobA.guid_branch_parent_id = tobB.guid_branch_id) WHERE tobB.i_depth >= 0 AND tobB.nvc_breadcrumb IS NOT NULL AND tobA.i_depth IS NULL ``` And then just do a join with your products table on the category ID and do a "LIKE '%/[CATEGORYID]/%' ". Keep in mind that this was done in MS SQL, but it should be easy enough to translate into a MySQL version. It might just be compatible enough for a cut and paste (after table and column name change). --- Expansion of explanation... t\_categories (as it stands now)... ``` Cat Parent CategoryName 1 NULL MyStore 2 1 Electronics 3 1 Clothing 4 1 Books 5 2 Televisions 6 2 Stereos 7 5 Plasma 8 5 LCD ``` t\_categories (after modification)... ``` Cat Parent CategoryName Depth Breadcrumb 1 NULL MyStore NULL NULL 2 1 Electronics NULL NULL 3 1 Clothing NULL NULL 4 1 Books NULL NULL 5 2 Televisions NULL NULL 6 2 Stereos NULL NULL 7 5 Plasma NULL NULL 8 5 LCD NULL NULL ``` t\_categories (after use of the script I gave) ``` Cat Parent CategoryName Depth Breadcrumb 1 NULL MyStore 0 / 2 1 Electronics 1 /1/ 3 1 Clothing 1 /1/ 4 1 Books 1 /1/ 5 2 Televisions 2 /1/2/ 6 2 Stereos 2 /1/2/ 7 5 LCD 3 /1/2/5/ 8 7 Samsung 4 /1/2/5/7/ ``` t\_products (as you have it now, no modifications)... ``` ID Cat Name 1 8 Samsung LNT5271F 2 7 LCD TV mount, up to 36" 3 7 LCD TV mount, up to 52" 4 5 HDMI Cable, 6ft ``` Join categories and products (where categories is C, products is P) ``` C.Cat Parent CategoryName Depth Breadcrumb ID p.Cat Name 1 NULL MyStore 0 / NULL NULL NULL 2 1 Electronics 1 /1/ NULL NULL NULL 3 1 Clothing 1 /1/ NULL NULL NULL 4 1 Books 1 /1/ NULL NULL NULL 5 2 Televisions 2 /1/2/ 4 5 HDMI Cable, 6ft 6 2 Stereos 2 /1/2/ NULL NULL NULL 7 5 LCD 3 /1/2/5/ 2 7 LCD TV mount, up to 36" 7 5 LCD 3 /1/2/5/ 3 7 LCD TV mount, up to 52" 8 7 Samsung 4 /1/2/5/7/ 1 8 Samsung LNT5271F ``` Now assuming that the products table was more complete so that there is stuff in each category and no NULLs, you could do a "Breadcrumb LIKE '%/5/%'" to get the last three items of the last table I provided. Notice that it includes the direct items and children of the category (like the Samsung tv). If you want ONLY the specific category items, just do a "c.cat = 5".
I think the cleanest way to achieve this would be to use the **nested set model**. It's a bit complicated to implement, but powerful to use. MySQL has a tutorial named [Managing Hierarchical Data in MySQL](http://mikehillyer.com/articles/managing-hierarchical-data-in-mysql/). One of the big SQL gurus Joe Celko wrote about the same thing [here](http://www.ibase.ru/devinfo/DBMSTrees/sqltrees.html). If you need even more information have a look at [Troel's links on storing hierarchical data](http://troels.arvin.dk/db/rdbms/links/#hierarchical). In my case I would stay away from using a RDBMS to store this kind of data and use a graph database instead, as the data in this case actually is a directed graph.
mySQL query for selecting children
[ "", "php", "mysql", "database", "" ]
So I have a generic list, and an `oldIndex` and a `newIndex` value. I want to move the item at `oldIndex`, to `newIndex`...as simply as possible. Any suggestions? ## Note The item should be end up between the items at `(newIndex - 1)` and `newIndex` *before* it was removed.
I know you said "generic list" but you didn't specify that you needed to use the *List(T)* class so here is a shot at something different. The *ObservableCollection(T)* class has a [Move method](http://msdn.microsoft.com/en-us/library/ms654933.aspx) that does exactly what you want. ``` public void Move(int oldIndex, int newIndex) ``` Underneath it is *basically* implemented like this. ``` T item = base[oldIndex]; base.RemoveItem(oldIndex); base.InsertItem(newIndex, item); ``` So as you can see the swap method that others have suggested is essentially what the *ObservableCollection* does in it's own Move method. **UPDATE 2015-12-30:** You can see the source code for the [Move](https://github.com/dotnet/corefx/blob/836f0480afbfc8fe7555530c6d98f70873db8ae4/src/System.ObjectModel/src/System/Collections/ObjectModel/ObservableCollection.cs#L70) and [MoveItem](https://github.com/dotnet/corefx/blob/836f0480afbfc8fe7555530c6d98f70873db8ae4/src/System.ObjectModel/src/System/Collections/ObjectModel/ObservableCollection.cs#L187) methods in corefx now for yourself without using Reflector/ILSpy since .NET is open source.
``` var item = list[oldIndex]; list.RemoveAt(oldIndex); if (newIndex > oldIndex) newIndex--; // the actual index could have shifted due to the removal list.Insert(newIndex, item); ``` Put into Extension methods they look like: ``` public static void Move<T>(this List<T> list, int oldIndex, int newIndex) { var item = list[oldIndex]; list.RemoveAt(oldIndex); if (newIndex > oldIndex) newIndex--; // the actual index could have shifted due to the removal list.Insert(newIndex, item); } public static void Move<T>(this List<T> list, T item, int newIndex) { if (item != null) { var oldIndex = list.IndexOf(item); if (oldIndex > -1) { list.RemoveAt(oldIndex); if (newIndex > oldIndex) newIndex--; // the actual index could have shifted due to the removal list.Insert(newIndex, item); } } } ```
Generic List - moving an item within the list
[ "", "c#", ".net", "generics", "list", "" ]
I would like to fetch a SSL page in Java. The problem is, that I have to authenticate against a http proxy. So I want a simple way to fetch this page. I tried the Apache Commons httpclient, but it's too much overhead for my problem. I tried this piece of code, but it does not contain an authentication action: ``` import java.io.*; import java.net.*; public class ProxyTest { public static void main(String[] args) throws ClientProtocolException, IOException { URL url = new URL("https://ssl.site"); Socket s = new Socket("proxy.address", 8080); Proxy proxy = new Proxy(Proxy.Type.HTTP, s.getLocalSocketAddress()); URLConnection connection = url.openConnection(proxy); InputStream inputStream = connection.getInputStream(); BufferedReader br = new BufferedReader(new InputStreamReader(inputStream)); String tmpLine = ""; while ((tmpLine = br.readLine()) != null) { System.out.println(tmpLine); } } } ``` Can anyone provide some information how to implement it on an easy way? Thanks in advance
org.apache.commons.httpclient.HttpClient is your friend, Sample code from <http://hc.apache.org/httpclient-3.x/sslguide.html> ``` HttpClient httpclient = new HttpClient(); httpclient.getHostConfiguration().setProxy("myproxyhost", 8080); httpclient.getState().setProxyCredentials("my-proxy-realm", " myproxyhost", new UsernamePasswordCredentials("my-proxy-username", "my-proxy-password")); GetMethod httpget = new GetMethod("https://www.verisign.com/"); try { httpclient.executeMethod(httpget); System.out.println(httpget.getStatusLine()); } finally { httpget.releaseConnection(); } ```
You need to set a [java.net.Authenticator](http://java.sun.com/j2se/1.5.0/docs/api/java/net/Authenticator.html) before you open your connection: ``` ... public static void main(String[] args) throws Exception { // Set the username and password in a manner which doesn't leave it visible. final String username = Console.readLine("[%s]", "Proxy Username"); final char[] password = Console.readPassword("[%s"], "Proxy Password:"); // Use a anonymous class for our authenticator for brevity Authenticator.setDefault(new Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(username, password); } }); URL url = new URL("https://ssl.site"); ... } ``` To remove your authenticator after you're finished, call the following code: ``` Authenticator.setDefault(null); ``` The authenticator in Java SE 6 supports `HTTP Basic`, `HTTP Digest` *and* `NTLM`. For more information, see the [Http Authentication](http://java.sun.com/javase/6/docs/technotes/guides/net/http-auth.html) documentation at sun.com
Easiest way to fetch SSL page via a proxy in Java
[ "", "java", "ssl", "proxy", "http-proxy", "" ]
Are there any problems with not prefixing private fields with an underscore in C# if the binary version is going to be consumed by other framework languages? For example since C# is case-sensitive you can call a field "foo" and the public property "Foo" and it works fine. Would this have **any** effect on a case-insensitive language such as VB.NET, will there by any CLS-compliance (or other) problems if the names are only distinguishable by casing?
It will have **no** effect. Part of the recommendations for writing CLS-compliant libraries is to NOT have two public/protected entities that differ only by case e.g you should **NOT** have ``` public void foo() {...} ``` and ``` public void Foo() {...} ``` what you're describing isn't a problem because the private item isn't available to the user of the library
**IMPORTANT UPDATE (December 12, 2022):** It really doesn't matter which notation you use. Just go with what is already used at your project or pick whatever for a new one. At the end of the day it's nitpicking and has nothing to do with how productive you are. Being flexible is your most important quality! You are a mercenary and you have to fight with any weapon you get. So do not read the rest as it's very opinionated. And being an extremist doesn't help. Peace! **IMPORTANT UPDATE (April 12, 2016):** It was brought to our attention that the internal standard of the .NET CoreFX team [insists on using the underscore-notation](https://github.com/dotnet/corefx/blob/368fdfd86ee3a3bf1bca2a6c339ee590f3d6505d/Documentation/coding-guidelines/coding-style.md) without giving any insights as to why. However if we look closely at rule #3 it becomes evident that there is a system of `_`, `t_`, `s_` prefixes that suggests why `_` was chosen in the first place. > 3. We use `_camelCase` for internal and private fields and use readonly where possible. Prefix instance fields with `_`, static fields with `s_` and thread static fields with `t_`. When used on static fields, `readonly` should come after `static` (i.e. `static readonly` not `readonly static`). > 4. We avoid `this.` unless absolutely necessary. So **if you are just like .NET CoreFX team working on some performance critical, multithreaded, system level code**, then it is STRONGLY SUGGESTED that you: * adhere to their coding standards and * use the underscore-notation and * don't read this answer any further **Otherwise please read on...** **THE ORIGINAL ANSWER:** Let's first agree on what we are talking about. The question is how we access instance members from within non-static methods and constructors of a class/sub-classes if visibility modifiers allow doing so. *Underscore-notation* * suggests that you use the "\_" prefix in the names of private fields * it also says that you should never use "this" unless it's absolutely necessary *This-notation* * suggests that you just always use "this." to access any instance member **Why does this-notation exist?** Because this is how you * tell apart a parameter from a field when they share the same name * ensure you are working in the context of the current instance Example ``` public class Demo { private String name; public Demo(String name) { this.name = name; } } ``` **Why does the underscore-notation exist?** Some people don't like typing "this", but they still need a way to distinguish a field and a parameter, so they agreed to use "\_" in front of a field Example ``` public class Demo { private String _name; public Demo(String name) { _name = name; } } ``` One may think it's just the matter of personal taste and both ways are equally good/bad. However there are certain aspects where this-notation beats the underscore-notation: **Clarity** * underscore-notation clutters names * this-notation keeps names intact **Cognitive load** * underscore-notation is inconsistent, it makes you treat fields in a special way, but you cannot use it with other members, every time you need to ask yourself whether you need a property or a field * this-notation is consistent, you don't have to think, you just always use "this" to refer to any member **Maintenance** > UPDATE: as was pointed out the following isn't an advantage point > > * underscore-notation requires you to keep an eye on `_` while refactoring, say turning a field into property (remove `_`) or the opposite (add `_`) > * this-notation doesn't have such problem **Autocompletion** When you need to see the list of instance members: * underscore-notation doesn't help you much, because when you type "\_" the autocomplete popup shows you the private fields and all types available from the linked assemblies mixed with the rest of the instance members * this-notation gives you a clear answer, by typing "this" all you see is the list of members and nothing else **Ambiguity** Sometimes you have to deal with the code without help of the Intellisense. For example when you do code reviews or browse source code online. * underscore-notation is ambiguous: When you see Something.SomethingElse you cannot tell whether Something is a class and SomethingElse is its static property... or maybe Something is a current instance property which has its own property of SomethingElse * this-notation is clear: When you see Something.SomethingElse it can only mean a class with a static property and when you see this.Something.SomethingElse you know that Something is a member and SomethingElse is its property **Extension methods** You cannot use extensions methods on the instance itself without using "this." * underscore-notation requires that you don't use "this", however with the extension methods you have to * this-notation saves you from hesitation, you always use "this", period. **Visual Studio support** * underscore-notation doesn't have a built-in support in Visual Studio * this-notation is supported by Visual Studio naturally: 1. ["This." Qualification](https://learn.microsoft.com/visualstudio/ide/editorconfig-language-conventions#this-and-me): *Prefer all non-static fields used in non-static methods to be prefaced with `this.` in C#* **Official recommendations** There a lot of official guidelines that clearly say "do not use underscores" especially in C# * **underscore-notation** came from C++ where it is a general practice which helps to avoid naming conflicts, also is recommended for VisualBasic.Net to overcome a problem where a field "value" and a property "Value" actually have the same name, because VisualBasic is case-insensitive 1. [Declared element names in Visual Basic](https://learn.microsoft.com/dotnet/visual-basic/programming-guide/language-features/declared-elements/declared-element-names) 2. [Backing fields in VisualBasic.NET](https://learn.microsoft.com/dotnet/visual-basic/programming-guide/language-features/procedures/auto-implemented-properties) * **this-notation** is recommended for C# while "\_" is explicitly prohibited: 1. [this keyword in C#](https://msdn.microsoft.com/en-us/library/dk1507sz%28v=vs.71%29.aspx) 2. [Field usage guidelines](https://learn.microsoft.com/previous-versions/dotnet/netframework-1.1/ta31s3bc(v=vs.71)): *Do not apply a prefix to field names or static field names.* 3. [Guidelines for names: Names of type members](https://learn.microsoft.com/previous-versions/dotnet/netframework-4.0/ms229012(v=vs.100)): *Do not use a prefix for field names.* 4. [General naming convention](https://learn.microsoft.com/dotnet/standard/design-guidelines/general-naming-conventions): *X DO NOT use underscores, hyphens, or any other non-alphanumeric characters* 5. [Quality assertion rule CA1707](https://learn.microsoft.com/visualstudio/code-quality/ca1707): *Identifiers should not contain underscores* 6. [Using underscores is not CLS compliant](https://learn.microsoft.com/dotnet/standard/language-independence-and-language-independent-components#naming) (for public and protected identifiers) 7. [Internal naming convention of .NET Framework developers](https://learn.microsoft.com/archive/blogs/brada/internal-coding-guidelines): *Do not use a prefix for member variables. If you want to distinguish between local and member variables you should use "this." in C# and "Me." in VB.NET.*
To underscore or to not to underscore, that is the question
[ "", "c#", "" ]
I'm building a web application that will is going to manipulate (pad, mix, merge etc) sound files and I've found that [sox](http://sox.sourceforge.net/) does exactly what I want. Sox is a linux command line program and I'm feeling a little uncomfortable with having the python web app starting new sox processes on my server on a per request basis. Example: ``` import os os.system('sox input.wav -b 24 output.aiff rate -v -L -b 90 48k') ``` This whole setup seems a little unstable to me. So my question is, what's the best practice for running command line programs from within a python (or any scripting language) web app? Message queues would be one thing to implement in order to get around the whole request response cycle. But is there other ways to make these things more elegant?
The [`subprocess`](http://docs.python.org/library/subprocess.html) module is the preferred way of running other programs from Python -- much more flexible and nicer to use than `os.system`. ``` import subprocess #subprocess.check_output(['ls', '-l']) # All that is technically needed... print(subprocess.check_output(['ls', '-l'])) ```
> This whole setup seems a little unstable to me. Talk to the [ffmpegx](http://homepage.mac.com/major4/) folks about having a [GUI](https://en.wikipedia.org/wiki/Graphical_user_interface) front-end over a command-line backend. It doesn't seem to bother them. Indeed, I submit that a [GUI](https://en.wikipedia.org/wiki/Graphical_user_interface) (or web) front-end over a command-line backend is actually more stable, since you have a very, very clean interface between [GUI](https://en.wikipedia.org/wiki/Graphical_user_interface) and command. The command can evolve at a different pace from the web, as long as the command-line options are compatible, you have no possibility of breakage.
Executing command line programs from within python
[ "", "python", "command-line", "" ]
I am installing active python, django. I don't know how to set the python path in vista environment system. First of all will it work in vista?
# Temporary Change To change the python path temporarily (i.e., for one interactive session), just append to `sys.path` like this: ``` >>> import sys >>> sys.path ['', 'C:\\Program Files\\PyScripter\\Lib\\rpyc.zip', 'C:\\Windows\\system32\\python27.zip', 'C:\\Python27\\DLLs', 'C:\\Python27\\lib', 'C:\\Python27\\lib\\plat-win', 'C:\\Python27\\lib\\lib-tk', 'C:\\Python27', 'C:\\Python27\\lib\\site-packages'] >>> sys.path.append(directory_to_be_added) ``` # Permanent (More or Less) Change Go to `Computer -> System Properties (Either by the big button near the title bar or in the context-menu by right-clicking) -> Advanced Settings (in the right-hand nav bar) -> Environment Variables`. In the `System Variables`, either add a variable called `PYTHONPATH` (if it's not already there, i.e., if you haven't done this before) or edit the existing variable. You should enter the directories normally (take care to use backslashes, not the normal ones) separated by a semicolon (`;`) w/o a space. Be careful not to end with a semicolon. The directories that you just entered now will be *added* to `sys.path` whenever you open a interpreter, they won't replace it. Also, the changes will take place only after you've restarted the interpreter. --- Source: <http://greeennotebook.com/2010/06/how-to-change-pythonpath-in-windows-and-ubuntu/>
Remember that in addition to setting `PYTHONPATH` in your system environment, you'll also want to assign `DJANGO_SETTINGS_MODULE`.
How to set Python Path on Windows Vista?
[ "", "python", "windows-vista", "" ]
What is the benefit of declaring the possible exception-throws from a C++ function? In other words, what does adding the keyword `throw()` actually do? I've read that a function declaration such as `void do_something() throw();` should guarantee that no exceptions originate from the `do_something()` function; however, this doesn't seem to hold true of functions called within `do_something()`, thus making it a weak guarantee. Please outline the usefulness (and best-use cases) of this language feature.
No one explains this better than Sutter <http://www.ddj.com/architect/184401544> The short version is 1. Never write an exception specification 2. Except possibly an empty one
The C++ standard requires that the `unexpected()` function is called if a function attempts to throw an exception that is not on its exception list. A short description of this from MSDN is here: <http://msdn.microsoft.com/en-us/library/awbt5tew(VS.80).aspx> Most compilers do not actually support this C++ feature.
What is the benefit to limiting throws allowed by a C++ function?
[ "", "c++", "function", "throw", "" ]
I am using a wx.TextCtrl to output text from a network daemon. As the output is quite verbose, the size of text in the TextCtrl can become huge (BTW is there any limitation on the size of the contents of a TextCtrl?) I would like to delete the top N lines from the TextCtrl when TextCtrl.GetNumberOfLines() exceeds a predefined treshold. What is the best way to accomplish this?
The [SetMaxLength reference](http://docs.wxwidgets.org/2.6/wx_wxtextctrl.html#wxtextctrlsetmaxlength) says that the limitation depends on the underlying native text control,but should be 32KB at least. About deleting the top N lines, you could try to call [GetLineLength](http://docs.wxwidgets.org/2.6/wx_wxtextctrl.html#wxtextctrlgetlinelength) for 0..N-1, calculate the sum S and then call [Remove](http://docs.wxwidgets.org/2.6/wx_wxtextctrl.html#wxtextctrlremove)(0,S)
How about the Remove method of wx.TextCtrl? Whenever you're about to add new text, you can check if the current text appears too long and remove some from the start.
Deleting lines from wx.TextCtrl
[ "", "python", "wxpython", "wx.textctrl", "" ]
Can I pass a property as an "out" or "ref" parameter if not then why not? e.g. ``` Person p = new Person(); ``` . . . ``` public void Test(out p.Name); ```
Apologies for the short answer, but no, the C# language specification disallows it. See this [answer](https://stackoverflow.com/questions/340528/c-automatic-properties-why-do-i-have-to-write-get-set/340682#340682) to another question to see what happens when you try. It also says why you shouldn't make the property just be a public field to get around the restriction. Hope this helps **EDIT: You ask Why?** You pass a variable to an `out` or `ref` parameter you're actually passing the address (or location in memory) of the variable. Inside the function the compiler knows where the variable really is, and gets and writes values to that address. A property looks like a value, buts it's actually a pair of functions, each with a different signature. So to pass a property, you'd actually need to pass two function pointers, one for the get, and one for the set. Thats a completely different thing to pass to a function than the address of a variable i.e. one variable address v's two function pointers. **Update** *Why doesn't C# just look after this for us?* I'm no [Eric Lippert](https://stackoverflow.com/users/88656/eric-lippert), but I'll have a go at why What should the signature of the function you're calling be? Lets say you want to call `void MyFn(ref int i)` should that remain that way, or should it change to say we also allow properties? If it changes to some syntax like `void MyFn(prop_ref int i)` then this is fairly useless, you can't pass properties to library functions or 3rd party code that wasn't written with the special prop\_ref modifier. Anyway I think you're suggesting it shouldn't be different. Now lets say `MyFn` passes `i` to a COM function, or WinAPI call, passing the address of `i` (i.e. outside .net, by ref). If it's a property, how do you get the address of `i`? There may be no actual int under the property to get the address of. Do you do what VB.Net does? The Vb.Net compiler spots when a property is passed as a ByRef argument to a method. At that point it declares a variable, copies the property to the variable, passes the variable byref and then after the method is called, copies the variable back into the property. i.e. ``` MyFunc(myObject.IntProperty) ``` becomes ``` Dim temp_i As Integer = myObject.IntProperty MyFunc(temp_i) myObject.IntProperty = temp_i ``` Any property side effects don't happen until `MyFunc` returns, which can cause all sorts of problems and lead to *very* subtle bugs. In my humble opinion the Vb.Net solution to this problem is also broken, so I'm not going to accept that as an answer. How do you think the C# compiler should handle this?
Others have explained that you can't do this in C#. In VB.NET, you *can* do this, even with option strict/explicit on: ``` Option Strict On Option Explicit On Imports System.Text Module Test Sub Main() Dim sb as new StringBuilder Foo (sb.Length) End Sub Sub Foo(ByRef x as Integer) End Sub End Module ``` The above code is equivalent to this C# code: ``` using System.Text; class Test { static void Main() { StringBuilder sb = new StringBuilder(); int tmp = sb.Length; Foo(ref tmp); sb.Length = tmp; } static void Foo(ref int x) { } } ``` Personally I'm glad that C# doesn't have this - it's muddying the waters quite a lot, particularly in terms of the value of the property if the parameter is set within the method but then an exception is thrown. EDIT: As requested, my reasoning as to why I believe passing properties in muddies the waters. If you pass a normal variable by reference, then that variable is evaluated every time it is referenced within the method. If the value changes for some reason (e.g. as a side-effect of some other work in the method) then that change will be immediately visible in the method. That's not the case if you pass a property by reference in VB.NET: the property getter is invoked once, and then the property setter is invoked once. It's not like you're passing in "here's a *property* - get and set from that whenever you use the parameter." Here's a full example where passing a field and passing an entirely trivial property in .NET have very different results: ``` Option Strict On Option Explicit On Imports System.Text Class Test Dim counter as Integer Property CounterProperty As Integer Get Return counter End Get Set (ByVal value as Integer) counter = value End Set End Property Sub Increment counter += 1 End Sub Shared Sub Main() Dim t as new Test() Console.WriteLine("Counter = {0}", t.counter) t.Foo(t.counter) Console.WriteLine("Counter = {0}", t.counter) t.CounterProperty = 0 Console.WriteLine("CounterProperty = {0}", t.CounterProperty) t.Foo(t.CounterProperty) Console.WriteLine("CounterProperty = {0}", t.CounterProperty) End Sub Sub Foo(ByRef x as Integer) x = 5 Increment Increment Increment x += 1 End Sub End Class ``` .Net-Fiddle: <https://dotnetfiddle.net/ZPFIEZ> (different results for field and property)
Is it possible to pass properties as "out" or "ref" parameters?
[ "", "c#", "arguments", "pass-by-reference", "" ]
Can you explain the concepts of, and relationship between, Covering Indexes and Covered Queries in Microsoft's SQL Server?
A covering index is one which can satisfy all requested columns in a query without performing a further lookup into the clustered index. There is no such thing as a covering query. Have a look at this Simple-Talk article: [Using Covering Indexes to Improve Query Performance](http://www.simple-talk.com/sql/learn-sql-server/using-covering-indexes-to-improve-query-performance/).
If **all the columns** requested in the `select` list of query, are **available in the index**, then the query engine doesn't have to lookup the table again which can significantly increase the performance of the query. Since all the requested columns are available with in the index, the index is covering the query. So, the query is called a covering query and the index is a covering index. A clustered index can always cover a query, if the columns in the select list are from the same table. The following links can be helpful, if you are new to index concepts: * [Excellent video on advantages and disadvantages of index and covering queries and indexes.](http://csharp-video-tutorials.blogspot.co.uk/2012/09/advantages-and-disadvantages-of-indexes.html) * [Indexes in SQL Server](http://csharp-video-tutorials.blogspot.com/2012/09/indexes-in-sql-server-part-35.html)
What are Covering Indexes and Covered Queries in SQL Server?
[ "", "sql", "sql-server", "indexing", "" ]
I am using a `Socket` to receive data via TCP, and `TextReader.ReadLine` to read lines from the connection. There is a problem where a full line has not been received -- `TextReader.ReadLine` returns an incomplete string. I want it to return `null`, indicating that a full line could not be read. How can I do this? Basically, I have this data incoming: ``` "hello\nworld\nthis is a test\n" ``` When I run `ReadLine` I get these in return: ``` "hello" "world" "this is a te" <null> <socket gets more data> "st" <null> ``` I do not want "this is a te" returned. Rather, I want "this is a test" to wait until the entire line has been received. Code: ``` var endPoint = ...; var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP); socket.Connect(endPoint); var stream = new NetworkStream(socket, true); var messageBuffer = new StringBuilder(); // Data received async callback (called several times). int bytesRead = stream.EndRead(result); string data = Encoding.UTF8.GetString(readBuffer.Take(bytesRead).ToArray()); messageBuffer.Append(data); using(var reader = new StringReader(messageBuffer.ToString())) { // This loop does not know that Message.Read reads lines. For all it knows, it could read bytes or words or the whole stream. while((Message msg = Message.Read(reader)) != null) // See below. { Console.WriteLine(msg.ToString()); // See example input/echo above. } messageBuffer = new StringBuilder(reader.ReadToEnd()); } // Method of Message. public static Message Read(TextReader reader) { string line = reader.ReadLine(); if(line == null) return null; return Message.FromRawString(line); } ``` Thanks.
I decided to write my own ReadLine parser-ish kinda thing. Here's the code: ``` // Async callback. Message message; while((message = Message.ReadBytes(messageBuffer)) != null) { OnMessageReceived(new MessageEventArgs(message)); } // Message class. public static Message ReadBytes(List<byte> data) { int end = data.FindIndex(b => b == '\n' || b == '\r'); if(end == -1) return null; string line = Encoding.UTF8.GetString(data.Take(end).ToArray()); data.RemoveRange(0, end + 1); if(line == "") return ReadBytes(data); if(line == null) return null; return Message.FromRawString(line); } ``` Many thanks to @Jon Skeet, @Noldorin, and @Richard for their very helpful suggestions. Your combined efforts led me to my final solution. =]
It sounds like the data is being sent with some extra delimiters. Assuming you're using a StreamReader over a network stream, it should behave exactly as you expect. I suggest you use Wireshark to look at the exact data your socket is receiving. I also doubt that it's returning null and then another line - are you sure you don't mean it returns an empty string and then another line? EDIT: Now you've posted the code, the reason is a lot clearer - you're decoding just a single buffer at a time. That really won't work, and could break in much more serious ways. The buffer might not even break at a *character* boundary. To be honest, it'll be a lot easier to read synchronously and use a `StreamReader`. Doing it asynchronously, you should use a `System.Text.Decoder` which can store any previous state (from the end of the previous buffer) if it needs to. You'll also have to store however much of the previous line was read - and I suspect you won't be able to use `TextReader` at all, or at least you'll have to have special handling for the case where the final character is '\r' or '\n'. Bear in mind that one buffer could end with '\r' and the next buffer start with '\n', representing a single line break between them. See how difficult it can get? Do you definitely, definitely need to handle this asynchronously? EDIT: It sounds like you could do with something which you can basically dump data into, and attach a "LineCompleted" event handler. You could make attach the event handler to start with and then just keep dumping data into it until there's no more data (at which point you'd need to tell it that the data has finished). If that sounds appropriate, I might try to work on such a class for MiscUtil - but I'd be unlikely to finish it within the next week (I'm really busy at the moment).
TextReader.ReadLine returns incomplete lines
[ "", "c#", "networking", "" ]
In our java project, We decided to use ORM object/relational mapping technique in objects' persisting. But we hesitate to use a specific framework to do this.So, what is the best framework for java can do this task?
As [Chris](https://stackoverflow.com/questions/587634/object-relational-mapping/587640#587640) says, Hibernate is an excellent choice. A (not-exhaustive) list can be found on [wikipedia](http://en.wikipedia.org/wiki/List_of_object-relational_mapping_software#Java) Hibernate is a superset of [JPA](http://en.wikipedia.org/wiki/Java_Persistence_API). If you stay within the bounds of the JPA, then you can theoretically switch to a differenct JPA implementation at a later point...
[Hibernate](http://www.hibernate.org/) is an excellent choice.
Object/Relational mapping
[ "", "java", "orm", "" ]
What would be the best way to increment a value that contains leading zeroes? For example, I'd like to increment "00000001". However, it should be noted that the number of leading zeroes will not exceed 30. So there may be cases like "0000012", "00000000000000099", or "000000000000045". I can think of a couple ways, but I want to see if someone comes up with something slick.
Use the much overlooked str.zfill(): ``` str(int(x) + 1).zfill(len(x)) ```
``` int('00000001') + 1 ``` if you want the leading zeroes back: ``` "%08g" % (int('000000001') + 1) ```
How to increment a value with leading zeroes?
[ "", "python", "" ]
I've had a bit of a search, but didn't find anything quite like what I'm trying to achieve. Basically, I'm trying to find a similarity between two users' voting habits. I have a table storing each individual vote made, which stores: ``` voteID itemID (the item the vote is attached to) userID (the user who voted) direction (whether the user voted the post up, or down) ``` I'm aiming to calculate the similarity between, say, users A and B, by finding out two things: 1. **The number of votes they have in common**. That is, the number of times they've both voted on the same post (the direction does not matter at this point). 2. **The number of times they've voted in the same direction, on common votes**. (Then simply to calculate #2 as a percentage of #1, to achieve a crude similarity rating). My question is, **how do I find the intersection between the two users' sets of votes?** (i.e. how do I calculate point #1 adequately, without looping over every vote in a highly inefficient way.) If they were in different tables, an INNER JOIN would suffice, I'd imagine... but that obviously won't work on the same table (or will it?). Any ideas would be greatly appreciated.
Something like this: ``` SELECT COUNT(*) FROM votes v1 INNER JOIN votes v2 ON (v1.item_id = v2.item_id) WHERE v1.userID = 'userA' AND v2.userUD = 'userB' ```
In case you want to do this for a single user (rather than knowing both users at the start) to find to whom they are the closest match: ``` SELECT v2.userID, COUNT(*) AS matching_items, SUM(CASE WHEN v2.direction = v1.direction THEN 1 ELSE 0 END) AS matching_votes FROM Votes v1 INNER JOIN Votes v2 ON v2.userID <> v1.userID AND v2.itemID = v1.itemID WHERE v1.userID = @userID GROUP BY v2.userID ``` You can then limit that however you see fit (return the top 10, top 20, all, etc.) I haven't tested this yet, so let me know if it doesn't act as expected.
Get Common Rows Within The Same Table
[ "", "sql", "mysql", "database", "relational", "self-join", "" ]
I am trying to create a slideshow using Javascript and an asp.net image control. I am unable to add filter property to the image control. Any suggestions ? or is it possible to set the filter in javascript? ex: I want to be able to add style="filter:revealTrans(duration=2,transition=23)" to the image in "" control. Thanks
AFAIK, filters are for IE only. The result of us use [JavaScript frameworks](https://stackoverflow.com/questions/913/what-javascript-library-would-you-choose-for-a-new-project-and-why) to achieve these effects..
Consider using JQuery UI for this task
Is there a way to add filter transitions to an Image control
[ "", "asp.net", "javascript", "" ]
I have researched on spidering and think that it is a little too complex for quite a simple app I am trying to make. Some data on a web page is not available to view in the source as it is just being displayed by the browser. If I wanted to get a value from a specific web page that I was to display in a WebBrowser control, is there any method to read values off of the contents of this browser? If not, does anyone have any suggestions on how they might approach this?
I'd have to agree with Bombe, it sounds more like you want HTML Screen Scraping. It requires lots of parsing, and if the page your scraping ever changes, your app will break, however here's a small example of how to do it: ``` WebClient webClient = new WebClient(); const string strUrl = "http://www.yahoo.com/"; byte[] reqHTML; reqHTML = webClient.DownloadData(strUrl); UTF8Encoding objUTF8 = new UTF8Encoding(); string html = objUTF8.GetString(reqHTML); ``` Now the html variable has the entire HTML in it, and you can start parsing away.
You’re not looking for [spidering](http://en.wikipedia.org/wiki/Web_crawler), you’re looking for [screen scraping](http://en.wikipedia.org/wiki/Screen_Scraping).
Creating a simple 'spider'
[ "", "c#", "web-crawler", "" ]
Is there a work around (other than changing the column type to a textfield) for SELECTing a large varchar field using PHP and mssql library? For instance a varchar(500). Does PHP really restrict the number of characters to 255? Is there a way to pull back more than that?
From the PHP page, the problem seems to be the underlying database driver on Windows platforms. Varchar can only return < 255 characters. The work around is to cast the varchar to text within the sql SELECT statement.
To cast a wide VARCHAR to TEXT in MS SQL: ``` SELECT convert(text,myWideField) FROM myTable ``` Where myWideField is the column being truncated and myTable is well... my table. The result will be cast to TEXT returning more than 256 chars. d.
Can PHP and mssql library select more than 256 characters from a varchar column?
[ "", "php", "sql-server", "" ]
I'm having a heck of a time with this one. Might be the lack of sleep... or maybe I'm just getting dumb. I have 2 tables: a) Person {Key, Name, LastName} b) LogEntry {Key, PersonKey, Log, EntryTime} I'm trying to get a join of Person and LogEntry where LogEntry is the latest LogEntry for the given Person. I hope I don't go "duh..." in five minutes when the answers hits me hard.
If you have the Relations in SQLServer you should have in the class Person something like Person.LogEntries. You can do like this: ``` LogEntry logEntry = Person.LogEntries.OrderByDescending(p => p.EntryTime).FirstOrDefault(); ``` Then you can check if logEntry is null if not I should have the last log entry for the person.
If one does not have relationships setup, the accepted answer can be done by: ``` var r = Person .GroupJoin( LogEntry, o => o.Key, i => i.PersonKey, (o,i) => new {o, Entry = i.OrderByDescending(x => x.EntryTime).First()}); ```
Linq-to-sql One-To-Many with a max
[ "", "sql", "linq", "linq-to-sql", ".net-3.5", "join", "" ]
**First, some background:** I will have to work on code for a JSP that will demand a lot of code fixing and testing. This JSP will receive a structure of given objects, and render it according to a couple of rules. What I would like to do, is to write a "Test Server" that would read some mock data out of a fixtures file, and mock those objects into a factory that would be used by the JSP in question. The target App Server is WebSphere and I would like to code, change, code in order to test appropriate HTML rendering. I have done something similar on the past, but the JSP part was just calling a method on a rendering object, so I created an Ad Hoc HTTP server that would read the fixture files, parse it and render HTML. All I had to do was run it inside RAD, change the HTML code and hit F5. **So question pretty much goes down to:** Is there any stand alone library or lightweight server (I thought of Jetty) that would take a JSP, and given the correct contexts (Request, Response, Session, etc.) render the proper HTML?
I've never used JSPs, but I *have* played around with [OOWeb](http://ooweb.sourceforge.net/tutorial.html). It's definitely lightweight, and follows the request/response model, but you'll be hard pressed to connect it with your JSPs without a lot of glue. A couple lightweight containers are listed [here](http://www.artima.com/forums/flat.jsp?forum=1&thread=34027). It looks like [Tiny Java Web Server](http://tjws.sourceforge.net/) in particular is actively being developed. Unfortunately there's not much documentation available for it.
You need more than a web server. You've got to have a servlet/JSP engine, so there's no getting around that. Jetty's quite light. Maybe Resin deserves a look, too.
What would be the light way to render a JSP page without an App/Web Server
[ "", "java", "testing", "jsp", "" ]
I'm trying to create an object in a function, but I am running into the problem that variable names have to be defined at runtime. Is there something I can do like with arrays that allows ne to dynamically create a variable in a function and preferably give it a different name from the one created when the function was called last? \*\*\*I'm working in C++ EDIT: I can't give any code because I don't have any right now. All I have right now is pseudo code. Basically, I'm trying to create a linked list, but the addNewItem() method that I want to use would require using the same method to create different objects. EDIT: Technically, we're not making a linklist, just more of a proof of concept to understand how they work. EDIT: Here's the code: ``` #include "linklist.h" #include <iostream> using namespace std; struct linklist { Student * obj; linklist * next; }; linklist * head; int main() { } void addStudent(char * newsdnt) { if(!head){ linklist * a = new linklist; a->obj = new Student(newsdnt); a->next = 0; head = a; return; }else{ linklist * a = new linklist; a->obj = new Student(newsdnt); a->next = 0; if(!head->next){ head->next = a; // Can only have one or two items in list } } ``` }
If you want a linked list - call new to create each new node and then add it to the list. Smth like this: ``` void addStudent(char * newsdnt) { linklist* a = new linklist; a.obj = new Student(newsdnt); a.next = 0; if( head == 0 ) { head = a; } else { linklist* whereToAdd = head; while( whereToAdd.next != 0 ) { whereToAdd = whereToAdd.next; } whereToAdd.next = a; } } ```
The easiest way to build a (singly) linked list is to add the new item at the front: ``` linklist *head = 0; ... a->next = head; head = a; ... ``` If it is acceptable to add items at the tail in O(N) time, then you scan the list each time to find the end. ``` linklist head; ... a->next = 0; item = &head; while (item->next != 0) item = item->next; item->next = a; ... ``` If you must add new items at the tail of the list in O(1) time, then keep a circular list, and a pointer to the tail of the list (so that `tail->next` is a pointer to the head of the list). (The previous list structures could be called 'open ended'.) ``` linklist root = { 0, &root }; linklist *tail = &root; ... a->next = tail; tail->next = a; ... ``` Beware: the termination conditions for iterating over the entire list (e.g. to find an item in the list) vary depending on the structure used (circular versus open-ended). **Caveat**: untested code! If you aren't sure what O(1) and O(N) means, then read up on 'Big O' notation.
How to create multiple objects in the same function but without overwriting each other?
[ "", "c++", "pointers", "variables", "object", "" ]
One of my sites has some very complicated sorting functions, on top of a pagination, and the various variables add up to a pretty complex URL, which is a huge pain to manage. Is there a way to manage the QUERY\_STRING efficiently? By this I mean... if the url is index.php?catid=3&sort=date&year=2009&page=2 and I wish to have the user jump to page 3, or change the sort method..... how would I preserve the remaining vars without checking for each individual var with an if/else condition and echo them out in the link that would link to page 3 or alternate sort method.
To handle actual query **strings** (string format), you can use [`parse_str()`](http://php.net/parse_str). When you want to build a query string, use [`http_build_query()`](http://php.net/http_build_query). There's quite a few examples on those documentation pages. If for some reason you can't use `http_build_query`, check out my question about the [fastest way to implode an associative array](https://stackoverflow.com/questions/408032/fastest-way-to-implode-an-associative-array-with-keys). ``` <?php $QueryString = 'catid=3&sort=date&year=2009&page=2'; // sample querystring parse_str($QueryString, $HttpQuery); print_r($HttpQuery); // will be an associative array $HttpQuery['page'] = 3; // change any values $NewQueryString = http_build_query($HttpQuery); // rebuild the querystring ```
PHP supplies you a global $\_GET which holds your query string all nicely parsed into elements ``` $_GET['catid'] will be '3' $_GET['sort'] will be 'date' $_GET['year'] will be '2009' ``` etc You could unset the ones you don't want to pass along and then move to new url via something like: ``` $get = array_intersect_key($_GET, array_keys($_GET)); unset($get['sort']); $url = 'target.php?' . http_build_query($get); ```
Whats the best way to manage QUERY_STRING in php?
[ "", "php", "optimization", "query-string", "" ]
How can I downgrade a C++ Visual Studio 2008 project to visual studio 2005? Maybe there is a converter program that someone knows of or otherwise a process that I can undertake. Thanks.
I have no idea how well it works, but here's an open source converter tool: * <http://sourceforge.net/projects/vspc> that was an extension to the tool outlined in this article: * <http://www.codeproject.com/KB/macros/vsconvert.aspx>
I always hate to edit the .sln/proj files by hand, since they can be so picky and problematic. It might be easiest to just create a new project in 2005, and just copy all the code files back into it.
How Do I Downgrade a C++ Visual Studio 2008 Project to 2005
[ "", "c++", "visual-studio", "visual-studio-2008", "visual-studio-2005", "" ]
I have noticed a few times when working on legacy code, that you can do left and right outer joins in sql by using the ``` =* ``` as kind of shorthand for "right outer join" and ``` *= ``` as kind of shorthand for "left outer join" in statements like this: ``` select table1.firstname, table2.lastname from table1, table2 where table1.id *= table2.id ``` I would guess that there are other operators like these two for the different kinds of joins, but i have not been able to find any good complete documentation about it. So do you know any good links to documentation? I personaly think that the SQL statements i have seen using these operators are more difficult to figure out than when using the spelled out syntax, so is there any benefits using the shorthand version?
The =\* and \*= are not complaint with current SQL standards, I believe these operators will be deprecated soon you should always use the standard join syntax. The other operators that you mention are confusing and need to go away, I cringe when I see these in database objects.
The reason it has unintended consequenses is because it will interpret the ENTIRE where clause as the JOIN clause. Example: Select1: ``` select * from table a left join table b on a.id=b.id where b.name = "hello world" ``` VS Select2: ``` select * from table a left join table b on a.id=b.id and b.name = "hello world" ``` These 2 selects return different results. When you write a statement like this: ``` select * from tablea,tableb where tablea.id *= tableb.id and b.name="hello world" ``` I would expect that most people would WANT the results from Select1... but you will actually get the results from Select2.
Transact-SQL shorthand join syntax?
[ "", "sql", "join", "" ]
I just stumbled (by accident) on yet another stupid not-sanitized-at-all sql injection flaw in a project I'm working on ...and I'm so tired of it. Do you have any advise on how to eliminate such bad sql statements and enforce prepared statements where ever feasible? Right now I would prefer a solution like ``` REVOKE DarnInlineDataStatements ON * TO xyz ``` But since this seems unlikely, are there e.g. static code analysis tools for finding these things (to a certain point of reliability)? Or *anything* else you would recommend? **edit**: The soft-skills approach "please don't use them, there are (usually) better ways" didn't seem to work too well in the past. Therefore I would really prefer something that prevents such queries in the first place. Not to deliberately break existing code but for future projects, some "there are no such queries" solution ;-)
If you are already using static code analysis tools, you could configure it to look for usage of certain methods, say in Java world `Connection.createStatement` instead of `Connection.prepareStatement`. I think the better approach is to educate the team on ill effects of creating dynamic SQL with concatenation. You must add it to your coding standards document!
If you move the sql to stored procedures, you can disable SELECT, CREATE, ALTER, UPDATE, DELETE, DROP, etc, permissions for the application user, leaving only EXEC access. That assumes SQL Server, but I'm sure Oracle/MySQL etc allow similar setups. Note also that this won't guarantee prepared statements: you can still call a stored procedure in an unsafe way. But if you haven't been using a lot of stored procedures it will find any place that was not coded correctly, and if you miss anything it will make it very difficult for an sql injection attack to succeed.
Ways to enforce prepared statements
[ "", "sql", "prepared-statement", "" ]
I want to set a breakpoint in unmanaged C++, in Visual Studio 2005, but I would like to ignore this breakpoint if the call stack is in a specific function. Is there a way to do this?
If you have a commercial edition of Visual Studio, you should be able to set a breakpoint early in the calling routine, then change its "When Hit..." behaviour to "Run a macro". You'll need to write a macro that programmatically disables the breakpoint in the called function -- use this as the macro to run. (Hopefully someone else can describe how such a macro can be written.) Then set other breakpoints on all exit points of the calling function, and change their behaviour to reenable the breakpoint in the called function. If you have an Express Edition, you'll find that the "Run a macro" checkbox is greyed out unfortunately. In this case, if you have access to the source code for the calling function, I suggest the following: 1. Make a global `int` variable, `bp_enabled`, initially set to 1. 2. `--bp_enabled` on the first line of `calling_function()`. 3. `++bp_enabled` at all exit points of `calling_function()`. 4. Change the "Condition..." properties of the breakpoint in the called function to break only when `bp_enabled == 1`. (Go to Debug | Windows | Breakpoints, then right-click the breakpoint.) A bit of a hack, but it gets the job done. **[EDIT: Fixed to work properly even if `calling_function()` happens to call itself recursively (either directly or indirectly)...]**
You could put breaks on all the lines that call your method in question (except in that one caller routine you don't want to stop). I can see this being difficult if the routine is called from a lot of places, or invoked in non-obvious ways. Changing the code just for debugging seems like the easiest - if possible.
Visual Studio: breakpoint excluding calls from a specific function
[ "", "c++", "visual-studio", "visual-studio-2005", "" ]
I currently have the code below, to replace a characters in a string but I now need to replace characters within the first X (in this case 3) characters and leave the rest of the string. In my example below I have 51115 but I need to replace any 5 within the first 3 characters and I should end up with 61115. My current code: ``` value = 51115; oldString = 5; newString = 6; result = Regex.Replace(value.ToString(), oldString, newString, RegexOptions.IgnoreCase); ``` result is now 61116. What would you suggest I do to query just the first x characters? Thanks
Not particularly fancy, but only give regex the data it should be replacing; only send in the range of characters that should potentially be replaced. ``` result = Regex.Replace(value.ToString().Substring(0, x), oldString, newString, RegexOptions.IgnoreCase); ```
I think the character-by-character option mentioned here is probably clearer, but if you really want a regex: ``` string result = ""; int value = 55555; string oldString = "5"; string newString = "6"; var match = new Regex(@"(\d{1,3})(\d+)?").Match(value.ToString()); if (match.Groups.Count > 1) result = match.Groups[1].Value.Replace(oldString, newString) + (match.Groups.Count > 2 ? match.Groups[2].Value : ""); ```
C# String replacement using Regex
[ "", "c#", "string", "" ]
I am using the following code to write the table. Now I wish to add subscript text after the table text. How can it be achieved? My code has: ``` oCell = document.createElement("TD"); oCell.innerHTML = data; oRow.appendChild(oCell); ``` How do I add a subscript text followed by the data?
You may mean this: ``` oCell = document.createElement("TD"); oSub = document.createElement("sub"); oSub.innerHTML = data; oCell.appendChild(oSub); oRow.appendChild(oCell); ```
You can use the following to append another element to the `td` element: ``` var newElem = document.createElement("sub"); newElem.appendChild(document.createTextNode("foobar")); oCell.appendChild(newElem); ```
Subscript text in HTML
[ "", "javascript", "html", "dom", "" ]
I have written a really small 64-bit application that crashes on clean installations of Windows Vista x64. It runs smoothly on my development machine (Windows 7 64-bit), which has Visual Studio 2008 installed. The 64-bit C++ application (unmanaged) is started by a 32-bit .NET application, and crashes immediately afterwards with an access violation error. This is what the Event Viewer says: ``` Faulting application MaxTo64.exe, version 0.0.0.0, time stamp 0x49a41d9e, faulting module USER32.dll, version 6.0.6001.18000, time stamp 0x4791adc5, exception code 0xc0000005, fault offset 0x00000000000236d6, process id 0x82c, application start time 0x01c996a346a3e805. MaxTo64.exe 0.0.0.0 49a41d9e USER32.dll 6.0.6001.18000 4791adc5 c0000005 00000000000236d6 82c 01c996a346a3e805 ``` I have installed the VC2008 redistributable (2008 x86, 2008 x64, 2008 SP1 x86 and 2008 SP1 x64), so this should not be the problem. *Edit*: It might be worth mentioning that before installing the vcredist-package, it crashed differently, with a side-by-side configuration error. I am a C++ n00b, so I really have no idea where to look next. *Edit*: Output from Debugging Tools for Windows. ``` CommandLine: "C:\Program Files (x86)\MaxTo\MaxTo64.exe" maxto_a_do_run_run Symbol search path is: *** Invalid *** **************************************************************************** * Symbol loading may be unreliable without a symbol search path. * * Use .symfix to have the debugger choose a symbol path. * * After setting your symbol path, use .reload to refresh symbol locations. * **************************************************************************** Executable search path is: ModLoad: 00000001`3f2f0000 00000001`3f30b000 MaxTo64.exe ModLoad: 00000000`77160000 00000000`772e0000 ntdll.dll ModLoad: 00000000`77030000 00000000`7715b000 C:\Windows\system32\kernel32.dll ModLoad: 00000001`80000000 00000001`80011000 C:\Program Files (x86)\MaxTo\Hooker.dll ModLoad: 00000000`76f60000 00000000`7702d000 C:\Windows\system32\USER32.dll ModLoad: 000007fe`fed70000 000007fe`fedd3000 C:\Windows\system32\GDI32.dll ModLoad: 000007fe`fea20000 000007fe`feb28000 C:\Windows\system32\ADVAPI32.dll ModLoad: 000007fe`fe850000 000007fe`fe98f000 C:\Windows\system32\RPCRT4.dll ModLoad: 000007fe`fd8b0000 000007fe`fe502000 C:\Windows\system32\SHELL32.dll ModLoad: 000007fe`fef70000 000007fe`ff00c000 C:\Windows\system32\msvcrt.dll ModLoad: 000007fe`feee0000 000007fe`fef53000 C:\Windows\system32\SHLWAPI.dll (3a4.964): Break instruction exception - code 80000003 (first chance) *** ERROR: Symbol file could not be found. Defaulted to export symbols for ntdll.dll - ntdll!DbgBreakPoint: 00000000`771a4ea0 cc int 3 0:000> g ModLoad: 000007fe`fe780000 000007fe`fe7ad000 C:\Windows\system32\IMM32.DLL ModLoad: 000007fe`ff010000 000007fe`ff111000 C:\Windows\system32\MSCTF.dll ModLoad: 000007fe`feed0000 000007fe`feedd000 C:\Windows\system32\LPK.DLL ModLoad: 000007fe`fede0000 000007fe`fee7a000 C:\Windows\system32\USP10.dll ModLoad: 000007fe`fc150000 000007fe`fc349000 C:\Windows\WinSxS\amd64_microsoft.windows.common-controls_6595b64144ccf1df_6.0.6001.18000_none_152e7382f3bd50c6\comctl32.dll (3a4.964): Access violation - code c0000005 (first chance) First chance exceptions are reported before any exception handling. This exception may be expected and handled. *** ERROR: Symbol file could not be found. Defaulted to export symbols for C:\Windows\system32\USER32.dll - USER32!DisableProcessWindowsGhosting+0x1a: 00000000`76f836d6 66f2af repne scas word ptr [rdi] *** ERROR: Module load completed but symbols could not be loaded for MaxTo64.exe *** ERROR: Symbol file could not be found. Defaulted to export symbols for C:\Windows\system32\kernel32.dll - ``` The call stack at that point is: ``` USER32!DisableProcessWindowsGhosting+0x1a USER32!ChangeWindowMessageFilter+0x12d USER32!RegisterClassExW+0x25 MaxTo64+0x11e4 MaxTo64+0x1075 MaxTo64+0x1920 kernel32!BaseThreadInitThunk+0xd ntdll!RtlUserThreadStart+0x21 ``` It seems to be in MyRegisterClass, which looks like this: ``` ATOM MyRegisterClass(HINSTANCE hInstance) { WNDCLASSEX wcex; wcex.cbSize = sizeof(WNDCLASSEX); wcex.style = CS_HREDRAW | CS_VREDRAW; wcex.lpfnWndProc = WndProc; wcex.cbClsExtra = 0; wcex.cbWndExtra = 0; wcex.hInstance = hInstance; wcex.hIcon = LoadIcon(hInstance, MAKEINTRESOURCE(IDI_MAXTO64)); wcex.hCursor = LoadCursor(NULL, IDC_ARROW); wcex.hbrBackground = (HBRUSH)(COLOR_WINDOW+1); wcex.lpszClassName = szWindowClass; wcex.hIconSm = LoadIcon(wcex.hInstance, MAKEINTRESOURCE(IDI_SMALL)); return RegisterClassEx(&wcex); } ``` *EDIT*: Turns out the problem was my own stupid fault. Apparently, there is a field in the WNDCLASSEX-structure that is not initialized properly. This crashes on Vista, but not on Windows 7, strangely enough. Adding this fixes the problem. ``` wcex.lpszMenuName = NULL; ```
Seriously there's not much we can infer from your data: I advice to do at least one of the following items * Install a VS in the Vista 64 machine * Setup a remote debug session <http://msdn.microsoft.com/en-us/library/y7f5zaaa.aspx> * Use OutputDebugString to print info where your program is and watch it with DebugView to narrow where is it crashing. ***Edit***: After watching only your debug trace I've just come out with two possible problems: * You don't ZeroMemory WNDCLASSEX, so perhaps Vista is trying to use lpszMenuName. * Win7 is beta and probably is hiding a bug. But still you are not showing much code and the trace is incomplete, so it is difficult to assert something without being [psychic](http://blogs.msdn.com/oldnewthing/archive/2005/03/21/399688.aspx). If you copy the .pdb generated by VS to the Vista machine, in the same folder where is your .exe, you will have a more meaningful trace.
Install Debugging Tools for Windows and get a real backtrace - that should lead you to what's happening
Why is my 64-bit C++ app crashing?
[ "", "c++", "visual-studio-2008", "visual-c++", "" ]
Imagine that I have a matrix of 2x2 or 3x3 pictures and I want to make one big picture using these 4 or 9 pictures. I want to show this picture on a pictureBox. I'm developing a Windows Mobile App. How can I do this? Edit: Moved comments to question for clarification.. Normally you asing an image to a pictureBox like this `pictureBox.image = myImage`. I want to build myImage using 4 images. Imagine that I have a image and cut it out in four squared pieces. I want to use these 4 images to re-assamble the original one. Thank you!
Something like this: ``` Bitmap bitmap = new Bitmap(totalWidthOfAllImages, totalHeightOfAllImages); using(Graphics g = Graphics.FromBitmap(bitmap)) { foreach(Bitmap b in myBitmaps) g.DrawImage(/* do positioning stuff based on image position */) } pictureBox1.Image = bitmap; ```
Either place 4 och 9 PictureBoxes next to each other or use a Panel instead of a PictureBox and draw all images in the Panles Paint event using Graphics.DrawImage.
C# Make one picture using various pictures
[ "", "c#", "windows-mobile", "picturebox", "" ]
How can I get a random System.Decimal? `System.Random` doesn't support it directly.
This is similar to Daniel's version, but will give the complete range. It also introduces a new extension method to get a random "any integer" value, which I think is handy. Note that the distribution of decimals here **is not uniform**. ``` /// <summary> /// Returns an Int32 with a random value across the entire range of /// possible values. /// </summary> public static int NextInt32(this Random rng) { int firstBits = rng.Next(0, 1 << 4) << 28; int lastBits = rng.Next(0, 1 << 28); return firstBits | lastBits; } public static decimal NextDecimal(this Random rng) { byte scale = (byte) rng.Next(29); bool sign = rng.Next(2) == 1; return new decimal(rng.NextInt32(), rng.NextInt32(), rng.NextInt32(), sign, scale); } ```
It is also, through the power of easy stuff, to do: ``` var rand = new Random(); var item = new decimal(rand.NextDouble()); ```
Generating a random decimal in C#
[ "", "c#", ".net", "random", "decimal", "" ]
My problem is hard to explain, so I created an example to show here. When the WPF window in the example below is shown, three buttons are displayed, each one with a different text. When anyone of these buttons is clicked, I assume its text should be displayed in the message, but instead, all of them display the same message, as if all of them were using the event handler of the last button. ``` public partial class Window1 : Window { public Window1() { InitializeComponent(); var stackPanel = new StackPanel(); this.Content = stackPanel; var n = new KeyValuePair<string, Action>[] { new KeyValuePair<string, Action>("I", () => MessageBox.Show("I")), new KeyValuePair<string, Action>("II", () => MessageBox.Show("II")), new KeyValuePair<string, Action>("III", () => MessageBox.Show("III")) }; foreach (var a in n) { Button b = new Button(); b.Content = a.Key; b.Click += (x, y) => a.Value(); stackPanel.Children.Add(b); } } } ``` Does anyone know what is wrong?
It is because of how closures are evaluated compiler in the loop: ``` foreach (var a in n) { Button b = new Button(); b.Content = a.Key; b.Click += (x, y) => a.Value(); stackPanel.Children.Add(b); } ``` The compiler assumes that you will need the context of `a` in the closure, since you are using `a.Value`, so it is creating one lambda expression that uses the value of `a`. However, `a` has scope across the entire loop, so it will simply have the last value assigned to it. To get around this, you need to copy `a` to a variable inside the loop and then use that: ``` foreach (var a in n) { Button b = new Button(); b.Content = a.Key; // Assign a to another reference. var a2 = a; // Set click handler with new reference. b.Click += (x, y) => a2.Value(); stackPanel.Children.Add(b); } ```
Unintuitive, huh? The reason is because of how lambda expressions capture variables from outside the expression. When the for loop runs for the last time, the variable `a` is set to the last element in the array `n`, and it never gets touched after that. However, the lambda expression attached to the event handler, which returns `a.Value()`, hasn't actually been evaluated yet. As a result, when it does run, it'll then get the current value of `a`, which by then is the last element. The easiest way to make this work the way you expect it to without using a bunch of extra variables and so forth would probably to change to something like this: ``` var buttons = n.Select(a => { Button freshButton = new Button { Content = a.Key }; freshButton.Click += (x, y) => a.Value(); return freshButton; }); foreach(var button in buttons) stackPanel.Children.Add(button); ```
Strange behavior when using lambda expression on WPF buttons click event
[ "", "c#", "wpf", "events", "lambda", "" ]
Is there Anyone that has experience with any open source, or relatively cheap voice recognition API for java? I'm pretty much looking for something that will turn spoken words into text. From the java speech recognition page on sun, it seems that it is something that is rather dead. My requirements is something that at the least runs on linux. Can anyone recommend something? Pure java would be a bonus, else a linux based solution could be considered. And since this is a home project... the cheaper the better. * Edit CMU Sphinx As Amit pointed out CMU Sphinx <http://cmusphinx.sourceforge.net/html/cmusphinx.php> My problem is a massive word error rate. Training seems like a project all in itself, I'm hoping to gather some strength to try it this weekend. IBM ViaVoice There are news announcements floating around for 2004 about [Via Voice being made open source](http://www.linux.com/feature/10482). It seems the news release was premature and that it never happened. VIA Voice was [released for linux](http://www.articlearchives.com/computing/software-services-applications/440754-1.html) at some point, but It seems they stopped. All that seems to be left on IBM's website is [ViaVoice embedded](http://www.ibm.com/software/speech). IBM Websphere Voice I imagine this is why ViaVoice (desktop) seems discontinued. IBM created this commercial solution which will cost allot more than an arm and a leg. And just using it will take the ones you have left, at least after my experience with websphere and their IDE. Nuance It seems they still might create products for linux. But I think they got lost and followed IBM into the server market. I'm not that sure about this one, their web-site is not that friendly in finding useful information. [Open Mind / Free Speech](http://freespeech.sourceforge.net/) These guys keep changing their project name. Probably some money hungry company keeps threatening them, but I dont know. The project looks a bit dead. I might try training Sphinx this weekend to see if it wants to be friends. Else worse case, I'll be looking at using Microsoft's speech solution. It has worked well for me in the past, but it's not a great linux solution. I could probably use it through wine, but then I'll have two separate servers... messy messy. Oh and what seems a good place to visit for voice/speech [SpeechTechMag](http://www.speechtechmag.com). They have a 'Anual Reference' that has a list of companies that somehow relates themselves to voice/speech.
Mostly Java: <http://cmusphinx.sourceforge.net/html/cmusphinx.php>
sphinx is by far the best option available if you are on a budget. however it also makes a *huge* difference what models you use, how you tune them *and* how you tune your audio source. absolutely everything has to match otherwise it just wont work. given the problem you described id be willing to bet a substantial sum that you've got you got your models mixed up and your mic is not correctly calibrated. also, if you have an accent it probably will not work - this is not an issue with the decoder but with the acoustic models - if no one with a voice/accent similar to yours was included in the training data you'll get poor results. that said, have you looked at their open source models page? <http://www.speech.cs.cmu.edu/sphinx/models/> depending on what you are trying to do you should be able to obtain about 90% accuracy on free speech with the 16kHz WSJ models and the gigaword LMs NVP. i caution however that ASR is a massive undertaking and hasn't yet reached commodity status.
Java voice recognition
[ "", "java", "linux", "speech-recognition", "" ]
I have a problem with a large database I am working with which resides on a single drive - this Database contains around a dozen tables with the two main ones are around 1GB each which cannot be made smaller. My problem is the disk queue for the database drive is around 96% to 100% even when the website that uses the DB is idle. What optimisation could be done or what is the source of the problem the DB on Disk is 16GB in total and almost all the data is required - transactions data, customer information and stock details. What are the reasons why the disk queue is always high no matter the website traffic? What can be done to help improve performance on a database this size? Any suggestions would be appreciated! The database is an MS SQL 2000 Database running on Windows Server 2003 and as stated 16GB in size (Data File on Disk size). Thanks
Well, how much memory do you have on the machine? If you can't store the pages in memory, SQL Server is going to have to go to the disk to get it's information. If your memory is low, you might want to consider upgrading it. Since the database is so big, you might want to consider adding two separate physical drives and then putting the transaction log on one drive and partitioning some of the other tables onto the other drive (you have to do some analysis to see what the best split between tables is). In doing this, you are allowing IO accesses to occur in parallel, instead of in serial, which should give you some more performance from your DB.
Before buying more disks and shifting things around, you might also update statistics and check your queries - if you are doing lots of table scans and so forth you will be creating unnecessary work for the hardware. Your database isn't that big after all - I'd first look at tuning your queries. Have you profiled what sort of queries are hitting the database?
Database Disk Queue too high, what can be done?
[ "", "sql", "performance", "sql-server-2000", "ado", "" ]
I have a property that is assigned as: ``` public string propertyA{get;set;} ``` I want to call a method automatically when this property is set to assign another property in the class. Best way to trigger the call?
You don't have to use that syntax that is just shorthand. If you expand it you can do whatever you like in the setter. ``` public string PropertyA { get { return a; } set { a = value; doStuff(); } } ```
I think you'll have to go back to doing your property the old fashioned way. ``` private string _PropertyA; public string propertyA { get { return _PropertyA; } set { _PropertyA=value; //Set other parameter } } ```
C# setting multiple properties through a single assignment
[ "", "c#", "properties", "" ]
I am adding "Tagging" functionality in my web app. My applications table structures are as following; `Tag:` ``` (TagId INT IDENTITY, TagName VARCHAR(60)) ``` `TaggedRecords:` ``` (TaggedId INT IDENTITY, TagId, TaggedRecordId) ``` Now, I want when anyone adds a tag to any record then following action should be performed using a single sql query or using a stored procedure; * The tag is already present in "Tag" table or not? * If the tag is present then it inserts a row in "TaggedRecords" table * Else if the tag is not present then first insert the tag in "Tag" table and then get the Id of newly added tag and insert a record in "TaggedRecord" table Basically, I am more interested in doing these actions using a single query or at max two sql queries. I don't wanna make multiple If-Else conditions in sql stored procedure. Thanks,
How about this... ``` CREATE PROC TagMe(@TagName VARCHAR(100),@TaggedRecordId INT) AS DECLARE @TagId INT SET @TagId = SELECT TagId FROM Tag WHERE TagName = @TagName IF @TagId IS NOT NULL BEGIN --Tag exists INSERT INTO TaggedRecords (TagId, TaggedRecordId) VALUES(@TagId,@TaggedRecordId) RETURN END ELSE -- New tag BEGIN INSERT INTO Tag (TagName) OUTPUT inserted.id INTO @TagId VALUES(@TagName) INSERT INTO TaggedRecords (TagId, TaggedRecordId) VALUES(@TagId,@TaggedRecordId) RETURN END ``` Not tested this but the theory should be sound :) For another example of the OUTPUT usage see my post at [this link](https://stackoverflow.com/questions/352673/whats-the-best-way-to-update-a-single-record-via-sql-and-obtain-the-id-of-the-rec/352737#352737) **EDIT** As per comments below this version uses EXISTS... ``` CREATE PROC TagMe(@TagName VARCHAR(100),@TaggedRecordId INT) AS DECLARE @TagId INT IF EXISTS(SELECT TagId FROM Tag WHERE TagName = @TagName) BEGIN --Tag exists SET @TagId = SELECT TagId FROM Tag WHERE TagName = @TagName INSERT INTO TaggedRecords (TagId, TaggedRecordId) VALUES(@TagId,@TaggedRecordId) RETURN END ELSE -- New tag BEGIN INSERT INTO Tag (TagName) OUTPUT inserted.id INTO @TagId VALUES(@TagName) INSERT INTO TaggedRecords (TagId, TaggedRecordId) VALUES(@TagId,@TaggedRecordId) RETURN END ``` Although I'm not sure (I reliase I'm arguing against myself here but so much of this stuff is an "it depends" answer!). This example actually would work best for more usage of new tags because it would only perform the EXISTS once and then continue whereas for an existing tag it would perform an EXISTS and then a SELECT. Hmm, take your pick - or test both approaches under volume :)
You've basically got it, but you can make it a little more efficient by changing the order. Here's some pseudo-SQL-code for your procedure: ``` SELECT TagId FROM Tag WHERE TagName = @NewTag into @TagId IF @TagId IS NULL THEN INSERT new tag, returning the new TagId into @TagId INSERT new record into TaggedRecords ``` Not sure why you're so adverse to using if clauses though... --- To get the newly generated TagId into the variable, we have two options since you're using MSSQL: * Use the [OUTPUT command](http://www.select-sql.com/mssql/output-command-in-mssql-2005.html): ``` INSERT INTO Tag (TagName) OUTPUT Inserted.TagId INTO @TagId VALUES (@NewTag); ``` * The tags are unique, so you should be able to just SELECT it back out: ``` INSERT INTO Tag (TagName) VALUES (@NewTag); SELECT TagId FROM Tag WHERE TagName = @NewTag INTO @TagId; ``` If you want to SELECT it back out, the procedure might read better if you use an IF EXISTS clause, but essentially you're doing the same work either way: ``` IF NOT EXISTS(SELECT TagId FROM Tag WHERE TagName = @NewTag) BEGIN INSERT INTO Tag (TagName) VALUES (@NewTag); SET @TagId = (SELECT TagId FROM Tag WHERE TagName = @NewTag); END ELSE BEGIN SET @TagId = (SELECT TagId FROM Tag WHERE TagName = @NewTag); END INSERT new record into TaggedRecords ```
How to write "Tagging" query in SQL?
[ "", "sql", "sql-server-2005", "t-sql", "stored-procedures", "" ]
I have a method that gets a nested array as parameter: ``` Number[][] data ``` where Number is my very simple class that inherits from INotifyPropertyChange. And then i have a statement like this: ``` double[] max = (double[])data.Select(crArray => crArray.Select( cr => cr.ValueNorm ).Max()); ``` When I'm trying to watch it in the debugger it just skips it and the whole method though no exception pops out. What is the answer? And what is the better way to do it. I can use loops, of course - but it looks so dirty and long. So LINQ is preferrable P.S. I'm using VS2008 SP1
Are you sure that the Select method returns an array? Casting + generics = code smell Try this: ``` double[] max = data .Select(crArray => crArray.Select( cr => cr.ValueNorm ).Max()) .ToArray(); ``` --- Conversion Method - (ToArray) allocates a new array and populates it. Bound by the restrictions of methods. Down Casting - Allows you to change the type of the **reference** to an object instance. Only the actual instance type, or some type that the instance type inherits from are allowed. Anything else gives a runtime exception. Explicit Conversion Operator - uses the syntax of down casting, to achieve the effect of conversion. It's really a Conversion Method. This is an endless source of confusion for people trying to understand casting. Consider this code: ``` // reference type is IEnumerable<string>, instance type is string[] IEnumerable<string> myArray = new string[3] { "abc", "def", "ghi" }; // reference type is IEnumerable<string>, instance type is ??? IEnumerable<string> myQuery = myArray .Select(s => s.Reverse().ToString()); //Cast - works string[] result = (string[]) myArray; //Cast - runtime exception: System.InvalidCastException result = (string[])myQuery; //Conversion - works result = myQuery.ToArray(); ``` Why didn't you get a runtime exception in vs? I don't know.
Usually this type of behaviour means that your source code files are not up to date. Try deleting all .bin and .pdb files from the output directory and rebuild.
LINQ Query skips without exception. Why?
[ "", "c#", ".net", "linq", "lambda", "" ]
A customer of mine is using IDEA 6 for their project and I'd like to use IDEA 8. I know that IDEA 8 gives the option of upgrading the project or keeping it in the v6 format. If I use IDEA 8 but keep it in v6 format, will this give any grief to the the IDEA 6 users?
IDEA has always upgraded my project files without problems, but I don't think that it is backwards compatible. If you want to maintain backwards compatibility, store only the IDEA 6 projects files in version control, and keep the IDEA 8 projects files only locally. Another possibility would be to not store the IDEA project files in version control at all. Use Maven or something else to manage the project dependencies. Since IDEA 7 it has been possible to import a Maven project to IDEA. (And I recommend upgrading from 6 to at least 7 just for the performance improvements that it gives, let alone other new features.)
Unless the project files change a lot, you might want to just make a copy of the v6 project files and let Idea upgrade them to v8. This would avoid any kind of change (intentional or otherwise) that would cause problems in Idea 6.
Using IntelliJ IDEA 8 for IDEA 6 Projects
[ "", "java", "intellij-idea", "" ]
After calling `System.Drawing.Icon.ToBitmap()` to create an image, is it safe to dispose the original `Icon`?
Yes. Icon.ToBitmap draws the Icon to a new Bitmap object so it is safe to dispose it afterwards. Edit: Looking at the Icon.ToBitmap() method in Reflector was interesting. I expected it to be a simple Graphics.DrawImage or Graphics.DrawIcon call but it is more involved than that. As long as it is possible the function will do a memory copy of the icon image data instead, but it will revert to a Graphics.DrawImage or Graphics.DrawIcon call if it cannot perform the copy. The memory copy is much faster so that is obviously the reason, but this makes the code much harder to read.
The method converts an `Icon` to a new `Bitmap` object, so there will be no reference from the `Bitmap` to the `Icon`. So yes, it is safe to dispose the `Icon`.
Is it safe to dispose the Icon after calling Icon.ToBitmap()?
[ "", "c#", ".net", "icons", "idisposable", "" ]
I need to be able to create a quiz type application with 20 some odd multiple choice questions. I have 3 models: `Quizzes`, `Questions`, and `Answers`. I want in the admin interface to create a quiz, and inline the quiz and answer elements. The goal is to click "Add Quiz", and be transferred to a page with 20 question fields, with 4 answer fields per each in place. Here's what I have currently: ``` class Quiz(models.Model): label = models.CharField(blank=true, max_length=50) class Question(models.Model): label = models.CharField(blank=true, max_length=50) quiz = models.ForeignKey(Quiz) class Answer(models.Model): label = models.CharField(blank=true, max_length=50) question = models.ForeignKey(Question) class QuestionInline(admin.TabularInline): model = Question extra = 20 class QuestionAdmin(admin.ModelAdmin): inlines = [QuestionInline] class AnswerInline(admin.TabularInline): model = Answer extra = 4 class AnswerAdmin(admin.ModelAdmin): inlines = [AnswerInline] class QuizAdmin(admin.ModelAdmin): inlines = [QuestionInline, AnswerInline] admin.site.register(Question, QuestionAdmin) admin.site.register(Answer, AnswerAdmin) admin.site.register(Quiz, QuizAdmin) ``` I get the following error when I try to add a quiz: ``` class 'quizzer.quiz.models.Answer'> has no ForeignKey to <class 'quizzer.quiz.models.Quiz'> ``` Is this doable, or am I trying to pull too much out of the Django Admin app?
You can't do ["nested" inlines](http://code.djangoproject.com/ticket/9025) in the Django admin (i.e. you can't have a Quiz with inline Questions, with each inline Question having inline Answers). So you'll need to lower your sights to just having inline Questions (then if you navigate to view a single Question, it could have inline Answers). So your models are fine, but your admin code should look like this: ``` class QuestionInline(admin.TabularInline): model = Question extra = 20 class AnswerInline(admin.TabularInline): model = Answer extra = 4 class QuestionAdmin(admin.ModelAdmin): inlines = [AnswerInline] class AnswerAdmin(admin.ModelAdmin): pass class QuizAdmin(admin.ModelAdmin): inlines = [QuestionInline] ``` It doesn't make sense for AnswerAdmin to have an AnswerInline, or QuestionAdmin to have a QuestionInline (unless these were models with a self-referential foreign key). And QuizAdmin can't have an AnswerInline, because Answer has no foreign key to Quiz. If Django did support nested inlines, the logical syntax would be for QuestionInline to accept an "inlines" attribute, which you'd set to [AnswerInline]. But it doesn't. Also note that "extra = 20" means you'll have 20 blank Question forms at the bottom of every Quiz, every time you load it up (even if it already has 20 actual Questions). Maybe that's what you want - makes for a long page, but makes it easy to add lots of questions at once.
Let's follow through step by step. The error: "Answer has no FK to Quiz". That's correct. The Answer model has no FK to Quiz. It has an FK to Question, but not Quiz. Why does Answer need an FK to quiz? The QuizAdmin has an AnswerInline and a QuestionInline. For an admin to have inlines, it means the inlined models (Answer and Question) must have FK's to the parent admin. Let's check. Question has an FK to Quiz. And. Answer has no FK to Quiz. So your Quiz admin demands an FK that your model lacks. That's the error.
<class> has no foreign key to <class> in Django when trying to inline models
[ "", "python", "django", "django-admin", "" ]
I have a Windows Form with a label and a picture box. To retreive an image from a web service I use a thread. The user click on a button and first the label must be displayed and then new thread is started to retrieve the image. This is the code: ``` private void menuItem1_Click(object sender, EventArgs e) { etiquetaCargando.Visible = true; this.Invoke(new System.Threading.ThreadStart(RequestImage)); } ``` The problem is this: label etiquetaCargando doesn't appear. I'm programming on Compact Framework. What it's happening? Thanks!
The question is unclear, but by using Invoke, you are defeating the purpose of having the image request on a separate thread. (You might notice that your interface becomes unresponsive while the request is happening) Instead, it is better to create a new thread object, start it, and then use the Invoke to set the image (after it has been retrieved), something along the lines of ``` private void menuItem1_Click(object sender, EventArgs e) { etiquetaCargando.Visible = true; Thread reqThread = new Thread(new ThreadStart(RequestImage)); reqThread.Start(); } private void RequestImage() { /* Get the image ... */ Invoke(SetTheImage, new object[] { theImage }); } ``` this assumes that you have a method SetTheImage which will actually do the job of displaying the image on your form.
You shouldn't be calling this: ``` this.Invoke(new System.Threading.ThreadStart(RequestImage)); ``` I assume that you are deadlocking here, as Invoke method will route the delegate to the UI thread, but you are waiting for your operation to complete. To get the code to execute on another thread, you would do this: ``` private void menuItem1_Click(object sender, EventArgs e) { etiquetaCargando.Visible = true; Thread t = new Thread(RequestImage); t.Start(); } ``` Then, in your RequestImage method, you would call the Invoke method, passing a delegate to be executed on the UI thread, in this case, passing the image you downloaded.
c# Threads and display update
[ "", "c#", "winforms", "multithreading", "" ]
My class has the following core: ``` class SmartDbConnection { private readonly IDbConnection Connection; public SmartDbConnection(string ConnectionString) { if(ConnectionString.Contains("MultipleActiveResultSets=true")) { Connection = new SqlConnection(ConnectionString); } } } ``` I don't want it to have "SqlConnection" hardcoded. So I thought in making it a Generic class (accepting IDbConnection classes). But I don't know how to do it. Anyone can help?
First - I've added `IDisposable` to this, as I believe it is important. Second, note that providers are an alternative here: ``` class SmartDbConnection { private DbConnection Connection; public SmartDbConnection(string provider, string connectionString) { Connection = DbProviderFactories.GetFactory(provider) .CreateConnection(); Connection.ConnectionString = connectionString; } public void Dispose() { if (Connection != null) { Connection.Dispose(); Connection = null; } } } ``` If you must go generic, how about: ``` class SmartDbConnection<T> : IDisposable where T : class, IDbConnection, new() { private T Connection; public SmartDbConnection(string connectionString) { T t = new T(); t.ConnectionString = connectionString; // etc } public void Dispose() { if (Connection != null) { Connection.Dispose(); Connection = null; } } } ```
Why don't you accept IDbConnection instead of connectionstring to your ctor?
How to make this class generic? (.NET C#)
[ "", "c#", ".net", "generics", "constructor", "interface", "" ]
Is it possible to create packages of related classes and have the same `protected` and `private` fields which are visible only to classes from within the same package? Basically, the same type of packages as what Java has. Is it possible?
Right now, there is no concept of package. However, PHP 5.3 is going to introduce [namespaces](http://www.php.net/manual/en/language.namespaces.faq.php). I'm not sure about how that will affect visibility between classes.
Nope. PHP has no package or friend-class support.
Packages in PHP?
[ "", "php", "oop", "" ]