Search Results

Search found 388 results on 16 pages for 'clarity'.

Page 10/16 | < Previous Page | 6 7 8 9 10 11 12 13 14 15 16  | Next Page >

  • vi and emacs: comparison? (not flamebait!)

    - by jared
    So, I've been enjoying learning and using vi for the last couple of years. The beauty of vi, for me, is that its UI is a language of movement and action with a very uniform, simple grammar, and which is terse enough that the requisite memorization pays ample dividends in how much more I enjoy working with text (by avoiding boring repetition and eliminating micro-hassles, like that half-second annoying wait while you scroll down the screen). (Note--I don't claim to have expert knowledge of vi, but I get around decently well: comfortable with limited '@' macros and regexp search-and-replace within files; frequently use multiple buffers, tabs, and windows; get around pretty well in the file browser; understand the grammar of actions + movement + subject (as described so aptly in this beautiful SO answer); and had some pretty sweet debugger and ctags integration going with PHP.) I wonder if some emacs folks could take a swing at explaining what emacs does brilliantly, or sum its strengths up in a phrase or two. Spare me the talk about productivity; I'm more interested in conceptual clarity. Lisp-centric answers are okay; I'm learning Scheme on the weekends, and would pick up emacs for that alone (have been using Racket).

    Read the article

  • Confusing Java syntax...

    - by posfan12
    I'm trying to convert the following code (from Wikipedia) from Java to JavaScript: /* * 3 June 2003, [[:en:User:Cyp]]: * Maze, generated by my algorithm * 24 October 2006, [[:en:User:quin]]: * Source edited for clarity * 25 January 2009, [[:en:User:DebateG]]: * Source edited again for clarity and reusability * 1 June 2009, [[:en:User:Nandhp]]: * Source edited to produce SVG file when run from the command-line * * This program was originally written by [[:en:User:Cyp]], who * attached it to the image description page for an image generated by * it on en.wikipedia. The image was licensed under CC-BY-SA-3.0/GFDL. */ import java.awt.*; import java.applet.*; import java.util.Random; /* Define the bit masks */ class Constants { public static final int WALL_ABOVE = 1; public static final int WALL_BELOW = 2; public static final int WALL_LEFT = 4; public static final int WALL_RIGHT = 8; public static final int QUEUED = 16; public static final int IN_MAZE = 32; } public class Maze extends java.applet.Applet { /* The width and height (in cells) of the maze */ private int width; private int height; private int maze[][]; private static final Random rnd = new Random(); /* The width in pixels of each cell */ private int cell_width; /* Construct a Maze with the default width, height, and cell_width */ public Maze() { this(20,20,10); } /* Construct a Maze with specified width, height, and cell_width */ public Maze(int width, int height, int cell_width) { this.width = width; this.height = height; this.cell_width = cell_width; } /* Initialization method that will be called when the program is * run from the command-line. Maze will be written as SVG file. */ public static void main(String[] args) { Maze m = new Maze(); m.createMaze(); m.printSVG(); } /* Initialization method that will be called when the program is * run as an applet. Maze will be displayed on-screen. */ public void init() { createMaze(); } /* The maze generation algorithm. */ private void createMaze(){ int x, y, n, d; int dx[] = { 0, 0, -1, 1 }; int dy[] = { -1, 1, 0, 0 }; int todo[] = new int[height * width], todonum = 0; /* We want to create a maze on a grid. */ maze = new int[width][height]; /* We start with a grid full of walls. */ for (x = 0; x < width; ++x) { for (y = 0; y < height; ++y) { if (x == 0 || x == width - 1 || y == 0 || y == height - 1) { maze[x][y] = Constants.IN_MAZE; } else { maze[x][y] = 63; } } } /* Select any square of the grid, to start with. */ x = 1 + rnd.nextInt (width - 2); y = 1 + rnd.nextInt (height - 2); /* Mark this square as connected to the maze. */ maze[x][y] &= ~48; /* Remember the surrounding squares, as we will */ for (d = 0; d < 4; ++d) { if ((maze[][d][][d] & Constants.QUEUED) != 0) { /* want to connect them to the maze. */ todo[todonum++] = ((x + dx[d]) << Constants.QUEUED) | (y + dy[d]); maze[][d][][d] &= ~Constants.QUEUED; } } /* We won't be finished until all is connected. */ while (todonum > 0) { /* We select one of the squares next to the maze. */ n = rnd.nextInt (todonum); x = todo[n] >> 16; /* the top 2 bytes of the data */ y = todo[n] & 65535; /* the bottom 2 bytes of the data */ /* We will connect it, so remove it from the queue. */ todo[n] = todo[--todonum]; /* Select a direction, which leads to the maze. */ do { d = rnd.nextInt (4); } while ((maze[][d][][d] & Constants.IN_MAZE) != 0); /* Connect this square to the maze. */ maze[x][y] &= ~((1 << d) | Constants.IN_MAZE); maze[][d][][d] &= ~(1 << (d ^ 1)); /* Remember the surrounding squares, which aren't */ for (d = 0; d < 4; ++d) { if ((maze[][d][][d] & Constants.QUEUED) != 0) { /* connected to the maze, and aren't yet queued to be. */ todo[todonum++] = ((x + dx[d]) << Constants.QUEUED) | (y + dy[d]); maze[][d][][d] &= ~Constants.QUEUED; } } /* Repeat until finished. */ } /* Add an entrance and exit. */ maze[1][1] &= ~Constants.WALL_ABOVE; maze[width - 2][height - 2] &= ~Constants.WALL_BELOW; } /* Called by the applet infrastructure to display the maze on-screen. */ public void paint(Graphics g) { drawMaze(g); } /* Called to write the maze to an SVG file. */ public void printSVG() { System.out.format("<svg width=\"%d\" height=\"%d\" version=\"1.1\"" + " xmlns=\"http://www.w3.org/2000/svg\">\n", width*cell_width, height*cell_width); System.out.println(" <g stroke=\"black\" stroke-width=\"1\"" + " stroke-linecap=\"round\">"); drawMaze(null); System.out.println(" </g>\n</svg>"); } /* Main maze-drawing loop. */ public void drawMaze(Graphics g) { int x, y; for (x = 1; x < width - 1; ++x) { for (y = 1; y < height - 1; ++y) { if ((maze[x][y] & Constants.WALL_ABOVE) != 0) drawLine( x * cell_width, y * cell_width, (x + 1) * cell_width, y * cell_width, g); if ((maze[x][y] & Constants.WALL_BELOW) != 0) drawLine( x * cell_width, (y + 1) * cell_width, (x + 1) * cell_width, (y + 1) * cell_width, g); if ((maze[x][y] & Constants.WALL_LEFT) != 0) drawLine( x * cell_width, y * cell_width, x * cell_width, (y + 1) * cell_width, g); if ((maze[x][y] & Constants.WALL_RIGHT) != 0) drawLine((x + 1) * cell_width, y * cell_width, (x + 1) * cell_width, (y + 1) * cell_width, g); } } } /* Draw a line, either in the SVG file or on the screen. */ public void drawLine(int x1, int y1, int x2, int y2, Graphics g) { if ( g != null ) g.drawLine(x1, y1, x2, y2); else System.out.format(" <line x1=\"%d\" y1=\"%d\"" + " x2=\"%d\" y2=\"%d\" />\n", x1, y1, x2, y2); } } Anyway, I was chugging along fairly quickly when I came to a bit that I just don't understand: /* Remember the surrounding squares, as we will */ for (var d = 0; d < 4; ++d) { if ((maze[][d][][d] & Constants.QUEUED) != 0) { /* want to connect them to the maze. */ todo[todonum++] = ((x + dx[d]) << Constants.QUEUED) | (y + dy[d]); maze[][d][][d] &= ~Constants.QUEUED; } } What I don't get is why there are four sets of brackets following the "maze" parameter instead of just two, since "maze" is a two dimensional array, not a four dimensional array. I'm sure there's a good reason for this. Problem is, I just don't get it. Thanks!

    Read the article

  • Some VS 2010 RC Updates (including patches for Intellisense and Web Designer fixes)

    - by ScottGu
    [In addition to blogging, I am also now using Twitter for quick updates and to share links. Follow me at: twitter.com/scottgu] We are continuing to make progress on shipping Visual Studio 2010.  I’d like to say a big thank you to everyone who has downloaded and tried out the VS 2010 Release Candidate, and especially to those who have sent us feedback or reported issues with it. This data has been invaluable in helping us find and fix remaining bugs before we ship the final release. Last month I blogged about a patch we released for the VS 2010 RC that fixed a bad intellisense crash issue.  This past week we released two additional patches that you can download and apply to the VS 2010 RC to immediately fix two other common issues we’ve seen people run into: Patch that fixes crashes with Tooltip invocation and when hovering over identifiers The Visual Studio team recently released a second patch that fixes some crashes we’ve seen when tooltips are displayed – most commonly when hovering over an identifier to view a QuickInfo tooltip. You can learn more about this issue from this blog post, and download and apply the patch here. Patch that fixes issues with the Web Forms designer not correctly adding controls to the auto-generated designer files The Visual Web Developer team recently released a patch that fixes issues where web controls are not correctly added to the .designer.cs file associated with the .aspx file – which means they can’t be programmed against in the code-behind file.  This issue is most commonly described as “controls are not being recognized in the code-behind” or “editing existing .aspx files regenerates the .aspx.designer.(vb or cs) file and controls are now missing” or “I can’t embed controls within the Ajax Control Toolkit TabContainer or the <asp:createuserwizard> control”. You can learn more about the issue here, and download the patch that fixes it here. Common Cause of Intellisense and IDE sluggishness on Windows XP, Vista, Win Server 2003/2008 systems Over the last few months we’ve occasionally seen reports of people seeing tremendous slowness when typing and using intellisense within VS 2010 despite running on decent machines.  It took us awhile to track down the cause – but we have found that the common culprit seems to be that these machines don’t have the latest versions of the UIA (Windows Automation) component installed. UIA 3 ships with Windows 7, and is a recommended Windows Update patch on XP and Vista (which is why we didn’t see the problem in our tests – since our machines are patched with all recommended updates).  Many systems (especially on XP) don’t automatically install recommended updates, though, and are running with older versions of UIA. This can cause significant performance slow-downs within the VS 2010 editor when large lists are displayed (for example: with intellisense). If you are running on Windows XP, Vista, or Windows Server 2003 or 2008 and are seeing any performance issues with the editor or IDE, please install the free UIA 3 update that can be downloaded from this page.  If you scroll down the page you’ll find direct links to versions for each OS. Note that we are making improvements to the final release of VS 2010 so that we don’t have big perf issues when UIA 3 isn’t installed – and we are also adding a message within the IDE that will warn you if you don’t have UIA 3 installed and accessibility is activated. Improved Text Rendering with WPF 4 and VS 2010 We recently made some nice changes to WPF 4 which improve the text clarity and text crispness over what was in the VS 2010/.NET 4 Release Candidate.  In particular these changes improve scenarios where you have a dark background with light text. You can learn more about these improvements in this WPF Team blog post.  These changes will be in the final release of VS 2010 and .NET 4. Hope this helps, Scott

    Read the article

  • ASP.NET AJAX, jQuery and AJAX Control Toolkit&ndash;the roadmap

    - by Harish Ranganathan
    The opinions mentioned herein are solely mine and do not reflect those of my employer Wanted to post this for a long time but couldn’t.  I have been an ASP.NET Developer for quite sometime and have worked with version 1.1, 2.0, 3.5 as well as the latest 4.0. With ASP.NET 2.0 and Visual Studio 2005, came the era of AJAX and rich UI style web applications.  So, ASP.NET AJAX (codenamed “ATLAS”) was released almost an year later.  This was called as ASP.NET 2.0 AJAX Extensions.  This release was supported further with Visual Studio 2005 Service Pack 1. The initial release of ASP.NET AJAX had 3 components ASP.NET AJAX Library – Client library that is used internally by the server controls as well as scripts that can be used to write hand coded ajax style pages ASP.NET AJAX Extensions – Server controls i.e. ScriptManager,Proxy, UpdatePanel, UpdateProgress and Timer server controls.  Works pretty much like other server controls in terms of development and render client side behavior automatically AJAX Control Toolkit – Set of server controls that extend a behavior or a capability.  Ex.- AutoCompleteExtender The AJAX Control Toolkit was a separate download from CodePlex while the first two get installed when you install ASP.NET AJAX Extensions. With Visual Studio 2008, ASP.NET AJAX made its way into the runtime.  So one doesn’t need to separately install the AJAX Extensions.  However, the AJAX Control Toolkit still remained as a community project that can be downloaded from CodePlex.  By then, the toolkit had close to 30 controls. So, the approach was clear viz., client side programming using ASP.NET AJAX Library and server side model using built-in controls (UpdatePanel) and/or AJAX Control Toolkit. However, with Visual Studio 2008 Service Pack 1, we also added support for the ever increasing popular jQuery library.  That is, you can use jQuery along with ASP.NET and would also get intellisense for jQuery in Visual Studio 2008. Some of you who have played with Visual Studio 2010 Beta and .NET Framework 4 Beta, would also have explored the new AJAX Library which had a lot of templates, live bindings etc.,  But, overall, the road map ahead makes it much simplified. For client side programming using JavaScript for implementing AJAX in ASP.NET, the recommendation is to use jQuery which will be shipped along with Visual Studio and provides intellisense as well. For server side programming one you can use the server controls like UpdatePanel etc., and also the AJAX Control Toolkit which has close to 40 controls now.  The AJAX Control Toolkit still remains as a separate download at CodePlex.  You can download the different versions for different versions of ASP.NET at http://ajaxcontroltoolkit.codeplex.com/ The Microsoft AJAX Library will still be available through the CDN (Content Delivery Network) channels.  You can view the CDN resources at http://www.asp.net/ajaxlibrary/CDN.ashx Similarly even jQuery and the toolkit would be available as CDN resources in case you chose not to download and have them as a part of your application. I think this makes AJAX development pretty simple.  Earlier, having Microsoft AJAX Library as well as jQuery for client side scripting was kind of confusing on which one to use.  With this roadmap, it makes it simple and clear. You can read more on this at http://ajax.asp.net I hope this post provided some clarity on the AJAX roadmap as I could decipher from various product teams. Cheers!!!

    Read the article

  • Airtel 3G in Chennai – User experience, Price & What’s the catch?

    - by Boonei
    Finally ! Here we are with Airtel 3G in India. Now Airtel customers can have a go at real 3G speed. Sources suggest that the delay in rolling out 3G was due to hardware problems. It was provided by Ericsson. Now first things first. Let me get to the point. I had subscribed to Airtel’s 3G pack Rs.100 for 100 MB. This is to check out how good it is, did not want to pay a hefty sum at the first instance. It was pretty smooth upgrading.. After the upgrade I did see the much awaited 3G signal bar on my phone. Ok! now its testing time. User experience First I did a bit of browsing, boy ! it was pretty quick, web pages loaded in a jiffy. I really did not time it because it loaded really quick. I loaded a YouTube Video, no buffering, watched the 4 min Video with no problems, it took around 6 MB of data usage Made a Skype call for about 6 min, voice clarity was really good and data usage was around 4-5 MB Tried Google Maps everything was so fast could not see the difference between computer and my phone, used it for about couple of minutes. Did listen to an Online Radio for about 5 min took about 8 MB of data usage Guess there is no need to say about Facebook or Twitter. It was good obviously. Video Call – Not yet tested Price – Do you get what you pay for ? 3G speed is fantastic, you have to really feel it to enjoy it. But currently in Airtel, 3G is available only in 3 places wiz. Bengaluru, Chennai, Coimbatore. ok ! Its not even there in all the metros? hmmm. 3G signal was not available in all parts of Chennai, often in many places it changed to 2G. Let alone all the places, even in my house when walking from one room to another sometimes its shows 2G. When it chaged from 3G to 2G there was lag in the application when it was loading data which often made me wonder if the application hanged. Currently prices not low. 2G plans in Airtel is Rs.98 for 2GB and for Rs.100 its only 100MB in 3G. Now you decide please, it’s quite a debate. The Catch – There is always a catch right ? If you have bought 3G connection and in places where 3G is not available (2G) and use any application that requires data connections (youtube, browse, chat etc) its changed with 3G!. Meaning if you have bought 100MB of 3G by paying Rs.100 like I did, suppose you used the connection for about 10MB using 2G, then it would reduce from the 100MB to 90 MB….That’s bad ! You cannot have 2G and 3G plans activated at the same point of time in your phone. You will pay 3G price for using 2G. This article titled,Airtel 3G in Chennai – User experience, Price & What’s the catch?, was originally published at Tech Dreams. Grab our rss feed or fan us on Facebook to get updates from us.

    Read the article

  • Automating XNA Performance Testing?

    - by Grofit
    I was wondering what peoples approaches or thoughts were on automating performance testing in XNA. Currently I am looking at only working in 2d, but that poses many areas where performance can be improved with different implementations. An example would be if you had 2 different implementations of spatial partitioning, one may be faster than another but without doing some actual performance testing you wouldn't be able to tell which one for sure (unless you saw the code was blatantly slow in certain parts). You could write a unit test which for a given time frame kept adding/updating/removing entities for both implementations and see how many were made in each timeframe and the higher one would be the faster one (in this given example). Another higher level example would be if you wanted to see how many entities you can have on the screen roughly without going beneath 60fps. The problem with this is to automate it you would need to use the hidden form trick or some other thing to kick off a mock game and purely test which parts you care about and disable everything else. I know that this isnt a simple affair really as even if you can automate the tests, really it is up to a human to interpret if the results are performant enough, but as part of a build step you could have it run these tests and publish the results somewhere for comparison. This way if you go from version 1.1 to 1.2 but have changed a few underlying algorithms you may notice that generally the performance score would have gone up, meaning you have improved your overall performance of the application, and then from 1.2 to 1.3 you may notice that you have then dropped overall performance a bit. So has anyone automated this sort of thing in their projects, and if so how do you measure your performance comparisons at a high level and what frameworks do you use to test? As providing you have written your code so its testable/mockable for most parts you can just use your tests as a mechanism for getting some performance results... === Edit === Just for clarity, I am more interested in the best way to make use of automated tests within XNA to track your performance, not play testing or guessing by manually running your game on a machine. This is completely different to seeing if your game is playable on X hardware, it is more about tracking the change in performance as your game engine/framework changes. As mentioned in one of the comments you could easily test "how many nodes can I insert/remove/update within QuadTreeA within 2 seconds", but you have to physically look at these results every time to see if it has changed, which may be fine and is still better than just relying on playing it to see if you notice any difference between version. However if you were to put an Assert in to notify you of a fail if it goes lower than lets say 5000 in 2 seconds you have a brittle test as it is then contextual to the hardware, not just the implementation. Although that being said these sort of automated tests are only really any use if you are running your tests as some sort of build pipeline i.e: Checkout - Run Unit Tests - Run Integration Tests - Run Performance Tests - Package So then you can easily compare the stats from one build to another on the CI server as a report of some sort, and again this may not mean much to anyone if you are not used to Continuous Integration. The main crux of this question is to see how people manage this between builds and how they find it best to report upon. As I said it can be subjective but as knowledge will be gained from the answers it seems a worthwhile question.

    Read the article

  • Inequality joins, Asynchronous transformations and Lookups : SSIS

    - by jamiet
    It is pretty much accepted by SQL Server Integration Services (SSIS) developers that synchronous transformations are generally quicker than asynchronous transformations (for a description of synchronous and asynchronous transformations go read Asynchronous and synchronous data flow components). Notice I said “generally” and not “always”; there are circumstances where using asynchronous transformations can be beneficial and in this blog post I’ll demonstrate such a scenario, one that is pretty common when building data warehouses. Imagine I have a [Customer] dimension table that manages information about all of my customers as a slowly-changing dimension. If that is a type 2 slowly changing dimension then you will likely have multiple rows per customer in that table. Furthermore you might also have datetime fields that indicate the effective time period of each member record. Here is such a table that contains data for four dimension members {Terry, Max, Henry, Horace}: Notice that we have multiple records per customer and that the [SCDStartDate] of a record is equivalent to the [SCDEndDate] of the record that preceded it (if there was one). (Note that I am on record as saying I am not a fan of this technique of storing an [SCDEndDate] but for the purposes of clarity I have included it here.) Anyway, the idea here is that we will have some incoming data containing [CustomerName] & [EffectiveDate] and we need to use those values to lookup [Customer].[CustomerId]. The logic will be: Lookup a [CustomerId] WHERE [CustomerName]=[CustomerName] AND [SCDStartDate] <= [EffectiveDate] AND [EffectiveDate] <= [SCDEndDate] The conventional approach to this would be to use a full cached lookup but that isn’t an option here because we are using inequality conditions. The obvious next step then is to use a non-cached lookup which enables us to change the SQL statement to use inequality operators: Let’s take a look at the dataflow: Notice these are all synchronous components. This approach works just fine however it does have the limitation that it has to issue a SQL statement against your lookup set for every row thus we can expect the execution time of our dataflow to increase linearly in line with the number of rows in our dataflow; that’s not good. OK, that’s the obvious method. Let’s now look at a different way of achieving this using an asynchronous Merge Join transform coupled with a Conditional Split. I’ve shown it post-execution so that I can include the row counts which help to illustrate what is going on here: Notice that there are more rows output from our Merge Join component than on the input. That is because we are joining on [CustomerName] and, as we know, we have multiple records per [CustomerName] in our lookup set. Notice also that there are two asynchronous components in here (the Sort and the Merge Join). I have embedded a video below that compares the execution times for each of these two methods. The video is just over 8minutes long. View on Vimeo  For those that can’t be bothered watching the video I’ll tell you the results here. The dataflow that used the Lookup transform took 36 seconds whereas the dataflow that used the Merge Join took less than two seconds. An illustration in case it is needed: Pretty conclusive proof that in some scenarios it may be quicker to use an asynchronous component than a synchronous one. Your mileage may of course vary. The scenario outlined here is analogous to performance tuning procedural SQL that uses cursors. It is common to eliminate cursors by converting them to set-based operations and that is effectively what we have done here. Our non-cached lookup is performing a discrete operation for every single row of data, exactly like a cursor does. By eliminating this cursor-in-disguise we have dramatically sped up our dataflow. I hope all of that proves useful. You can download the package that I demonstrated in the video from my SkyDrive at http://cid-550f681dad532637.skydrive.live.com/self.aspx/Public/BlogShare/20100514/20100514%20Lookups%20and%20Merge%20Joins.zip Comments are welcome as always. @Jamiet Share this post: email it! | bookmark it! | digg it! | reddit! | kick it! | live it!

    Read the article

  • Home Energy Management & Automation with Windows Phone 7

    A number of people at Clarity are personally interested in home energy conservation and home automation. We feel that a mobile device is a great fit for bringing this idea to fruition. While this project is merely a concept and not directly associated with Microsofts Hohm web service, it provides a great model for communicating the concept. I wanted to take the idea a step further and combine saving energy in your home with the ability to track water usage and control your home devices. I designed an application that focuses on total home control and not just energy usage. Application Overview By monitoring home consumption in real time and with yearly projections users can pinpoint vampire devices, times of high or low consumption, and wasteful patterns of energy use. Energy usage meters indicate total current consumption as well as individual device consumption. Users can then use the information to take action, make adjustments, and change their consumption behaviors. The app can be used to automate certain systems like lighting, temperature, or alarms. Other features can be turned on an off at the touch of a toggle switch on your phone, away from home. Forget to turn off the TV or shut the garage door? No problem, you can do it from your phone. Through settings you can enable and disable features of the phone that apply to your home making it a completely customized and convenient experience. To be clear, this equates to more security, big environmental impact, and even bigger savings.   Design and User Interface  Since this panorama application is designed for win phone 7 devices, it complies with the UI Design and Interaction Guide for wp7. I developed the frame and page hierarchy from existing examples. The interface takes advantage of the interactive nature of touch screens with slider controls, pivot control views, and toggle switches to turn on and off devices (not shown in mockup). I followed recommendations for text based elements and adapted the tile notifications to display the most recent user activity. For example, the mockup indicates upon launching the app that the last thing you did was program the thermostat. This model is great for quick launching common user actions. One last design feature to point out is the technical reasons for supplying both light and dark themes for the app. Since this application is targeting energy consumption it only makes sense to consider the effect of the apps background color or image on the phones energy use. When displaying darker colors like black the OLED display may use less power, extending battery life. Other Considerations For now I left out options of wind and solar powered energy options because they are not available to everyone. Renewable energy sources and new technologies associated with them are definitely ideas to keep in mind for a next iteration. Another idea to explore for such an application would be to include a savings model similar to mint.com. In addition to general energy-saving recommendations the application could recommend customized ways to save based on your current utility providers and available options in your area. If your television or refrigerator is guilty of sucking a lot of energy then you may see recommendations for energy star products that could save you even more money! Did you know that DotNetSlackers also publishes .net articles written by top known .net Authors? We already have over 80 articles in several categories including Silverlight. Take a look: here.

    Read the article

  • SQL SERVER – Solution of Puzzle – Swap Value of Column Without Case Statement

    - by pinaldave
    Earlier this week I asked a question where I asked how to Swap Values of the column without using CASE Statement. Read here: SQL SERVER – A Puzzle – Swap Value of Column Without Case Statement. I have proposed 3 different solutions in the blog posts itself. I had requested the help of the community to come up with alternate solutions and honestly I am stunned and amazed by the qualified entries. I will be not able to cover every single solution which is posted as a comment, however, I would like to for sure cover few interesting entries. However, I am selecting 5 solutions which are different (not necessary they are most optimal or best – just different and interesting). Just for clarity I am involving the original problem statement here. USE tempdb GO CREATE TABLE SimpleTable (ID INT, Gender VARCHAR(10)) GO INSERT INTO SimpleTable (ID, Gender) SELECT 1, 'female' UNION ALL SELECT 2, 'male' UNION ALL SELECT 3, 'male' GO SELECT * FROM SimpleTable GO -- Insert Your Solutions here -- Swap value of Column Gender SELECT * FROM SimpleTable GO DROP TABLE SimpleTable GO Here are the five most interesting and different solutions I have received. Solution by Roji P Thomas UPDATE S SET S.Gender = D.Gender FROM SimpleTable S INNER JOIN SimpleTable D ON S.Gender != D.Gender I really loved the solutions as it is very simple and drives the point home – elegant and will work pretty much for any values (not necessarily restricted by the option in original question ‘male’ or ‘female’). Solution by Aneel CREATE TABLE #temp(id INT, datacolumn CHAR(4)) INSERT INTO #temp VALUES(1,'gent'),(2,'lady'),(3,'lady') DECLARE @value1 CHAR(4), @value2 CHAR(4) SET @value1 = 'lady' SET @value2 = 'gent' UPDATE #temp SET datacolumn = REPLACE(@value1 + @value2,datacolumn,'') Aneel has very interesting solution where he combined both the values and replace the original value. I personally liked this creativity of the solution. Solution by SIJIN KUMAR V P UPDATE SimpleTable SET Gender = RIGHT(('fe'+Gender), DIFFERENCE((Gender),SOUNDEX(Gender))*2) Sijin has amazed me with Difference and Soundex function. I have never visualized that above two functions can resolve the problem. Hats off to you Sijin. Solution by Nikhildas UPDATE St SET St.Gender = t.Gender FROM SimpleTable St CROSS Apply (SELECT DISTINCT gender FROM SimpleTable WHERE St.Gender != Gender) t I was expecting that someone will come up with this solution where they use CROSS APPLY. This is indeed very neat and for sure interesting exercise. If you do not know how CROSS APPLY works this is the time to learn. Solution by mistermagooo UPDATE SimpleTable SET Gender=X.NewGender FROM (VALUES('male','female'),('female','male')) AS X(OldGender,NewGender) WHERE SimpleTable.Gender=X.OldGender As per author this is a slow solution but I love how syntaxes are placed and used here. I love how he used syntax here. I will say this is the most beautifully written solution (not necessarily it is best). Bonus: Solution by Madhivanan Somehow I was confident Madhi – SQL Server MVP will come up with something which I will be compelled to read. He has written a complete blog post on this subject and I encourage all of you to go ahead and read it. Now personally I wanted to list every single comment here. There are some so good that I am just amazed with the creativity. I will write a part of this blog post in future. However, here is the challenge for you. Challenge: Go over 50+ various solutions listed to the simple problem here. Here are my two asks for you. 1) Pick your best solution and list here in the comment. This exercise will for sure teach us one or two things. 2) Write your own solution which is yet not covered already listed 50 solutions. I am confident that there is no end to creativity. Reference: Pinal Dave (http://blog.SQLAuthority.com) Filed under: PostADay, SQL, SQL Authority, SQL Function, SQL Puzzle, SQL Query, SQL Server, SQL Tips and Tricks, T SQL, Technology

    Read the article

  • It’s the thought that counts…

    - by Tony Davis
    I recently finished editing a book called Tribal SQL, and it was a fantastic experience. It’s a community-sourced book written by first-timers. Fifteen previously unpublished authors contributed one chapter each, with the seemingly simple remit to write about “what makes them passionate about working with SQL Server, something that all SQL Server DBAs and developers really need to know”. Sure, some of the writing skills were a bit rusty as one would expect from busy people, but the ideas and energy were sheer nectar. Any seasoned editor can deal easily with the problem of fixing the output of untrained writers. We can handle with the occasional technical error too, which is why we have technical reviewers. The editor’s real job is to hone the clarity and flow of ideas, making the author’s knowledge and experience accessible to as many others as possible. What the writer needs to bring, on the other hand, is enthusiasm, attention to detail, common sense, and a sense of the person behind the writing. If any of these are missing, no editor can fix it. We can see these essential characteristics in many of the more seasoned and widely-published writers about SQL. To illustrate what I mean by enthusiasm, or passion, take a look at the work of Laerte Junior or Fabiano Amorim. Both authors have English as a second language, but their energy, enthusiasm, sheer immersion in a technology and thirst to know more, drives them, with a little editorial help, to produce articles of far more practical value than one can find in the “manuals”. There’s the attention to detail of the likes of Jonathan Kehayias, or Paul Randal. Read their work and one begins to understand the knowledge coupled with incredible rigor, the willingness to bend and test every piece of advice offered to make sure it’s correct, that marks out the very best technical writing. There’s the common sense of someone like Louis Davidson. All writers, including Louis, like to stretch the grey matter of their readers, but some of the most valuable writing is that which takes a complicated idea, or distils years of experience, and expresses it in a way that sounds like simple common sense. There’s personality and humor. Contrary to what you may have been told, they can and do mix well with technical writing, as long as they don’t become a distraction. Read someone like Rodney Landrum, or Phil Factor, for numerous examples of articles that teach hard technical lessons but also make you smile at least twice along the way. Writing well is not easy and it takes a certain bravery to expose your ideas and knowledge for dissection by others, but it doesn’t mean that writing should be the preserve only of those trained in the art, or best left to the MVPs. I believe that Tribal SQL is testament to the fact that if you have passion for what you do, and really know your topic then, with a little editorial help, you can write, and people will learn from what you have to say. You can read a sample chapter, by Mark Rasmussen, in this issue of Simple-Talk and I hope you’ll consider checking out the book (if you needed any further encouragement, it’s also for a good cause, Computers4Africa). Cheers, Tony  

    Read the article

  • PHP Web Services - Nice try

    Thanks to the membership in the O'Reilly User Group Programme the Mauritius Software Craftsmanship Community (short: MSCC) recently received a welcome package with several book titles. Among them is the latest publication of Lorna Jane Mitchell - 'PHP Web Services: APIs for the Modern Web'. Following is the book review I put on Amazon: Nice try! Initially, I was astonished that a small book like 'PHP Web Services' would be able to cover all the interesting topics about APIs and Web Services, independently whether they are written in PHP or not. And unfortunately, the title isn't able to stand up to the readers (or at least my) expectations. Maybe as a light defense, there is no usual paragraph about the intended audience of that book, but still I have to admit that the first half (chapters 1 to 8) are well written and Lorna has her points on the various technologies. Also, the code samples in PHP are clean and easy to understand. With chapter 'Debugging Web Services' the book started to change my mind about the clarity of advice and the instructions on designing and developing good APIs. Eventually, this might be related to the fact that I'm used to other tools since years, like Telerik Fiddler as HTTP proxy in order to trace and inspect any kind of request/response handling. Including localhost monitoring, SSL certification acceptance, and the ability to debug mobile devices, especially iOS-based ones. Compared to Charles, Fiddler is available for free. What really got me off the hook is the following statement in chapter 10 about Service Type Decisions: "For users who have larger systems using technology stacks such as Java, C++, or .NET, it may be easier for them to integrate with a SOAP service." WHAT? A couple of pages earlier the author recommends to stay away from 'old-fashioned' API styles like SOAP (if possible). And on top of that I wonder why there are tons of documentation towards development of RESTful Web Services based on WebAPI. The ASP.NET stack clearly moves away from SOAP to JSON and REST since years! Honestly, as a software developer on the .NET stack this leaves a mixed feeling after all. As for the remaining chapters I simply consider them as 'blah blah' without any real value and lots of theoretical advice. Related to the chapter 13 about 'Documentation', I just had the 'pleasure' to write a C#-based client against a Java-based SOAP Web Service. Personally, I take the WSDL as the master reference in the first place and Visual Studio generates all the stub types involved in the communication. During the implementation and testing I came across a 'java.lang.NullPointerException' in various methods and for various method parameters. The WSDL and the generated types were declared as Nullable, so nothing to worry about, or? Well, I logged in a support ticket, and guess what was the response to that scenario? "The service definition in the WSDL is wrong, please refer to the documentation in order to use the methods and parameters correctly" - No comment! Lorna's title is a quick read and in some areas she has good advice on designing and implementing Web Services and APIs. But roughly 100 pages aren't enough to cover a vast topic like that. After all, nice try and I'm looking forward to an improved second edition. Honestly, I never thought that I would come across a poor review. In general, it's a good book but it clearly has a lack of depth, the PHP code samples are incomplete (closing tags missing), and there are too many assumptions and theoretical statements.

    Read the article

  • Get Across The Table & Share Your Story By Megha Kapil !!!

    - by Nadiya
    Normal 0 false false false EN-US X-NONE X-NONE MicrosoftInternetExplorer4 I am sure many of you are presently sitting across the table facing an industry expert to prove your mettle. Generally when you think of an interview; first image is of someone firing you with questions & you trying to hit all the shots right. We make an interview look like a court room where you are a victim & being prosecuted to apply for job: Why have you applied for this job, why do you think you are fit for this role, tell me your strengths, tell me your weaknesses, How, When Where, What..?   Interview is a process of knowing a candidate & his/her fitment in the system for interviewer; where as for interviewee its understanding the organization & his/her role. We have made this process of interview synonym to Q&A session. However, as a matter of fact the best scenario is when an interviewee initiates a conversation; which seldom happens. Why don’t we look at our Interview as a meeting to discover a prospect of lifetime, a process to showcase best of our skills, an opportunity to learn while exchanging meaningful dialogue with experts from industry?  We all get inspired when we get to know somebody’s achievements. We like to listen to interesting life stories of people which are positive & motivating. Do you have a story? Everyone does… It’s only about realizing & putting it together. If you want to win the game then the only trick is to “Drive the Conversation”. Tell the interviewer your story; mind you “An Interesting Story”. It’s a non frictional story where you are the “Hero/ Heroine” & you display your strengths to the best. Your story has to be fabricated with hard facts, incidences, experiences & exposures that fits the role you are interested to be in. Story of your success, that describes your knowledge & awareness about the latest trends in industry; solutions which reflect your logical approach towards problem solving. A story which exhibits clarity of your thoughts & ambition; demonstrates your enthusiasm, willingness to learn & passion. Preparation gives you confidence & genuine preparation never goes unnoticed. Organizations look for distinctive individuals; so don’t try to be someone else. Know yourself; be what you are, articulate your characteristics & craft your Unique Story Right Now!! /* Style Definitions */ table.MsoNormalTable {mso-style-name:"Table Normal"; mso-tstyle-rowband-size:0; mso-tstyle-colband-size:0; mso-style-noshow:yes; mso-style-priority:99; mso-style-qformat:yes; mso-style-parent:""; mso-padding-alt:0in 5.4pt 0in 5.4pt; mso-para-margin:0in; mso-para-margin-bottom:.0001pt; mso-pagination:widow-orphan; font-family:"Calibri","sans-serif"; mso-ascii- mso-ascii-theme-font:minor-latin; mso-fareast-font-family:"Times New Roman"; mso-fareast-theme-font:minor-fareast; mso-hansi- mso-hansi-theme-font:minor-latin; mso-bidi-font-family:"Times New Roman"; mso-bidi-theme-font:minor-bidi;}

    Read the article

  • What Counts For a DBA: Imagination

    - by drsql
    "Imagination…One little spark, of inspiration… is at the heart, of all creation." – From the song "One Little Spark", by the Sherman Brothers I have a confession to make. Despite my great enthusiasm for databases and programming, it occurs to me that every database system I've ever worked on has been, in terms of its inputs and outputs, downright dull. Most have been glorified e-spreadsheets, many replacing manual systems built on actual spreadsheets. I've created a lot of database-driven software whose main job was to "count stuff"; phone calls, web visitors, payments, donations, pieces of equipment and so on. Sometimes, instead of counting stuff, the database recorded values from other stuff, such as data from sensors or networking devices. Yee hah! So how do we, as DBAs, maintain high standards and high spirits when we realize that so much of our work would fail to raise the pulse of even the most easily excitable soul? The answer lies in our imagination. To understand what I mean by this, consider a role that, in terms of its output, offers an extreme counterpoint to that of the DBA: the Disney Imagineer. Their job is to design Disney's Theme Parks, of which I'm a huge fan. To me this has always seemed like a fascinating and exciting job. What must an Imagineer do, every day, to inspire the feats of creativity that are so clearly evident in those spectacular rides and shows? Here, if ever there was one, is a role where "dull moments" must be rare indeed, surely? I wanted to find out, and so parted with a considerable sum of money for my wife and I to have lunch with one; I reasoned that if I found one small way to apply their secrets to my own career, it would be money well spent. Early in the conversation with our Imagineer (Cindy Cote), the job did indeed sound magical. However, as talk turned to management meetings, budget-wrangling and insane deadlines, I came to the strange realization that, in fact, her job was a lot more like mine than I would ever have guessed. Much like databases, all those spectacular Disney rides bring with them a vast array of complex plumbing, lighting, safety features, and all manner of other "boring bits", kept well out of sight of the end user, but vital for creating the desired experience; and, of course, it is these "boring bits" that take up much of the Imagineer's time. Naturally, there is still a vital part of their job that is spent testing out new ideas, putting themselves in the place of a park visitor, from a 9-year-old boy to a 90-year-old grandmother, and trying to imagine what experiences they'd like to have. It is these small, but vital, sparks of imagination and creativity that have the biggest impact. The real feat of a successful Imagineer is clearly to never to lose sight of this fact, in among all the rote tasks. It is the same for a DBA. Not matter how seemingly dull is the task at hand, try to put yourself in the shoes of the end user, and imagine how your input will affect the experience he or she will have with the database you're building, and how that may affect the world beyond the bits stored in your database. Then, despite the inevitable rush to be "done", find time to go the extra mile and hone the design so that it delivers something as close to that imagined experience as you can get. OK, our output still can't and won't reach the same spectacular heights as the "Journey into The Imagination" ride at EPCOT Theme Park in Orlando, where I first heard "One Little Spark". However, our imaginative sparks and efforts can, and will, make a difference to the user who now feels slightly more at home with a database application, or to the manager holding a report presented with enough clarity to drive an interesting decision or two. They are small victories, but worth having, and appreciated, or at least that's how I imagine it.

    Read the article

  • Project Euler 17: (Iron)Python

    - by Ben Griswold
    In my attempt to learn (Iron)Python out in the open, here’s my solution for Project Euler Problem 17.  As always, any feedback is welcome. # Euler 17 # http://projecteuler.net/index.php?section=problems&id=17 # If the numbers 1 to 5 are written out in words: # one, two, three, four, five, then there are # 3 + 3 + 5 + 4 + 4 = 19 letters used in total. # If all the numbers from 1 to 1000 (one thousand) # inclusive were written out in words, how many letters # would be used? # # NOTE: Do not count spaces or hyphens. For example, 342 # (three hundred and forty-two) contains 23 letters and # 115 (one hundred and fifteen) contains 20 letters. The # use of "and" when writing out numbers is in compliance # with British usage. import time start = time.time() def to_word(n): h = { 1 : "one", 2 : "two", 3 : "three", 4 : "four", 5 : "five", 6 : "six", 7 : "seven", 8 : "eight", 9 : "nine", 10 : "ten", 11 : "eleven", 12 : "twelve", 13 : "thirteen", 14 : "fourteen", 15 : "fifteen", 16 : "sixteen", 17 : "seventeen", 18 : "eighteen", 19 : "nineteen", 20 : "twenty", 30 : "thirty", 40 : "forty", 50 : "fifty", 60 : "sixty", 70 : "seventy", 80 : "eighty", 90 : "ninety", 100 : "hundred", 1000 : "thousand" } word = "" # Reverse the numbers so position (ones, tens, # hundreds,...) can be easily determined a = [int(x) for x in str(n)[::-1]] # Thousands position if (len(a) == 4 and a[3] != 0): # This can only be one thousand based # on the problem/method constraints word = h[a[3]] + " thousand " # Hundreds position if (len(a) >= 3 and a[2] != 0): word += h[a[2]] + " hundred" # Add "and" string if the tens or ones # position is occupied with a non-zero value. # Note: routine is broken up this way for [my] clarity. if (len(a) >= 2 and a[1] != 0): # catch 10 - 99 word += " and" elif len(a) >= 1 and a[0] != 0: # catch 1 - 9 word += " and" # Tens and ones position tens_position_value = 99 if (len(a) >= 2 and a[1] != 0): # Calculate the tens position value per the # first and second element in array # e.g. (8 * 10) + 1 = 81 tens_position_value = int(a[1]) * 10 + a[0] if tens_position_value <= 20: # If the tens position value is 20 or less # there's an entry in the hash. Use it and there's # no need to consider the ones position word += " " + h[tens_position_value] else: # Determine the tens position word by # dividing by 10 first. E.g. 8 * 10 = h[80] # We will pick up the ones position word later in # the next part of the routine word += " " + h[(a[1] * 10)] if (len(a) >= 1 and a[0] != 0 and tens_position_value > 20): # Deal with ones position where tens position is # greater than 20 or we have a single digit number word += " " + h[a[0]] # Trim the empty spaces off both ends of the string return word.replace(" ","") def to_word_length(n): return len(to_word(n)) print sum([to_word_length(i) for i in xrange(1,1001)]) print "Elapsed Time:", (time.time() - start) * 1000, "millisecs" a=raw_input('Press return to continue')

    Read the article

  • Planning development when academic research is involved

    - by Another Anonymous User
    Dear fellow programmers, how do you do "software planning" when academic research is involved? And, on a side note, how do you convince your boss that writing software is not like building a house and it's more like writing a novel? The gory details are below. I am in charge of a small dev team working in a research lab. We started developing a software with the purpose of going public one day (i.e. sell and make money off that). Such software depends on, amongst other things, at least two independent research lines: that is, there are at least two Ph.D. candidates that will, hopefully, one day come out with a working implementation of what we need. The main software depends also on other, more concrete resources that we as developers can take care of: graphics rendering, soft bodies deformation, etc. My boss asked me to write the specifications, requirements AND a bloody GANTT chart of the entire project. Faced with the fact that I don't have a clue about the research part, and that such research is fundamental for the software, he said "make assumptions." For the clarity of the argument, he is a professor whose Ph.D. students should come up with the research we need. And he comes from a strictly engineering background: plan everything first, write down specifications and only then write down code that "it's the last part". What I am doing now: I broke down the product in features; each 'feature' is, de facto, a separate product; Each feature is built on top of the previous one; Once a feature (A) has a working prototype the team can start working on the next feature (B), while QA for is being done for A (if money allows, more people can be brought in, etc.); Features that depend on research will come last: by then, hopefully, the research part will be completed (when is still a big question) ; Also, I set the team to use SCRUM for the development of 'version 1.0', due in a few months. This deadline could be set based on reasonable assumptions: we listed all required features, we counted our availability, and we gave a reasonable estimate. So my questions, again, are: How do I make my boss happy while at the same time get something out the door? How do I write specifications for something we -the developers- have no clue whether it's possible to do or not? (We still haven't decided which libraries to use for some tasks; we'll do so when we'll need to) How do I get the requirements for that, given that there are yet no clients nor investors, just lots of interests and promises? How do I get peace in the world? I am sure at least one of my questions will be answered :) ps: I am writing this anonymously since a potential investor might backfire if this is discovered. Hope you'll understand. However I must say I do not like this mentality of 'hiding the truth': this program will likely benefit many, and not being able to talk openly about this (with my name and my reputation attached) feels like censorship. But alas, I care more about your suggestions now.

    Read the article

  • Planning development when academic research is involved

    - by Another Anonymous User
    Dear fellow programmers, how do you do "software planning" when academic research is involved? And, on a side note, how do you convince your boss that writing software is not like building a house and it's more like writing a novel? The gory details are below. I am in charge of a small dev team working in a research lab. We started developing a software with the purpose of going public one day (i.e. sell and make money off that). Such software depends on, amongst other things, at least two independent research lines: that is, there are at least two Ph.D. candidates that will, hopefully, one day come out with a working implementation of what we need. The main software depends also on other, more concrete resources that we as developers can take care of: graphics rendering, soft bodies deformation, etc. My boss asked me to write the specifications, requirements AND a bloody GANTT chart of the entire project. Faced with the fact that I don't have a clue about the research part, and that such research is fundamental for the software, he said "make assumptions." For the clarity of the argument, he is a professor whose Ph.D. students should come up with the research we need. And he comes from a strictly engineering background: plan everything first, write down specifications and only then write down code that "it's the last part". What I am doing now: I broke down the product in features; each 'feature' is, de facto, a separate product; Each feature is built on top of the previous one; Once a feature (A) has a working prototype the team can start working on the next feature (B), while QA for is being done for A (if money allows, more people can be brought in, etc.); Features that depend on research will come last: by then, hopefully, the research part will be completed (when is still a big question) ; Also, I set the team to use SCRUM for the development of 'version 1.0', due in a few months. This deadline could be set based on reasonable assumptions: we listed all required features, we counted our availability, and we gave a reasonable estimate. So my questions, again, are: How do I make my boss happy while at the same time get something out the door? How do I write specifications for something we -the developers- have no clue whether it's possible to do or not? (We still haven't decided which libraries to use for some tasks; we'll do so when we'll need to) How do I get the requirements for that, given that there are yet no clients nor investors, just lots of interests and promises? How do I get peace in the world? I am sure at least one of my questions will be answered :) ps: I am writing this anonymously since a potential investor might backfire if this is discovered. Hope you'll understand. However I must say I do not like this mentality of 'hiding the truth': this program will likely benefit many, and not being able to talk openly about this (with my name and my reputation attached) feels like censorship. But alas, I care more about your suggestions now.

    Read the article

  • C#&ndash;Using a delegate to raise an event from one class to another

    - by Bill Osuch
    Even though this may be a relatively common task for many people, I’ve had to show it to enough new developers that I figured I’d immortalize it… MSDN says “Events enable a class or object to notify other classes or objects when something of interest occurs. The class that sends (or raises) the event is called the publisher and the classes that receive (or handle) the event are called subscribers.” Any time you add a button to a Windows Form or Web app, you can subscribe to the OnClick event, and you can also create your own event handlers to pass events between classes. Here I’ll show you how to raise an event from a separate class to a console application (or Windows Form). First, create a console app project (you could create a Windows Form, but this is easier for this demo). Add a class file called MyEvent.cs (it doesn’t really need to be a separate file, this is just for clarity) with the following code: public delegate void MyHandler1(object sender, MyEvent e); public class MyEvent : EventArgs {     public string message; } Your event can have whatever public properties you like; here we’re just got a single string. Next, add a class file called WorkerDLL.cs; this will simulate the class that would be doing all the work in the project. Add the following code: class WorkerDLL {     public event MyHandler1 Event1;     public WorkerDLL()     {     }     public void DoWork()     {         FireEvent("From Worker: Step 1");         FireEvent("From Worker: Step 5");         FireEvent("From Worker: Step 10");     }     private void FireEvent(string message)     {         MyEvent e1 = new MyEvent();         e1.message = message;         if (Event1 != null)         {             Event1(this, e1);         }         e1 = null;     } } Notice that the FireEvent method creates an instance of the MyEvent class and passes it to the Event1 handler (which we’ll create in just a second). Finally, add the following code to Program.cs: static void Main(string[] args) {     Program p = new Program(args); } public Program(string[] args) {     Console.WriteLine("From Console: Creating DLL");     WorkerDLL wd = new WorkerDLL();     Console.WriteLine("From Console: Wiring up event handler");     WireEventHandlers(wd);     Console.WriteLine("From Console: Doing the work");     wd.DoWork();     Console.WriteLine("From Console: Done - press any key to finish.");     Console.ReadLine(); } private void WireEventHandlers(WorkerDLL wd) {     MyHandler1 handler = new MyHandler1(OnHandler1);     wd.Event1 += handler; } public void OnHandler1(object sender, MyEvent e) {     Console.WriteLine(e.message); } The OnHandler1 method is called any time the event handler “hears” an event matching the specified signature – you could have it log to a file, write to a database, etc. Run the app in debug mode and you should see output like this: You can distinctly see which lines were written by the console application itself (Program.cs) and which were written by the worker class (WorkerDLL.cs). Technorati Tags: Csharp

    Read the article

  • Broken Views

    - by Ajarn Mark Caldwell
    “SELECT *” isn’t just hazardous to performance, it can actually return blatantly wrong information. There are a number of blog posts and articles out there that actively discourage the use of the SELECT * FROM …syntax.  The two most common explanations that I have seen are: Performance:  The SELECT * syntax will return every column in the table, but frequently you really only need a few of the columns, and so by using SELECT * your are retrieving large volumes of data that you don’t need, but the system has to process, marshal across tiers, and so on.  It would be much more efficient to only select the specific columns that you need. Future-proof:  If you are taking other shortcuts in your code, along with using SELECT *, you are setting yourself up for trouble down the road when enhancements are made to the system.  For example, if you use SELECT * to return results from a table into a DataTable in .NET, and then reference columns positionally (e.g. myDataRow[5]) you could end up with bad data if someone happens to add a column into position 3 and skewing all the remaining columns’ ordinal position.  Or if you use INSERT…SELECT * then you will likely run into errors when a new column is added to the source table in any position. And if you use SELECT * in the definition of a view, you will run into a variation of the future-proof problem mentioned above.  One of the guys on my team, Mike Byther, ran across this in a project we were doing, but fortunately he caught it while we were still in development.  I asked him to put together a test to prove that this was related to the use of SELECT * and not some other anomaly.  I’ll walk you through the test script so you can see for yourself what happens. We are going to create a table and two views that are based on that table, one of them uses SELECT * and the other explicitly lists the column names.  The script to create these objects is listed below. IF OBJECT_ID('testtab') IS NOT NULL DROP TABLE testtabgoIF OBJECT_ID('testtab_vw') IS NOT NULL DROP VIEW testtab_vwgo IF OBJECT_ID('testtab_vw_named') IS NOT NULL DROP VIEW testtab_vw_namedgo CREATE TABLE testtab (col1 NVARCHAR(5) null, col2 NVARCHAR(5) null)INSERT INTO testtab(col1, col2)VALUES ('A','B'), ('A','B')GOCREATE VIEW testtab_vw AS SELECT * FROM testtabGOCREATE VIEW testtab_vw_named AS SELECT col1, col2 FROM testtabgo Now, to prove that the two views currently return equivalent results, select from them. SELECT 'star', col1, col2 FROM testtab_vwSELECT 'named', col1, col2 FROM testtab_vw_named OK, so far, so good.  Now, what happens if someone makes a change to the definition of the underlying table, and that change results in a new column being inserted between the two existing columns?  (Side note, I normally prefer to append new columns to the end of the table definition, but some people like to keep their columns alphabetized, and for clarity for later people reviewing the schema, it may make sense to group certain columns together.  Whatever the reason, it sometimes happens, and you need to protect yourself and your code from the repercussions.) DROP TABLE testtabgoCREATE TABLE testtab (col1 NVARCHAR(5) null, col3 NVARCHAR(5) NULL, col2 NVARCHAR(5) null)INSERT INTO testtab(col1, col3, col2)VALUES ('A','C','B'), ('A','C','B')goSELECT 'star', col1, col2 FROM testtab_vwSELECT 'named', col1, col2 FROM testtab_vw_named I would have expected that the view using SELECT * in its definition would essentially pass-through the column name and still retrieve the correct data, but that is not what happens.  When you run our two select statements again, you see that the View that is based on SELECT * actually retrieves the data based on the ordinal position of the columns at the time that the view was created.  Sure, one work-around is to recreate the View, but you can’t really count on other developers to know the dependencies you have built-in, and they won’t necessarily recreate the view when they refactor the table. I am sure that there are reasons and justifications for why Views behave this way, but I find it particularly disturbing that you can have code asking for col2, but actually be receiving data from col3.  By the way, for the record, this entire scenario and accompanying test script apply to SQL Server 2008 R2 with Service Pack 1. So, let the developer beware…know what assumptions are in effect around your code, and keep on discouraging people from using SELECT * syntax in anything but the simplest of ad-hoc queries. And of course, let’s clean up after ourselves.  To eliminate the database objects created during this test, run the following commands. DROP TABLE testtabDROP VIEW testtab_vwDROP VIEW testtab_vw_named

    Read the article

  • EL syntax error: Expression cannot start with binary operator

    - by auser
    Anyone have any creative ideas for how I can solve this warning? EL syntax error: Expression cannot start with binary operator caused by the following code: String.format("#{myController.deleteItemById(%d)}", getId()) My code looked like this before: "#{myController.deleteItemById(" + getId() + ")}" but this caused eclipse to generate the following warning: EL syntax error: String is not closed UPDATE: @ManagedBean(name = "myController") @ViewScoped public class MyController implements Serializable { private long id; private HtmlPanelGroup panel; public long getId() {return this.id; } private void getPanel() { /// bunch of code for programatically creating a form HtmlCommandButton deleteButton = new HtmlCommandButton(); deleteButton.setId(id); deleteButton.setValue(value); deleteButton.setActionExpression(/* EL expression used here */); } } <?xml version='1.0' encoding='UTF-8' ?> <html xmlns="http://www.w3.org/1999/xhtml" xmlns:h="http://java.sun.com/jsf/html" xmlns:f="http://java.sun.com/jsf/core" xmlns:ui="http://java.sun.com/jsf/facelets"> <!-- some other elements removed for the sake of clarity --> <h:body> <h:panelGroup binding="#{myController.panel}" /> </h:body> </html>

    Read the article

  • Python recursive function error: "maximum recursion depth exceeded"

    - by user283169
    I solved Problem 10 of Project Euler with the following code, which works through brute force: def isPrime(n): for x in range(2, int(n**0.5)+1): if n % x == 0: return False return True def primeList(n): primes = [] for i in range(2,n): if isPrime(i): primes.append(i) return primes def sumPrimes(primelist): prime_sum = sum(primelist) return prime_sum print (sumPrimes(primeList(2000000))) The three functions work as follows: isPrime checks whether a number is a prime; primeList returns a list containing a set of prime numbers for a certain range with limit 'n', and; sumPrimes sums up the values of all numbers in a list. (This last function isn't needed, but I liked the clarity of it, especially for a beginner like me.) I then wrote a new function, primeListRec, which does exactly the same thing as primeList, to help me better understand recursion: def primeListRec(i, n): primes = [] #print i if (i != n): primes.extend(primeListRec(i+1,n)) if (isPrime(i)): primes.append(i) return primes return primes The above recursive function worked, but only for very small values, like '500'. The function caused my program to crash when I put in '1000'. And when I put in a value like '2000', Python gave me this: RuntimeError: maximum recursion depth exceeded. What did I do wrong with my recursive function? Or is there some specific way to avoid a recursion limit?

    Read the article

  • How do I get folder size with Exchange Web Services 2010 Managed API?

    - by Adam Tuttle
    I'm attempting to use EWS 2010 Managed API to get the total size of a user's mailbox. I haven't found a web service method to get this data, so I figured I would try to calculate it. I found one seemingly-applicable question on another site about finding mailbox sizes with EWS 2007, but either I'm not understanding what it's asking me to do, or that method just doesn't work with EWS 2010. Noodling around in the code insight, I was able to write what I thought was a method that would traverse the folder structure recursively and result in a combined total for all folders inside the Inbox: private int traverseChildFoldersForSize(Folder f) { int folderSizeSum = 0; if (f.ChildFolderCount > 0) { foreach (Folder c in f.FindFolders(new FolderView(10000))) { folderSizeSum += traverseChildFoldersForSize(c); } } folderSizeSum += (int)f.ManagedFolderInformation.FolderSize; return folderSizeSum; } (Assumes there aren't more than 10,000 folders inside a given folder. Figure that's a safe bet...) Unfortunately, this doesn't work. I'm initiating the recursion with this code: Folder root = Folder.Bind(svc, WellKnownFolderName.Inbox); int totalSize = traverseChildFoldersForSize(root); But a Null Pointer Exception is thrown, essentially saying that [folder].ManagedFolderInformation is a null object reference. For clarity, I also attempted to just get the size of the root folder: Console.Write(root.ManagedFolderInformation.FolderSize.ToString()); Which threw the same NPE exception, so I know that it's not just that once you get to a certain depth in the directory tree that ManagedFolderInformation doesn't exist. Any ideas on how to get the total size of the user's mailbox? Am I barking up the wrong tree?

    Read the article

  • Tiff Analyzer

    - by Kevin
    I am writing a program to convert some data, mainly a bunch of Tiff images. Some of the Tiffs seems to have a minor problem with them. They show up fine in some viewers (Irfanview, client's old system) but not in others (Client's new system, Window's picture and fax viewer). I have manually looked at the binary data and all the tags seem ok. Can anyone recommend an app that can analyze it and tell me what, if anything, is wrong with it? Also, for clarity sake, I'm only converting the data about the images which is stored seperately in a database and copying the images, I'm not editting the images myself, so I'm pretty sure I'm not messing them up. UDPATE: For anyone interested, here are the tags from a good and bad file: BAD Tag Type Length Value 256 Image Width SHORT 1 1652 257 Image Length SHORT 1 704 258 Bits Per Sample SHORT 1 1 259 Compression SHORT 1 4 262 Photometric SHORT 1 0 266 Fill Order SHORT 1 1 273 Strip Offsets LONG 1 210 (d2 Hex) 274 Orientation SHORT 1 3 277 Samples Per Pixel SHORT 1 1 278 Rows Per Strip SHORT 1 450 279 Strip Byte Counts LONG 1 7264 (1c60 Hex) 282 X Resolution RATIONAL 1 <194 200 / 1 = 200.000 283 Y Resolution RATIONAL 1 <202 200 / 1 = 200.000 284 Planar Configuration SHORT 1 1 296 Resolution Unit SHORT 1 2 Good Tag Type Length Value 254 New Subfile Type LONG 1 0 (0 Hex) 256 Image Width SHORT 1 1193 257 Image Length SHORT 1 788 258 Bits Per Sample SHORT 1 1 259 Compression SHORT 1 4 262 Photometric SHORT 1 0 266 Fill Order SHORT 1 1 270 Image Description ASCII 45 256 273 Strip Offsets LONG 1 1118 (45e Hex) 274 Orientation SHORT 1 1 277 Samples Per Pixel SHORT 1 1 278 Rows Per Strip LONG 1 788 (314 Hex) 279 Strip Byte Counts LONG 1 496 (1f0 Hex) 280 Min Sample Value SHORT 1 0 281 Max Sample Value SHORT 1 1 282 X Resolution RATIONAL 1 <301 200 / 1 = 200.000 283 Y Resolution RATIONAL 1 <309 200 / 1 = 200.000 284 Planar Configuration SHORT 1 1 293 Group 4 Options LONG 1 0 (0 Hex) 296 Resolution Unit SHORT 1 2

    Read the article

  • Explicit casting doesn't work in default model binding

    - by Felix
    I am using ASP.NET MVC2 and Entity Framework. I am going to simplify the situation a little; hopefully it will make it clearer, not more confusing! I have a controller action to create address, and the country is a lookup table (in other words, there is a one-to-many relationship between Country and Address classes). Let's say for clarity that the field in the Address class is called Address.Land. And, for the purposes of the dropdown list, I am getting Country.CountryID and Country.Name. I am aware of Model vs. Input validation. So, if I call the dropdown field formLand - I can make it work. But if I call the field Land (that is, matching the variable in Address class) - I am getting the following error: "The parameter conversion from type 'System.String' to type 'App.Country' failed because no type converter can convert between these types." OK, this makes sense. A string (CountryID) comes from the form and the binder doesn't know how to convert it to Country type. So, I wrote the converter: namespace App { public partial class Country { public static explicit operator Country(string countryID) { AppEntities context = new AppEntities(); Country country = (Country) context.GetObjectByKey( new EntityKey("AppEntities.Countries", "CountryID", countryID)); return country; } } } FWIW, I tried both explicit and implicit. I tested it from the controller - Country c = (Country)"fr" - and it works fine. However, it never got invoked when the View is posted. I am getting the same "no type converter" error in the model. Any ideas how to hint to the model binder that there is a type converter? Thanks

    Read the article

  • How can you replace the src of an image that points to mjpeg?

    - by user165623
    I have an application that displays images from network cameras. The application will show multiple images on a single page. Each image container has a button on it that causes jQuery to scale that image up to fill a 64x480 div vs much smaller when multiple images are present. I change the src in the image with jquery as you'd expect: $("#imageId").attr("src", "http://cameraUrl.com:6000?width=640&height=480&d="+date.getTime()); the date.getTime() is intended to override the caching in a browser. It works for retrieving still images. Sometimes the video changes to the larger resolution. Other times it just sticks with the original image scaled up to fit the larger div as if it is not loading the new URL. This is evident by the fact it's grainy and the text overlay from the camera is scaled up. Occasionally the image finally loads in the higher resolution version and it works evidenced by the image clarity and the text overlay scaling to what it should be. Is there a correct way to force the setting of an image src where the src points to a motion jpeg stream to reload?

    Read the article

  • Winforms MVP with Castle Windsor - DI for subforms?

    - by Paul Kirby
    I'm building a winforms app utilizing passive-view MVP and Castle Windsor as an IoC container. I'm still a little new to dependency injection and MVP, so I'm looking for some clarity... I have a main form which contains a number of user controls, and also will bring up other dialogs (ex. Login, options, etc) as needed. My first question is...should I use constructor injection to get the presenters for these other views into the main view, or should I go back to a Service Locator-type pattern? (which I've been told is a big nono!) Or something else? Second question...the user controls need to communicate back to the main form when they are "completed" (definition of that state varies based on the control). Is there a standard way of hooking these up? I was thinking perhaps just wiring up events between the main presenter and the child presenters, but I'm not sure if this is proper thinking. I'd appreciate any help, it seems that the combination of MVP and IoC in winforms isn't exactly well-documented.

    Read the article

< Previous Page | 6 7 8 9 10 11 12 13 14 15 16  | Next Page >