Search Results

Search found 1251 results on 51 pages for 'negative'.

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

  • Java: any problems/negative sides of keeping SoftReference to ArrayList in HttpSession?

    - by westla7
    My code is doing the following (just as an example, and the reason that I specify package path to java.lang.ref.SoftReference is to note that it's not my own implementaiton :-): ... List<String> someData = new ArrayList<String>(); someData.add("Value1"); someData.add("Value2"); ... java.lang.ref.SoftReference softRef = new SoftReference(someData); ... HttpSession session = request.getSession(true); session.setAttribute("mySoftRefData", softRef); ... and later: ... java.lang.ref.SoftReference softRef = session.getAttribute("mySoftRefData"); if (softRef != null && softRef.get() != null) { List<String> someData = (List<String>)softRef.get(); // do something with it. } ... Any disadvantages? Which I do not see? Thank you!

    Read the article

  • How can I set the order of the positive and negative buttons in AlertDialog?

    - by Micah Hainline
    Why I want to do this is another discussion entirely, but I need to figure out the best way to make all my alert dialogs have the positive button on the right side. Note that in version 3.0 and below the buttons normally appear as OK / Cancel and in 4.0 and above it is Cancel / OK. I want to force my application to use Cancel / OK in the simplest way possible. I have a lot of AlertDialogs in the application.

    Read the article

  • What could the negative effects be of attaching to a process as a debugger?

    - by I_like_traffic_lights
    Background A client of mine has a major problem. They have a CRM system, which was created by a single person over a period of 9 years. Unfortunatelly, a few weeks ago, this person died. I believe the company has learned their lesson, and they have started a project of rewriting the CRM system to a modern platform. I have been hired to create a solution in the meantime to make adaptations to the CRM system. I have given up understanding the code, as this would take too long. My solution, is therefore, to make a window and show this on top of the CRM system, whenever this CRM system is showing. This part works fine, but my major problem is extracting the data from the CRM system. Proposed solution After excluding 6 approaches, including runtime code injection, memory searching, database integration, I have arrived at attaching to the process as a debugger, so I get notified about event, and use this in combination with reading from process memory. This approach seems to work, but I am worried about possible side-effects of this approach. Question What are the dangers of using this in a production environment, where there are 250 employees utilizing the system. Needless to say, I cannot risk reducing the already shaky stability of the system.

    Read the article

  • updating a column in a table only if after the update it won't be negative and identifying all updat

    - by Azeem
    Hello all, I need some help with a SQL query. Here is what I need to do. I'm lost on a few aspects as outlined below. I've four relevant tables: Table A has the price per unit for all resources. I can look up the price using a resource id. Table B has the funds available to a given user. Table C has the resource production information for a given user (including the number of units to produce everyday). Table D has the number of units ever produced by any given user (can be identified by user id and resource id) Having said that, I need to run a batch job on a nightly basis to do the following: a. for all users, identify whether they have the funds needed to produce the number of resources specified in table C and deduct the funds if they are available from table B (calculating the cost using table A). b. start the process to produce resources and after the resource production is complete, update table D using values from table C after the resource product is complete. I figured the second part can be done by using an UPDATE with a subquery. However, I'm not sure how I should go about doing part a. I can only think of using a cursor to fetch each row, examine and update. Is there a single sql statement that will help me avoid having to process each row manually? Additionally, if any rows weren't updated, the part b. SQL should not produce resources for that user. Basically, I'm attempting to modify the sql being used for this logic that currently is in a stored procedure to something that will run a lot faster (and won't process each row separately). Please let me know any ideas and thoughts. Thanks! - Azeem

    Read the article

  • Greiner-Hormann clipping problem

    - by Belgin
    I have a set of planar polygons in 3D space defined by their vertices in counterclockwise order. Let's define the 'positive face' as being the face of the 3D polygon such as when observed, the vertices appear in counterclockwise order, and the 'negative face', the face which when observed, the vertices appear in clockwise order. I'm doing perspective projection of the set of polygons onto a projection polygon defined by the points in this order: (0, h, 0), (0, 0, 0), (w, 0, 0), and (w, h, 0), where w and h are strictly positive integers. The positive face of this projection polygon is oriented towards positive Z, and the camera point is somewhere at (0, 0, d), where d is a strictly negative number. In order to 'clip' the projected polygons into the projection polygon, I'm applying the Greiner-Hormann (PDF) clipping algorithm, which requires that the clipper and the to-be-clipped polygons be in the same order (i.e. clockwise or counterclockwise). My question is the following: How can I determine whether the projected face of the 3D polygon is the negative or the positive one? Meaning, how do I find out if I have to work with the vertices in normal or inverted order for the algorithm to work? I noticed that only if the 3D polygon is facing the projection polygon with its negative face, both of them are in the same order (counterclockwise), otherwise, a modification needs to be done. Here is a picture (PNG) that illustrates this. Note that the planes described by the polygon from the set and the projection polygon may not always be parallel.

    Read the article

  • Refactoring an ERB Template to Haml

    - by Liam McLennan
    ERB is the default view templating system used by Ruby on Rails. Haml is an alternative templating system that uses whitespace to represent document structure. The example from the haml website shows the following equivalent markup: Haml ERB #profile .left.column #date= print_date #address= current_user.address .right.column #email= current_user.email #bio= current_user.bio <div id="profile"> <div class="left column"> <div id="date"><%= print_date %></div> <div id="address"><%= current_user.address %></div> </div> <div class="right column"> <div id="email"><%= current_user.email %></div> <div id="bio"><%= current_user.bio %></div> </div> </div> I like haml because it is concise and the significant whitespace makes it easy to see the structure at a glance. This post is about a ruby project but nhaml makes haml available for asp.net MVC also. The ERB Template Today I spent some time refactoring an ERB template to Haml. The template is called list.html.erb and its purpose is to render a list of tweets (twitter messages). <style> form { float: left; } </style> <h1>Tweets</h1> <table> <thead><tr><th></th><th>System</th><th>Human</th><th></th></tr></thead> <% @tweets.each do |tweet| %> <tr> <td><%= h(tweet['text']) %></td> <td><%= h(tweet['system_classification']) %></td> <td><%= h(tweet['human_classification']) %></td> <td><form action="/tweet/rate" method="post"> <%= token_tag %> <input type="submit" value="Positive"/> <input type="hidden" value="<%= tweet['id']%>" name="id" /> <input type="hidden" value="positive" name="rating" /> </form> <form action="/tweet/rate" method="post"> <%= token_tag %> <input type="submit" value="Neutral"/> <input type="hidden" value="<%= tweet['id']%>" name="id" /> <input type="hidden" value="neutral" name="rating" /> </form> <form action="/tweet/rate" method="post"> <%= token_tag %> <input type="submit" value="Negative"/> <input type="hidden" value="<%= tweet['id']%>" name="id" /> <input type="hidden" value="negative" name="rating" /> </form> </td> </tr> <% end %> </table> Haml Template: Take 1 My first step was to convert this page to a Haml template in place. Directly translating the ERB template to Haml resulted in: list.haml %style form {float: left;} %h1 Tweets %table %thead %tr %th %th System %th Human %th %tbody - @tweets.each do |tweet| %tr %td= tweet['text'] %td= tweet['system_classification'] %td= tweet['human_classification'] %td %form{ :action=>"/tweet/rate", :method=>"post"} = token_tag <input type="submit" value="Positive"/> <input type="hidden" value="positive" name="rating" /> %input{ :type=>"hidden", :value => tweet['id']} %form{ :action=>"/tweet/rate", :method=>"post"} = token_tag <input type="submit" value="Neutral"/> <input type="hidden" value="neutral" name="rating" /> %input{ :type=>"hidden", :value => tweet['id']} %form{ :action=>"/tweet/rate", :method=>"post"} = token_tag <input type="submit" value="Negative"/> <input type="hidden" value="negative" name="rating" /> %input{ :type=>"hidden", :value => tweet['id']} end I like this better already but I can go further. Haml Template: Take 2 The haml documentation says to avoid using iterators so I introduced a partial template (_tweet.haml) as the template to render a single tweet. _tweet.haml %tr %td= tweet['text'] %td= tweet['system_classification'] %td= tweet['human_classification'] %td %form{ :action=>"/tweet/rate", :method=>"post"} = token_tag <input type="submit" value="Positive"/> <input type="hidden" value="positive" name="rating" /> %input{ :type=>"hidden", :value => tweet['id']} %form{ :action=>"/tweet/rate", :method=>"post"} = token_tag <input type="submit" value="Neutral"/> <input type="hidden" value="neutral" name="rating" /> %input{ :type=>"hidden", :value => tweet['id']} %form{ :action=>"/tweet/rate", :method=>"post"} = token_tag <input type="submit" value="Negative"/> <input type="hidden" value="negative" name="rating" /> %input{ :type=>"hidden", :value => tweet['id']} and the list template is simplified to: list.haml %style form {float: left;} %h1 Tweets %table     %thead         %tr             %th             %th System             %th Human             %th     %tbody         = render(:partial => "tweet", :collection => @tweets) That is definitely an improvement, but then I noticed that _tweet.haml contains three form tags that are nearly identical.   Haml Template: Take 3 My first attempt, later aborted, was to use a helper to remove the duplication. A much better solution is to use another partial.  _rate_button.haml %form{ :action=>"/tweet/rate", :method=>"post"} = token_tag %input{ :type => "submit", :value => rate_button[:rating].capitalize } %input{ :type => "hidden", :value => rate_button[:rating], :name => 'rating' } %input{ :type => "hidden", :value => rate_button[:id], :name => 'id' } and the tweet template is now simpler: _tweet.haml %tr %td= tweet['text'] %td= tweet['system_classification'] %td= tweet['human_classification'] %td = render( :partial => 'rate_button', :object => {:rating=>'positive', :id=> tweet['id']}) = render( :partial => 'rate_button', :object => {:rating=>'neutral', :id=> tweet['id']}) = render( :partial => 'rate_button', :object => {:rating=>'negative', :id=> tweet['id']}) list.haml remains unchanged. Summary I am extremely happy with the switch. No doubt there are further improvements that I can make, but I feel like what I have now is clean and well factored.

    Read the article

  • Index was out of range. Must be non-negative and less than the size of the collection. Parameter: In

    - by user356973
    Dear Telerik Team, When I am trying to display data using radgrid I am getting error like "Index was out of range. Must be non-negative and less than the size of the collection. Parameter: Index". Here is my code <telerik:RadGrid ID="gvCktMap" BorderColor="White" runat="server" AutoGenerateColumns="true" AllowSorting="true" BackColor="White" AllowPaging="true" PageSize="25" GridLines="None" OnPageIndexChanging="gvCktMap_PageIndexChanging" OnRowCancelingEdit="gvCktMap_RowCancelingEdit" OnRowCommand="gvCktMap_RowCommand" OnRowUpdating="gvCktMap_RowUpdating" OnRowDataBound="gvCktMap_RowDataBound" OnSorting="gvCktMap_Sorting" OnRowEditing="gvCktMap_RowEditing" ShowGroupPanel="True" EnableHeaderContextMenu="true" EnableHeaderContextFilterMenu="true" AllowMultiRowSelection="true" AllowFilteringByColumn="True" AllowCustomPaging="false" OnItemCreated="gvCktMap_ItemCreated" EnableViewState="false" OnNeedDataSource="gvCktMap_NeedDataSource" OnItemUpdated="gvCktMap_ItemUpdated" > <MasterTableView DataKeyNames="sId" UseAllDataFields="true"> <Columns> <telerik:GridBoundColumn UniqueName="sId" HeaderText="sId" DataField="sId" Visible="false"> </telerik:GridBoundColumn> <telerik:GridBoundColumn UniqueName="orderId" HeaderText="orderId" DataField="orderId"> </telerik:GridBoundColumn> <telerik:GridBoundColumn UniqueName="REJ" HeaderText="REJ" DataField="REJ"> </telerik:GridBoundColumn> <telerik:GridBoundColumn UniqueName="Desc" HeaderText="Desc" DataField="Desc"> </telerik:GridBoundColumn> <telerik:GridBoundColumn UniqueName="CustomerName" HeaderText="CustomerName" DataField="CustomerName"> </telerik:GridBoundColumn> <telerik:GridBoundColumn UniqueName="MarketName" HeaderText="MarketName" DataField="MarketName"> </telerik:GridBoundColumn> <telerik:GridBoundColumn UniqueName="HeadendName" HeaderText="HeadendName" DataField="HeadendName"> </telerik:GridBoundColumn> <telerik:GridBoundColumn UniqueName="SiteName" HeaderText="SiteName" DataField="SiteName"> </telerik:GridBoundColumn> <telerik:GridBoundColumn UniqueName="TaskStatus" HeaderText="TaskStatus" DataField="TaskStatus"> </telerik:GridBoundColumn> </Columns> </telerik:RadGrid> Here is my code behind private void bingGrid() { try { gvCktMap.Columns.Clear(); DataSet dsResult = new DataSet(); DataSet dsEditItems = new DataSet(); dsEditItems.ReadXml(Server.MapPath("XMLS/" + Session["TaskID"].ToString() + ".xml")); clsSearch_BL clsObj = new clsSearch_BL(); clsObj.TaskID = (string)Session["TaskID"]; clsObj.CustName = (string)Session["CustName"]; clsObj.MarketName = (string)Session["MarketName"]; clsObj.HeadendName = (string)Session["HeadendName"]; clsObj.SiteName = (string)Session["SiteName"]; clsObj.TaskStatus = (string)Session["TaskStatus"]; clsObj.OrdType = (string)Session["OrdType"]; clsObj.OrdStatus = (string)Session["OrdStatus"]; clsObj.ProName = (string)Session["ProName"]; clsObj.LOC = (string)Session["LOC"]; dsResult = clsObj.getSearchResults_BL(clsObj); Session["SearchRes"] = dsResult; DataTable dtFilter = new DataTable(); DataColumn dtCol = new DataColumn("FilterBy"); dtFilter.Columns.Add(dtCol); dtCol = new DataColumn("DataType"); dtFilter.Columns.Add(dtCol); gvCktMap.DataSource = dsResult; gvCktMap.DataBind(); } catch (Exception ex) { } } If i remove <MasterTableView></MasterTableView> Its working fine without any error. But for some reasons i need to use <MasterTableView></MasterTableView> Can anyone help me out to fix this error. Thanks In Advance

    Read the article

  • Can I mix compile time string comparison with MPL templates?

    - by Negative Zero
    I got this compile time string comparison from another thread using constexpr and C++11 (http://stackoverflow.com/questions/5721813/compile-time-assert-for-string-equality). It works with constant strings like "OK" constexpr bool isequal(char const *one, char const *two) { return (*one && *two) ? (*one == *two && isequal(one + 1, two + 1)) : (!*one && !*two); } I am trying to use it in the following context: static_assert(isequal(boost::mpl::c_str<boost::mpl::string<'ak'>>::value, "ak"), "should not fail"); But it gives me an compilation error of static_assert expression is not an constant integral expression. Can I do this?

    Read the article

  • Creating a folder inside Mac OS App

    - by Negative Zero
    I want a an app that is "self-contained" (I don't know if i use the right word. "putting the app into trash bin will remove everything" is what I meant). But the app requires some resources to run. I usually put those resources into a folder. I want to move those resources into the App folder ( package contents). Can I do that? Is it a good practice to do that? When I test the app directly running from Xcode, the App runs fine. But if i run it from finder, the app will say fails to create resources folder because permission denied. I checked the app's folder permission - User(me) has read/write access. I am wondering what is causing this different behavior. The last option is to use Application Support folder, but I don't want to leave trails when user deletes the app. Can someone help me out here?

    Read the article

  • Correct way to take absolute value of INT_MIN

    - by aka.nice
    I want to perform some arithmetic in unsigned, and need to take absolute value of negative int, something like do_some_arithmetic_in_unsigned_mode(int some_signed_value) { unsigned int magnitude; int negative; if(some_signed_value<0) { magnitude = 0 - some_signed_value; negative = 1; } else { magnitude = some_signed_value; negative = 0; } ...snip... } But INT_MIN might be problematic, 0 - INT_MIN is UB if performed in signed arithmetic. What is a standard/robust/safe/efficient way to do this in C?

    Read the article

  • ActionScript Negating a Number

    - by TheDarkIn1978
    i'd like to negate a number and would like to know if there's a built in method that will convert a negative number to a positive OR a positive into a negative, depending on the number. i know about Math.abs(), but that only seems to convert negative into positive. is there a method that will do both?

    Read the article

  • SQL SERVER – Introduction to Function SIGN

    - by pinaldave
    Yesterday I received an email from a friend asking how do SIGN function works. Well SIGN Function is very fundamental function. It will return the value 1, -1 or 0. If your value is negative it will return you negative -1 and if it is positive it will return you positive +1. Let us start with a simple small example. DECLARE @IntVal1 INT, @IntVal2 INT,@IntVal3 INT DECLARE @NumVal1 DECIMAL(4,2), @NumVal2 DECIMAL(4,2),@NumVal3 DECIMAL(4,2) SET @IntVal1 = 9; SET @IntVal2 = -9; SET @IntVal3 = 0; SET @NumVal1 = 9.0; SET @NumVal2 = -9.0; SET @NumVal3 = 0.0; SELECT SIGN(@IntVal1) IntVal1,SIGN(@IntVal2) IntVal2,SIGN(@IntVal3) IntVal3 SELECT SIGN(@NumVal1) NumVal1,SIGN(@NumVal2) NumVal2,SIGN(@NumVal2) NumVal3   The above function will give us following result set. You will notice that when there is positive value the function gives positive values and if the values are negative it will return you negative values. Also you will notice that if the data type is  INT the return value is INT and when the value passed to the function is Numeric the result also matches it. Not every datatype is compatible with this function.  Here is the quick look up of the return types. bigint -> bigint int/smallint/tinyint -> int money/smallmoney -> money numeric/decimal -> numeric/decimal everybody else -> float What will be the best example of the usage of this function that you will not have to use the CASE Statement. Here is example of CASE Statement usage and the same replaced with SIGN function. USE tempdb GO CREATE TABLE TestTable (Date1 SMALLDATETIME, Date2 SMALLDATETIME) INSERT INTO TestTable (Date1, Date2) SELECT '2012-06-22 16:15', '2012-06-20 16:15' UNION ALL SELECT '2012-06-24 16:15', '2012-06-22 16:15' UNION ALL SELECT '2012-06-22 16:15', '2012-06-22 16:15' GO -- Using Case Statement SELECT CASE WHEN DATEDIFF(d,Date1,Date2) > 0 THEN 1 WHEN DATEDIFF(d,Date1,Date2) < 0 THEN -1 ELSE 0 END AS Col FROM TestTable GO -- Using SIGN Function SELECT SIGN(DATEDIFF(d,Date1,Date2)) AS Col FROM TestTable GO DROP TABLE TestTable GO This was interesting blog post for me to write. Let me know your opinion. Reference: Pinal Dave (http://blog.sqlauthority.com) Filed under: PostADay, SQL, SQL Authority, SQL Function, SQL Query, SQL Server, SQL Tips and Tricks, T SQL, Technology

    Read the article

  • How do I randomly generate a top-down 2D level with separate sections and is infinite?

    - by Bagofsheep
    I've read many other questions/answers about random level generation but most of them deal with either randomly/proceduraly generating 2D levels viewed from the side or 3D levels. What I'm trying to achieve is sort of like you were looking straight down on a Minecraft map. There is no height, but the borders of each "biome" or "section" of the map are random and varied. I already have basic code that can generate a perfectly square level with the same tileset (randomly picking segments from the tileset image), but I've encountered a major issue for wanting the level to be infinite: Beyond a certain point, the tiles' positions become negative on one or both of the axis. The code I use to only draw tiles the player can see relies on taking the tiles position and converting it to the index number that represents it in the array. As you well know, arrays cannot have a negative index. Here is some of my code: This generates the square (or rectangle) of tiles: //Scale is in tiles public void Generate(int sX, int sY) { scaleX = sX; scaleY = sY; for (int y = 0; y <= scaleY; y++) { tiles.Add(new List<Tile>()); for (int x = 0; x <= scaleX; x++) { tiles[tiles.Count - 1].Add(tileset.randomTile(x * tileset.TileSize, y * tileset.TileSize)); } } } Before I changed the code after realizing an array index couldn't be negative my for loops looked something like this to center the map around (0, 0): for (int y = -scaleY / 2; y <= scaleY / 2; y++) for (int x = -scaleX / 2; x <= scaleX / 2; x++) Here is the code that draws the tiles: int startX = (int)Math.Floor((player.Position.X - (graphics.Viewport.Width) - tileset.TileSize) / tileset.TileSize); int endX = (int)Math.Ceiling((player.Position.X + (graphics.Viewport.Width) + tileset.TileSize) / tileset.TileSize); int startY = (int)Math.Floor((player.Position.Y - (graphics.Viewport.Height) - tileset.TileSize) / tileset.TileSize); int endY = (int)Math.Ceiling((player.Position.Y + (graphics.Viewport.Height) + tileset.TileSize) / tileset.TileSize); for (int y = startY; y < endY; y++) { for (int x = startX; x < endX; x++) { if (x >= 0 && y >= 0 && x <= scaleX && y <= scaleY) tiles[y][x].Draw(spriteBatch); } } So to summarize what I'm asking: First, how do I randomly generate a top-down 2D map with different sections (not chunks per se, but areas with different tile sets) and second, how do I get past this negative array index issue?

    Read the article

  • Page Flip Flash Technology to Save the Environment

    With many more people becoming aware of the global climate change that is taking place around us, an increasing number of them are starting to understand their negative impact on the environment. Thankfully, a lot of them are taking steps to mitigate that negative impact.

    Read the article

  • A way of doing real-world test-driven development (and some thoughts about it)

    - by Thomas Weller
    Lately, I exchanged some arguments with Derick Bailey about some details of the red-green-refactor cycle of the Test-driven development process. In short, the issue revolved around the fact that it’s not enough to have a test red or green, but it’s also important to have it red or green for the right reasons. While for me, it’s sufficient to initially have a NotImplementedException in place, Derick argues that this is not totally correct (see these two posts: Red/Green/Refactor, For The Right Reasons and Red For The Right Reason: Fail By Assertion, Not By Anything Else). And he’s right. But on the other hand, I had no idea how his insights could have any practical consequence for my own individual interpretation of the red-green-refactor cycle (which is not really red-green-refactor, at least not in its pure sense, see the rest of this article). This made me think deeply for some days now. In the end I found out that the ‘right reason’ changes in my understanding depending on what development phase I’m in. To make this clear (at least I hope it becomes clear…) I started to describe my way of working in some detail, and then something strange happened: The scope of the article slightly shifted from focusing ‘only’ on the ‘right reason’ issue to something more general, which you might describe as something like  'Doing real-world TDD in .NET , with massive use of third-party add-ins’. This is because I feel that there is a more general statement about Test-driven development to make:  It’s high time to speak about the ‘How’ of TDD, not always only the ‘Why’. Much has been said about this, and me myself also contributed to that (see here: TDD is not about testing, it's about how we develop software). But always justifying what you do is very unsatisfying in the long run, it is inherently defensive, and it costs time and effort that could be used for better and more important things. And frankly: I’m somewhat sick and tired of repeating time and again that the test-driven way of software development is highly preferable for many reasons - I don’t want to spent my time exclusively on stating the obvious… So, again, let’s say it clearly: TDD is programming, and programming is TDD. Other ways of programming (code-first, sometimes called cowboy-coding) are exceptional and need justification. – I know that there are many people out there who will disagree with this radical statement, and I also know that it’s not a description of the real world but more of a mission statement or something. But nevertheless I’m absolutely sure that in some years this statement will be nothing but a platitude. Side note: Some parts of this post read as if I were paid by Jetbrains (the manufacturer of the ReSharper add-in – R#), but I swear I’m not. Rather I think that Visual Studio is just not production-complete without it, and I wouldn’t even consider to do professional work without having this add-in installed... The three parts of a software component Before I go into some details, I first should describe my understanding of what belongs to a software component (assembly, type, or method) during the production process (i.e. the coding phase). Roughly, I come up with the three parts shown below:   First, we need to have some initial sort of requirement. This can be a multi-page formal document, a vague idea in some programmer’s brain of what might be needed, or anything in between. In either way, there has to be some sort of requirement, be it explicit or not. – At the C# micro-level, the best way that I found to formulate that is to define interfaces for just about everything, even for internal classes, and to provide them with exhaustive xml comments. The next step then is to re-formulate these requirements in an executable form. This is specific to the respective programming language. - For C#/.NET, the Gallio framework (which includes MbUnit) in conjunction with the ReSharper add-in for Visual Studio is my toolset of choice. The third part then finally is the production code itself. It’s development is entirely driven by the requirements and their executable formulation. This is the delivery, the two other parts are ‘only’ there to make its production possible, to give it a decent quality and reliability, and to significantly reduce related costs down the maintenance timeline. So while the first two parts are not really relevant for the customer, they are very important for the developer. The customer (or in Scrum terms: the Product Owner) is not interested at all in how  the product is developed, he is only interested in the fact that it is developed as cost-effective as possible, and that it meets his functional and non-functional requirements. The rest is solely a matter of the developer’s craftsmanship, and this is what I want to talk about during the remainder of this article… An example To demonstrate my way of doing real-world TDD, I decided to show the development of a (very) simple Calculator component. The example is deliberately trivial and silly, as examples always are. I am totally aware of the fact that real life is never that simple, but I only want to show some development principles here… The requirement As already said above, I start with writing down some words on the initial requirement, and I normally use interfaces for that, even for internal classes - the typical question “intf or not” doesn’t even come to mind. I need them for my usual workflow and using them automatically produces high componentized and testable code anyway. To think about their usage in every single situation would slow down the production process unnecessarily. So this is what I begin with: namespace Calculator {     /// <summary>     /// Defines a very simple calculator component for demo purposes.     /// </summary>     public interface ICalculator     {         /// <summary>         /// Gets the result of the last successful operation.         /// </summary>         /// <value>The last result.</value>         /// <remarks>         /// Will be <see langword="null" /> before the first successful operation.         /// </remarks>         double? LastResult { get; }       } // interface ICalculator   } // namespace Calculator So, I’m not beginning with a test, but with a sort of code declaration - and still I insist on being 100% test-driven. There are three important things here: Starting this way gives me a method signature, which allows to use IntelliSense and AutoCompletion and thus eliminates the danger of typos - one of the most regular, annoying, time-consuming, and therefore expensive sources of error in the development process. In my understanding, the interface definition as a whole is more of a readable requirement document and technical documentation than anything else. So this is at least as much about documentation than about coding. The documentation must completely describe the behavior of the documented element. I normally use an IoC container or some sort of self-written provider-like model in my architecture. In either case, I need my components defined via service interfaces anyway. - I will use the LinFu IoC framework here, for no other reason as that is is very simple to use. The ‘Red’ (pt. 1)   First I create a folder for the project’s third-party libraries and put the LinFu.Core dll there. Then I set up a test project (via a Gallio project template), and add references to the Calculator project and the LinFu dll. Finally I’m ready to write the first test, which will look like the following: namespace Calculator.Test {     [TestFixture]     public class CalculatorTest     {         private readonly ServiceContainer container = new ServiceContainer();           [Test]         public void CalculatorLastResultIsInitiallyNull()         {             ICalculator calculator = container.GetService<ICalculator>();               Assert.IsNull(calculator.LastResult);         }       } // class CalculatorTest   } // namespace Calculator.Test       This is basically the executable formulation of what the interface definition states (part of). Side note: There’s one principle of TDD that is just plain wrong in my eyes: I’m talking about the Red is 'does not compile' thing. How could a compiler error ever be interpreted as a valid test outcome? I never understood that, it just makes no sense to me. (Or, in Derick’s terms: this reason is as wrong as a reason ever could be…) A compiler error tells me: Your code is incorrect, but nothing more.  Instead, the ‘Red’ part of the red-green-refactor cycle has a clearly defined meaning to me: It means that the test works as intended and fails only if its assumptions are not met for some reason. Back to our Calculator. When I execute the above test with R#, the Gallio plugin will give me this output: So this tells me that the test is red for the wrong reason: There’s no implementation that the IoC-container could load, of course. So let’s fix that. With R#, this is very easy: First, create an ICalculator - derived type:        Next, implement the interface members: And finally, move the new class to its own file: So far my ‘work’ was six mouse clicks long, the only thing that’s left to do manually here, is to add the Ioc-specific wiring-declaration and also to make the respective class non-public, which I regularly do to force my components to communicate exclusively via interfaces: This is what my Calculator class looks like as of now: using System; using LinFu.IoC.Configuration;   namespace Calculator {     [Implements(typeof(ICalculator))]     internal class Calculator : ICalculator     {         public double? LastResult         {             get             {                 throw new NotImplementedException();             }         }     } } Back to the test fixture, we have to put our IoC container to work: [TestFixture] public class CalculatorTest {     #region Fields       private readonly ServiceContainer container = new ServiceContainer();       #endregion // Fields       #region Setup/TearDown       [FixtureSetUp]     public void FixtureSetUp()     {        container.LoadFrom(AppDomain.CurrentDomain.BaseDirectory, "Calculator.dll");     }       ... Because I have a R# live template defined for the setup/teardown method skeleton as well, the only manual coding here again is the IoC-specific stuff: two lines, not more… The ‘Red’ (pt. 2) Now, the execution of the above test gives the following result: This time, the test outcome tells me that the method under test is called. And this is the point, where Derick and I seem to have somewhat different views on the subject: Of course, the test still is worthless regarding the red/green outcome (or: it’s still red for the wrong reasons, in that it gives a false negative). But as far as I am concerned, I’m not really interested in the test outcome at this point of the red-green-refactor cycle. Rather, I only want to assert that my test actually calls the right method. If that’s the case, I will happily go on to the ‘Green’ part… The ‘Green’ Making the test green is quite trivial. Just make LastResult an automatic property:     [Implements(typeof(ICalculator))]     internal class Calculator : ICalculator     {         public double? LastResult { get; private set; }     }         One more round… Now on to something slightly more demanding (cough…). Let’s state that our Calculator exposes an Add() method:         ...   /// <summary>         /// Adds the specified operands.         /// </summary>         /// <param name="operand1">The operand1.</param>         /// <param name="operand2">The operand2.</param>         /// <returns>The result of the additon.</returns>         /// <exception cref="ArgumentException">         /// Argument <paramref name="operand1"/> is &lt; 0.<br/>         /// -- or --<br/>         /// Argument <paramref name="operand2"/> is &lt; 0.         /// </exception>         double Add(double operand1, double operand2);       } // interface ICalculator A remark: I sometimes hear the complaint that xml comment stuff like the above is hard to read. That’s certainly true, but irrelevant to me, because I read xml code comments with the CR_Documentor tool window. And using that, it looks like this:   Apart from that, I’m heavily using xml code comments (see e.g. here for a detailed guide) because there is the possibility of automating help generation with nightly CI builds (using MS Sandcastle and the Sandcastle Help File Builder), and then publishing the results to some intranet location.  This way, a team always has first class, up-to-date technical documentation at hand about the current codebase. (And, also very important for speeding up things and avoiding typos: You have IntelliSense/AutoCompletion and R# support, and the comments are subject to compiler checking…).     Back to our Calculator again: Two more R# – clicks implement the Add() skeleton:         ...           public double Add(double operand1, double operand2)         {             throw new NotImplementedException();         }       } // class Calculator As we have stated in the interface definition (which actually serves as our requirement document!), the operands are not allowed to be negative. So let’s start implementing that. Here’s the test: [Test] [Row(-0.5, 2)] public void AddThrowsOnNegativeOperands(double operand1, double operand2) {     ICalculator calculator = container.GetService<ICalculator>();       Assert.Throws<ArgumentException>(() => calculator.Add(operand1, operand2)); } As you can see, I’m using a data-driven unit test method here, mainly for these two reasons: Because I know that I will have to do the same test for the second operand in a few seconds, I save myself from implementing another test method for this purpose. Rather, I only will have to add another Row attribute to the existing one. From the test report below, you can see that the argument values are explicitly printed out. This can be a valuable documentation feature even when everything is green: One can quickly review what values were tested exactly - the complete Gallio HTML-report (as it will be produced by the Continuous Integration runs) shows these values in a quite clear format (see below for an example). Back to our Calculator development again, this is what the test result tells us at the moment: So we’re red again, because there is not yet an implementation… Next we go on and implement the necessary parameter verification to become green again, and then we do the same thing for the second operand. To make a long story short, here’s the test and the method implementation at the end of the second cycle: // in CalculatorTest:   [Test] [Row(-0.5, 2)] [Row(295, -123)] public void AddThrowsOnNegativeOperands(double operand1, double operand2) {     ICalculator calculator = container.GetService<ICalculator>();       Assert.Throws<ArgumentException>(() => calculator.Add(operand1, operand2)); }   // in Calculator: public double Add(double operand1, double operand2) {     if (operand1 < 0.0)     {         throw new ArgumentException("Value must not be negative.", "operand1");     }     if (operand2 < 0.0)     {         throw new ArgumentException("Value must not be negative.", "operand2");     }     throw new NotImplementedException(); } So far, we have sheltered our method from unwanted input, and now we can safely operate on the parameters without further caring about their validity (this is my interpretation of the Fail Fast principle, which is regarded here in more detail). Now we can think about the method’s successful outcomes. First let’s write another test for that: [Test] [Row(1, 1, 2)] public void TestAdd(double operand1, double operand2, double expectedResult) {     ICalculator calculator = container.GetService<ICalculator>();       double result = calculator.Add(operand1, operand2);       Assert.AreEqual(expectedResult, result); } Again, I’m regularly using row based test methods for these kinds of unit tests. The above shown pattern proved to be extremely helpful for my development work, I call it the Defined-Input/Expected-Output test idiom: You define your input arguments together with the expected method result. There are two major benefits from that way of testing: In the course of refining a method, it’s very likely to come up with additional test cases. In our case, we might add tests for some edge cases like ‘one of the operands is zero’ or ‘the sum of the two operands causes an overflow’, or maybe there’s an external test protocol that has to be fulfilled (e.g. an ISO norm for medical software), and this results in the need of testing against additional values. In all these scenarios we only have to add another Row attribute to the test. Remember that the argument values are written to the test report, so as a side-effect this produces valuable documentation. (This can become especially important if the fulfillment of some sort of external requirements has to be proven). So your test method might look something like that in the end: [Test, Description("Arguments: operand1, operand2, expectedResult")] [Row(1, 1, 2)] [Row(0, 999999999, 999999999)] [Row(0, 0, 0)] [Row(0, double.MaxValue, double.MaxValue)] [Row(4, double.MaxValue - 2.5, double.MaxValue)] public void TestAdd(double operand1, double operand2, double expectedResult) {     ICalculator calculator = container.GetService<ICalculator>();       double result = calculator.Add(operand1, operand2);       Assert.AreEqual(expectedResult, result); } And this will produce the following HTML report (with Gallio):   Not bad for the amount of work we invested in it, huh? - There might be scenarios where reports like that can be useful for demonstration purposes during a Scrum sprint review… The last requirement to fulfill is that the LastResult property is expected to store the result of the last operation. I don’t show this here, it’s trivial enough and brings nothing new… And finally: Refactor (for the right reasons) To demonstrate my way of going through the refactoring portion of the red-green-refactor cycle, I added another method to our Calculator component, namely Subtract(). Here’s the code (tests and production): // CalculatorTest.cs:   [Test, Description("Arguments: operand1, operand2, expectedResult")] [Row(1, 1, 0)] [Row(0, 999999999, -999999999)] [Row(0, 0, 0)] [Row(0, double.MaxValue, -double.MaxValue)] [Row(4, double.MaxValue - 2.5, -double.MaxValue)] public void TestSubtract(double operand1, double operand2, double expectedResult) {     ICalculator calculator = container.GetService<ICalculator>();       double result = calculator.Subtract(operand1, operand2);       Assert.AreEqual(expectedResult, result); }   [Test, Description("Arguments: operand1, operand2, expectedResult")] [Row(1, 1, 0)] [Row(0, 999999999, -999999999)] [Row(0, 0, 0)] [Row(0, double.MaxValue, -double.MaxValue)] [Row(4, double.MaxValue - 2.5, -double.MaxValue)] public void TestSubtractGivesExpectedLastResult(double operand1, double operand2, double expectedResult) {     ICalculator calculator = container.GetService<ICalculator>();       calculator.Subtract(operand1, operand2);       Assert.AreEqual(expectedResult, calculator.LastResult); }   ...   // ICalculator.cs: /// <summary> /// Subtracts the specified operands. /// </summary> /// <param name="operand1">The operand1.</param> /// <param name="operand2">The operand2.</param> /// <returns>The result of the subtraction.</returns> /// <exception cref="ArgumentException"> /// Argument <paramref name="operand1"/> is &lt; 0.<br/> /// -- or --<br/> /// Argument <paramref name="operand2"/> is &lt; 0. /// </exception> double Subtract(double operand1, double operand2);   ...   // Calculator.cs:   public double Subtract(double operand1, double operand2) {     if (operand1 < 0.0)     {         throw new ArgumentException("Value must not be negative.", "operand1");     }       if (operand2 < 0.0)     {         throw new ArgumentException("Value must not be negative.", "operand2");     }       return (this.LastResult = operand1 - operand2).Value; }   Obviously, the argument validation stuff that was produced during the red-green part of our cycle duplicates the code from the previous Add() method. So, to avoid code duplication and minimize the number of code lines of the production code, we do an Extract Method refactoring. One more time, this is only a matter of a few mouse clicks (and giving the new method a name) with R#: Having done that, our production code finally looks like that: using System; using LinFu.IoC.Configuration;   namespace Calculator {     [Implements(typeof(ICalculator))]     internal class Calculator : ICalculator     {         #region ICalculator           public double? LastResult { get; private set; }           public double Add(double operand1, double operand2)         {             ThrowIfOneOperandIsInvalid(operand1, operand2);               return (this.LastResult = operand1 + operand2).Value;         }           public double Subtract(double operand1, double operand2)         {             ThrowIfOneOperandIsInvalid(operand1, operand2);               return (this.LastResult = operand1 - operand2).Value;         }           #endregion // ICalculator           #region Implementation (Helper)           private static void ThrowIfOneOperandIsInvalid(double operand1, double operand2)         {             if (operand1 < 0.0)             {                 throw new ArgumentException("Value must not be negative.", "operand1");             }               if (operand2 < 0.0)             {                 throw new ArgumentException("Value must not be negative.", "operand2");             }         }           #endregion // Implementation (Helper)       } // class Calculator   } // namespace Calculator But is the above worth the effort at all? It’s obviously trivial and not very impressive. All our tests were green (for the right reasons), and refactoring the code did not change anything. It’s not immediately clear how this refactoring work adds value to the project. Derick puts it like this: STOP! Hold on a second… before you go any further and before you even think about refactoring what you just wrote to make your test pass, you need to understand something: if your done with your requirements after making the test green, you are not required to refactor the code. I know… I’m speaking heresy, here. Toss me to the wolves, I’ve gone over to the dark side! Seriously, though… if your test is passing for the right reasons, and you do not need to write any test or any more code for you class at this point, what value does refactoring add? Derick immediately answers his own question: So why should you follow the refactor portion of red/green/refactor? When you have added code that makes the system less readable, less understandable, less expressive of the domain or concern’s intentions, less architecturally sound, less DRY, etc, then you should refactor it. I couldn’t state it more precise. From my personal perspective, I’d add the following: You have to keep in mind that real-world software systems are usually quite large and there are dozens or even hundreds of occasions where micro-refactorings like the above can be applied. It’s the sum of them all that counts. And to have a good overall quality of the system (e.g. in terms of the Code Duplication Percentage metric) you have to be pedantic on the individual, seemingly trivial cases. My job regularly requires the reading and understanding of ‘foreign’ code. So code quality/readability really makes a HUGE difference for me – sometimes it can be even the difference between project success and failure… Conclusions The above described development process emerged over the years, and there were mainly two things that guided its evolution (you might call it eternal principles, personal beliefs, or anything in between): Test-driven development is the normal, natural way of writing software, code-first is exceptional. So ‘doing TDD or not’ is not a question. And good, stable code can only reliably be produced by doing TDD (yes, I know: many will strongly disagree here again, but I’ve never seen high-quality code – and high-quality code is code that stood the test of time and causes low maintenance costs – that was produced code-first…) It’s the production code that pays our bills in the end. (Though I have seen customers these days who demand an acceptance test battery as part of the final delivery. Things seem to go into the right direction…). The test code serves ‘only’ to make the production code work. But it’s the number of delivered features which solely counts at the end of the day - no matter how much test code you wrote or how good it is. With these two things in mind, I tried to optimize my coding process for coding speed – or, in business terms: productivity - without sacrificing the principles of TDD (more than I’d do either way…).  As a result, I consider a ratio of about 3-5/1 for test code vs. production code as normal and desirable. In other words: roughly 60-80% of my code is test code (This might sound heavy, but that is mainly due to the fact that software development standards only begin to evolve. The entire software development profession is very young, historically seen; only at the very beginning, and there are no viable standards yet. If you think about software development as a kind of casting process, where the test code is the mold and the resulting production code is the final product, then the above ratio sounds no longer extraordinary…) Although the above might look like very much unnecessary work at first sight, it’s not. With the aid of the mentioned add-ins, doing all the above is a matter of minutes, sometimes seconds (while writing this post took hours and days…). The most important thing is to have the right tools at hand. Slow developer machines or the lack of a tool or something like that - for ‘saving’ a few 100 bucks -  is just not acceptable and a very bad decision in business terms (though I quite some times have seen and heard that…). Production of high-quality products needs the usage of high-quality tools. This is a platitude that every craftsman knows… The here described round-trip will take me about five to ten minutes in my real-world development practice. I guess it’s about 30% more time compared to developing the ‘traditional’ (code-first) way. But the so manufactured ‘product’ is of much higher quality and massively reduces maintenance costs, which is by far the single biggest cost factor, as I showed in this previous post: It's the maintenance, stupid! (or: Something is rotten in developerland.). In the end, this is a highly cost-effective way of software development… But on the other hand, there clearly is a trade-off here: coding speed vs. code quality/later maintenance costs. The here described development method might be a perfect fit for the overwhelming majority of software projects, but there certainly are some scenarios where it’s not - e.g. if time-to-market is crucial for a software project. So this is a business decision in the end. It’s just that you have to know what you’re doing and what consequences this might have… Some last words First, I’d like to thank Derick Bailey again. His two aforementioned posts (which I strongly recommend for reading) inspired me to think deeply about my own personal way of doing TDD and to clarify my thoughts about it. I wouldn’t have done that without this inspiration. I really enjoy that kind of discussions… I agree with him in all respects. But I don’t know (yet?) how to bring his insights into the described production process without slowing things down. The above described method proved to be very “good enough” in my practical experience. But of course, I’m open to suggestions here… My rationale for now is: If the test is initially red during the red-green-refactor cycle, the ‘right reason’ is: it actually calls the right method, but this method is not yet operational. Later on, when the cycle is finished and the tests become part of the regular, automated Continuous Integration process, ‘red’ certainly must occur for the ‘right reason’: in this phase, ‘red’ MUST mean nothing but an unfulfilled assertion - Fail By Assertion, Not By Anything Else!

    Read the article

  • How do i have 4GB of video memory with a 1GB video card?

    - by Tomas Spc Yaczik
    I ran the direct X diagnostic tool to take a look at my graphics capabilities and its telling me that the approximate video memory is clocked in at 4096MB. That doesn't make any sense, how is that possible? The only things that i can think of were that DirectX was inaccurate so i looked at the graphics statistics of my computer on CPU-Z which was included with the motherboard and that's telling me i have "negative" 1988MB. Not only is that not 4096MB, but its giving me a negative number and i know for a fact that you can't have a negative amount of memory???!!! The only things i can think of that would be amplifying my video memory output is the PCIe 3.0 bus, or that the motherboard is somehow including the on board video chip set with the video card which only then is only 2GB of video memory, which still has to be being amplified by something. Any suggestions?

    Read the article

  • SEO impact on subdomain for full name and obscure ccTLD

    - by Dan Christian
    There have been a few questions on subdomains and their impact on SEO, mostly in comparison to subfolders. The closest question I've found is this question but it still doesn't completely answer my query. I'm setting up a blog for 'Sam Smith'. It's imperative the SEO is based around his full name as he is a prominent blogger and his name is his value. All ccTLD variations of 'samsmith' (samsmith.com, samsmith.cc etc) are taken. However there has been the opportunity to register an obscure ccTLD for 'smith'. In regards to SEO value purely from the URL... 1) Will there be any negative SEO implications on searches for 'Sam Smith' when setting up the subdomain as 'sam.smith.' compared to a more regular 'samsmith.' domain? Will a search engine recognise the subdomain as the full name as oppose to just 'smith'? 2) Are there any negative SEO implications with an obscure ccTLD. For instance if Sam Smith was a prominent blogger in Canada with most of his audience based there, would there be any negative SEO if he had, for example, a .co ccTLD.

    Read the article

  • Algorithm to shift the car

    - by Simran kaur
    I have a track that can be divided into n number of tracks and a car as GamObject. The track has transforms such that some part of the track's width lies in negative x axis and other in positive. Requirement: One move should cross one track. On every move(left or right), I want the car to reach exact centre of the next track on either sides i.e left or right. My code: Problem: : Because of negative values , somewhere I am missing out something that is making car move not in desirable positions and that's because of negative values only. variable tracks is the number of tracks the whole track is divided in. variable dist is the total width of the complete track. On left movement: if (Input.GetKeyDown (KeyCode.LeftArrow)) { if (this.transform.position.x < r.renderer.bounds.min.x + box.size.x) { this.transform.position = new Vector3 (r.renderer.bounds.min.x + Mathf.FloorToInt(box.size.x), this.transform.position.y, this.transform.position.z); } else { int tracknumber = Mathf.RoundToInt(dist - transform.position.x)/tracks; float averagedistance = (tracknumber*(dist/tracks) + (tracknumber-1)*(dist/tracks))/2; if(transform.position.x > averagedistoftracks) { amountofmovement = amountofmovement + (transform.position.x - averagedistance); } else { amountofmovement = amountofmovement - (averagedistance - transform.position.x); } this.transform.position = new Vector3 (this.transform.position.x - amountofmovement, this.transform.position.y, this.transform.position.z); } }

    Read the article

  • DataRelation Insert and ForeignKey

    - by Steve
    Guys, I have a winforms application with two DataGridViews displaying a master-detail relationship from my Person and Address tables. Person table has a PersonID field that is auto-incrementing primary key. Address has a PersonID field that is the FK. I fill my DataTables with DataAdapter and set Person.PersonID column's AutoIncrement=true and AutoIncrementStep=-1. I can insert records in the Person DataTable from the DataGridView. The PersonID column displays unique negative values for PersonID. I update the database by calling DataAdapter.Update(PersonTable) and the negative PersonIDs are converted to positive unique values automatically by SQL Server. Here's the rub. The Address DataGridView show the address table which has a DataRelation to Person by PersonID. Inserted Person records have the temporary negative PersonID. I can now insert records into Address via DataGridView and Address.PersonID is set to the negative value from the DataRelation mapping. I call Adapter.Update(AddressTable) and the negative PersonIDs go into the Address table breaking the relationship. How do you guys handle primary/foreign keys using DataTables and master-detail DataGridViews? Thanks! Steve EDIT: After more googling, I found that SqlDataAdapter.RowUpdated event gives me what I need. I create a new command to query the last id inserted by using @@IDENTITY. It works pretty well. The DataRelation updates the Address.PersonID field for me so it's required to Update the Person table first then update the Address table. All the new records insert properly with correct ids in place! Adapter = new SqlDataAdapter(cmd); Adapter.RowUpdated += (s, e) => { if (e.StatementType != StatementType.Insert) return; //set the id for the inserted record SqlCommand c = e.Command.Connection.CreateCommand(); c.CommandText = "select @@IDENTITY id"; e.Row[0] = Convert.ToInt32( c.ExecuteScalar() ); }; Adapter.Fill(this); SqlCommandBuilder sb = new SqlCommandBuilder(Adapter); sb.GetDeleteCommand(); sb.GetUpdateCommand(); sb.GetInsertCommand(); this.Columns[0].AutoIncrement = true; this.Columns[0].AutoIncrementSeed = -1; this.Columns[0].AutoIncrementStep = -1;

    Read the article

  • Flex bug?? Get messed up stacked ColumnChart with type="100%"

    - by Nir
    I am trying to do a stacked Column chart with type="100%" and a mixture of positive and negative values. When all the values are positive, is functions well, but when negative numbers come to the game, it looks totally messed up. When I also look at Adobe documentation (look here), I see the following code for stacked column chart involving negative numbers: <?xml version="1.0"?> <!-- charts/StackedNegative.mxml --> <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"> <mx:Script><![CDATA[ import mx.collections.ArrayCollection; [Bindable] public var expenses:ArrayCollection = new ArrayCollection([ {Month:"Jan", Profit:-2000, Expenses:-1500}, {Month:"Feb", Profit:1000, Expenses:-200}, {Month:"Mar", Profit:1500, Expenses:-500} ]); ]]></mx:Script> <mx:Panel title="Column Chart"> <mx:ColumnChart id="myChart" dataProvider="{expenses}" showDataTips="true"> <mx:horizontalAxis> <mx:CategoryAxis dataProvider="{expenses}" categoryField="Month" /> </mx:horizontalAxis> <mx:series> <mx:ColumnSet type="stacked" allowNegativeForStacked="true"> <mx:series> <mx:ColumnSeries xField="Month" yField="Profit" displayName="Profit" /> <mx:ColumnSeries xField="Month" yField="Expenses" displayName="Expenses" /> </mx:series> </mx:ColumnSet> </mx:series> </mx:ColumnChart> <mx:Legend dataProvider="{myChart}"/> </mx:Panel> </mx:Application> It works fine. But try to change: <mx:ColumnSet type="stacked" allowNegativeForStacked="true"> to: <mx:ColumnSet type="100%" allowNegativeForStacked="true"> and you'll see that it doesn't on January data, where both values are negative, the chart shows as if they are positive, and on the other two where one value is positive and the other is negative, it shows only the positive part as 100%... Isn't it a Flex Bug? I have my own case with such data and it behaves wrong the same way. I'd expect that if it has 800 stacked on -200, it will show 80% up and 20% down, totalling 100%. BTW: Using Flex 4, though these are all mx components. Thanks a lot and regards from Berlin, Germany, Nir.

    Read the article

  • Am I right about the differences between Floyd-Warshall, Dijkstra's and Bellman-Ford algorithms?

    - by Programming Noob
    I've been studying the three and I'm stating my inferences from them below. Could someone tell me if I have understood them accurately enough or not? Thank you. Dijkstra's algorithm is used only when you have a single source and you want to know the smallest path from one node to another, but fails in cases like this Floyd-Warshall's algorithm is used when any of all the nodes can be a source, so you want the shortest distance to reach any destination node from any source node. This only fails when there are negative cycles (this is the most important one. I mean, this is the one I'm least sure about:) 3.Bellman-Ford is used like Dijkstra's, when there is only one source. This can handle negative weights and its working is the same as Floyd-Warshall's except for one source, right? If you need to have a look, the corresponding algorithms are (courtesy Wikipedia): Bellman-Ford: procedure BellmanFord(list vertices, list edges, vertex source) // This implementation takes in a graph, represented as lists of vertices // and edges, and modifies the vertices so that their distance and // predecessor attributes store the shortest paths. // Step 1: initialize graph for each vertex v in vertices: if v is source then v.distance := 0 else v.distance := infinity v.predecessor := null // Step 2: relax edges repeatedly for i from 1 to size(vertices)-1: for each edge uv in edges: // uv is the edge from u to v u := uv.source v := uv.destination if u.distance + uv.weight < v.distance: v.distance := u.distance + uv.weight v.predecessor := u // Step 3: check for negative-weight cycles for each edge uv in edges: u := uv.source v := uv.destination if u.distance + uv.weight < v.distance: error "Graph contains a negative-weight cycle" Dijkstra: 1 function Dijkstra(Graph, source): 2 for each vertex v in Graph: // Initializations 3 dist[v] := infinity ; // Unknown distance function from 4 // source to v 5 previous[v] := undefined ; // Previous node in optimal path 6 // from source 7 8 dist[source] := 0 ; // Distance from source to source 9 Q := the set of all nodes in Graph ; // All nodes in the graph are 10 // unoptimized - thus are in Q 11 while Q is not empty: // The main loop 12 u := vertex in Q with smallest distance in dist[] ; // Start node in first case 13 if dist[u] = infinity: 14 break ; // all remaining vertices are 15 // inaccessible from source 16 17 remove u from Q ; 18 for each neighbor v of u: // where v has not yet been 19 removed from Q. 20 alt := dist[u] + dist_between(u, v) ; 21 if alt < dist[v]: // Relax (u,v,a) 22 dist[v] := alt ; 23 previous[v] := u ; 24 decrease-key v in Q; // Reorder v in the Queue 25 return dist; Floyd-Warshall: 1 /* Assume a function edgeCost(i,j) which returns the cost of the edge from i to j 2 (infinity if there is none). 3 Also assume that n is the number of vertices and edgeCost(i,i) = 0 4 */ 5 6 int path[][]; 7 /* A 2-dimensional matrix. At each step in the algorithm, path[i][j] is the shortest path 8 from i to j using intermediate vertices (1..k-1). Each path[i][j] is initialized to 9 edgeCost(i,j). 10 */ 11 12 procedure FloydWarshall () 13 for k := 1 to n 14 for i := 1 to n 15 for j := 1 to n 16 path[i][j] = min ( path[i][j], path[i][k]+path[k][j] );

    Read the article

  • Increasing touch surface (#wp7dev)

    - by Laurent Bugnion
    When you design for Windows Phone 7 (or for any touch device, for that matter, and most especially small screens), you need to be very careful to give enough surface to your users’ fingers. It is easy to miss a touch on such small screens, and that can be horrifyingly frustrating. This is especially true when people are on the move, and trying to hit the control while walking and holding their device in one hand, or when the device is mounted in a car and vibrating with the engine. In my experience, a touch surface should be ideally minimum 60x60 pixels to be easy to activate on the Windows Phone 7 screen (which is, as we know, 800 pixels x 480 pixels). Ideally, I try to make my touch surfaces 80x80 pixels minimum. This causes a few design challenges of course. Using transparent backgrounds However, one thing is helping us tremendously: some surfaces can be made transparent, and yet react to touch. The secret is the following: If you have a panel that has a Null background (i.e. the Background is not set at all), then the empty surface does not react to touch. If however the Background is set to the Transparent color (or any color where the Alpha channel is set to 0), then it will react to touch. Setting a transparent background is easy. For example: <Grid Background="#00000000"> </Grid> or <Grid Background="Transparent"> </Grid> In C#: var grid = new Grid { Background = new SolidColorBrush( Colors.Transparent) }; Using negative margins Having a transparent background reactive to touch is a good start, but in addition, you must make sure that the surface is big enough for my clumsy fingers. One way to achieve that is to increase the transparent, touch-reactive surface, and reposition the element using negative margins. For example, consider the following UI. I changed the transparent background of the HyperlinkButton to Red, in order to visualize the touch surface. In this figure, the Settings HyperlinkButton is 105 pixels x 31 pixels. This is wide enough, but really small in height and easy to miss. To improve this, we can use negative margins, for instance: <HyperlinkButton Content="Settings" HorizontalAlignment="Right" VerticalAlignment="Bottom" Height="60" Margin="0,0,0,-15" /> Notice the usage of negative bottom margin to bring the HyperlinkButton back at the bottom of the main Grid’s first row, where it belongs. And the result is: Notice how the touch surface is much bigger than before. This makes the HyperlinkButton easier to reach, and improves the user experience. With the background set back to normal, the UI looks exactly the same, as it should: In summary: Remember to maximize the touch surface for your controls. Plan your design in consequence by reserving enough room around each control to allow their hit surface to be expanded as shown in this article. Do not cram too many controls in one page. If REALLY needed, use an additional page (or even better: use a Pivot control with multiple pivot items) for the controls that don’t fit on the first one. This should ensure a smoother user experience and improved touch behavior. Happy coding! Laurent   Laurent Bugnion (GalaSoft) Subscribe | Twitter | Facebook | Flickr | LinkedIn

    Read the article

  • dns queries not using nscd for caching

    - by xenoterracide
    I'm trying to use nscd (Nameservices Cache Daemon) to cache dns locally so I can stop using bind to do it. I've gotten it started and ntpd seems to attempt to use it. But everything else for hosts seems to ignore it. e.g if I do dig apache.org 3 times none of them will hit the cache. I'm viewing the cache stats using nscd -g to determine whether it's been used. I've also turned the debug log level up to see if I can see it hitting and the queries don't even hit nscd. nsswitch.conf # Begin /etc/nsswitch.conf passwd: files group: files shadow: files publickey: files hosts: cache files dns networks: files protocols: files services: files ethers: files rpc: files netgroup: files # End /etc/nsswitch.confenter code here nscd.conf # # /etc/nscd.conf # # An example Name Service Cache config file. This file is needed by nscd. # # Legal entries are: # # logfile <file> # debug-level <level> # threads <initial #threads to use> # max-threads <maximum #threads to use> # server-user <user to run server as instead of root> # server-user is ignored if nscd is started with -S parameters # stat-user <user who is allowed to request statistics> # reload-count unlimited|<number> # paranoia <yes|no> # restart-interval <time in seconds> # # enable-cache <service> <yes|no> # positive-time-to-live <service> <time in seconds> # negative-time-to-live <service> <time in seconds> # suggested-size <service> <prime number> # check-files <service> <yes|no> # persistent <service> <yes|no> # shared <service> <yes|no> # max-db-size <service> <number bytes> # auto-propagate <service> <yes|no> # # Currently supported cache names (services): passwd, group, hosts, services # logfile /var/log/nscd.log threads 4 max-threads 32 server-user nobody # stat-user somebody debug-level 9 # reload-count 5 paranoia no # restart-interval 3600 enable-cache passwd yes positive-time-to-live passwd 600 negative-time-to-live passwd 20 suggested-size passwd 211 check-files passwd yes persistent passwd yes shared passwd yes max-db-size passwd 33554432 auto-propagate passwd yes enable-cache group yes positive-time-to-live group 3600 negative-time-to-live group 60 suggested-size group 211 check-files group yes persistent group yes shared group yes max-db-size group 33554432 auto-propagate group yes enable-cache hosts yes positive-time-to-live hosts 3600 negative-time-to-live hosts 20 suggested-size hosts 211 check-files hosts yes persistent hosts yes shared hosts yes max-db-size hosts 33554432 enable-cache services yes positive-time-to-live services 28800 negative-time-to-live services 20 suggested-size services 211 check-files services yes persistent services yes shared services yes max-db-size services 33554432 resolv.conf # Generated by dhcpcd from eth0 nameserver 127.0.0.1 domain westell.com nameserver 192.168.1.1 nameserver 208.67.222.222 nameserver 208.67.220.220 as kind of a side note I'm using archlinux.

    Read the article

  • dns queries not using nscd for caching

    - by xenoterracide
    I'm trying to use nscd (Nameservices Cache Daemon) to cache dns locally so I can stop using bind to do it. I've gotten it started and ntpd seems to attempt to use it. But everything else for hosts seems to ignore it. e.g if I do dig apache.org 3 times none of them will hit the cache. I'm viewing the cache stats using nscd -g to determine whether it's been used. I've also turned the debug log level up to see if I can see it hitting and the queries don't even hit nscd. nsswitch.conf # Begin /etc/nsswitch.conf passwd: files group: files shadow: files publickey: files hosts: cache files dns networks: files protocols: files services: files ethers: files rpc: files netgroup: files # End /etc/nsswitch.confenter code here nscd.conf # # /etc/nscd.conf # # An example Name Service Cache config file. This file is needed by nscd. # # Legal entries are: # # logfile <file> # debug-level <level> # threads <initial #threads to use> # max-threads <maximum #threads to use> # server-user <user to run server as instead of root> # server-user is ignored if nscd is started with -S parameters # stat-user <user who is allowed to request statistics> # reload-count unlimited|<number> # paranoia <yes|no> # restart-interval <time in seconds> # # enable-cache <service> <yes|no> # positive-time-to-live <service> <time in seconds> # negative-time-to-live <service> <time in seconds> # suggested-size <service> <prime number> # check-files <service> <yes|no> # persistent <service> <yes|no> # shared <service> <yes|no> # max-db-size <service> <number bytes> # auto-propagate <service> <yes|no> # # Currently supported cache names (services): passwd, group, hosts, services # logfile /var/log/nscd.log threads 4 max-threads 32 server-user nobody # stat-user somebody debug-level 9 # reload-count 5 paranoia no # restart-interval 3600 enable-cache passwd yes positive-time-to-live passwd 600 negative-time-to-live passwd 20 suggested-size passwd 211 check-files passwd yes persistent passwd yes shared passwd yes max-db-size passwd 33554432 auto-propagate passwd yes enable-cache group yes positive-time-to-live group 3600 negative-time-to-live group 60 suggested-size group 211 check-files group yes persistent group yes shared group yes max-db-size group 33554432 auto-propagate group yes enable-cache hosts yes positive-time-to-live hosts 3600 negative-time-to-live hosts 20 suggested-size hosts 211 check-files hosts yes persistent hosts yes shared hosts yes max-db-size hosts 33554432 enable-cache services yes positive-time-to-live services 28800 negative-time-to-live services 20 suggested-size services 211 check-files services yes persistent services yes shared services yes max-db-size services 33554432 resolv.conf # Generated by dhcpcd from eth0 nameserver 127.0.0.1 domain westell.com nameserver 192.168.1.1 nameserver 208.67.222.222 nameserver 208.67.220.220 as kind of a side note I'm using archlinux.

    Read the article

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