Search Results

Search found 325 results on 13 pages for 'immutable'.

Page 12/13 | < Previous Page | 8 9 10 11 12 13  | Next Page >

  • how to make accessor for Dictionary in a way that returned Dictionary cannot be changed C# / 2.0

    - by matti
    I thought of solution below because the collection is very very small. But what if it was big? private Dictionary<string, OfTable> _folderData = new Dictionary<string, OfTable>(); public Dictionary<string, OfTable> FolderData { get { return new Dictionary<string,OfTable>(_folderData); } } With List you can make: public class MyClass { private List<int> _items = new List<int>(); public IList<int> Items { get { return _items.AsReadOnly(); } } } That would be nice! Thanks in advance, Cheers & BR - Matti NOW WHEN I THINK THE OBJECTS IN COLLECTION ARE IN HEAP. SO MY SOLUTION DOES NOT PREVENT THE CALLER TO MODIFY THEM!!! CAUSE BOTH Dictionary s CONTAIN REFERENCES TO SAME OBJECT. DOES THIS APPLY TO List EXAMPLE ABOVE? class OfTable { private string _wTableName; private int _table; private List<int> _classes; private string _label; public OfTable() { _classes = new List<int>(); } public int Table { get { return _table; } set { _table = value; } } public List<int> Classes { get { return _classes; } set { _classes = value; } } public string Label { get { return _label; } set { _label = value; } } } so how to make this immutable??

    Read the article

  • Cross-Origin Resource Sharing (CORS) - am I missing something here?

    - by David Semeria
    I was reading about CORS (https://developer.mozilla.org/en/HTTP_access_control) and I think the implementation is both simple and effective. However, unless I'm missing something, I think there's a big part missing from the spec. As I understand, it's the foreign site that decides, based on the origin of the request (and optionally including credentials), whether to allow access to its resources. This is fine. But what if malicious code on the page wants to POST a user's sensitive information to a foreign site? The foreign site is obviously going to authenticate the request. Hence, again if I'm not missing something, CORS actually makes it easier to steal sensitive information. I think it would have made much more sense if the original site could also supply an immutable list of servers its page is allowed to access. So the expanded sequence would be: 1) Supply a page with list of acceptable CORS servers (abc.com, xyz.com, etc) 2) Page wants to make an XHR request to abc.com - the browser allows this because it's in the allowed list and authentication proceeds as normal 3) Page wants to make an XHR request to malicious.com - request rejected locally (ie by the browser) because the server is not in the list. I know that malicious code could still use JSONP to do its dirty work, but I would have thought that a complete implementation of CORS would imply the closing of the script tag multi-site loophole. I also checked out the official CORS spec (http://www.w3.org/TR/cors) and could not find any mention of this issue.

    Read the article

  • How do I implement a collection in Scala 2.8?

    - by Simon Reinhardt
    In trying to write an API I'm struggling with Scala's collections in 2.8(.0-beta1). Basically what I need is to write something that: adds functionality to immutable sets of a certain type where all methods like filter and map return a collection of the same type without having to override everything (which is why I went for 2.8 in the first place) where all collections you gain through those methods are constructed with the same parameters the original collection had (similar to how SortedSet hands through an ordering via implicits) which is still a trait in itself, independent of any set implementations. Additionally I want to define a default implementation, for example based on a HashSet. The companion object of the trait might use this default implementation. I'm not sure yet if I need the full power of builder factories to map my collection type to other collection types. I read the paper on the redesign of the collections API but it seems like things have changed a bit since then and I'm missing some details in there. I've also digged through the collections source code but I'm not sure it's very consistent yet. Ideally what I'd like to see is either a hands-on tutorial that tells me step-by-step just the bits that I need or an extensive description of all the details so I can judge myself which bits I need. I liked the chapter on object equality in "Programming in Scala". :-) But I appreciate any pointers to documentation or examples that help me understand the new collections design better.

    Read the article

  • Writing functions of tuples conveniently in Scala

    - by Alexey Romanov
    Quite a few functions on Map take a function on a key-value tuple as the argument. E.g. def foreach(f: ((A, B)) ? Unit): Unit. So I looked for a short way to write an argument to foreach: > val map = Map(1 -> 2, 3 -> 4) map: scala.collection.immutable.Map[Int,Int] = Map(1 -> 2, 3 -> 4) > map.foreach((k, v) => println(k)) error: wrong number of parameters; expected = 1 map.foreach((k, v) => println(k)) ^ > map.foreach({(k, v) => println(k)}) error: wrong number of parameters; expected = 1 map.foreach({(k, v) => println(k)}) ^ > map.foreach(case (k, v) => println(k)) error: illegal start of simple expression map.foreach(case (k, v) => println(k)) ^ I can do > map.foreach(_ match {case (k, v) => println(k)}) 1 3 Any better alternatives?

    Read the article

  • Rails creating users, roles, and projects

    - by Bobby
    I am still fairly new to rails and activerecord, so please excuse any oversights. I have 3 models that I'm trying to tie together (and a 4th to actually do the tying) to create a permission scheme using user-defined roles. class User < ActiveRecord::Base has_many :user_projects has_many :projects, :through => :user_projects has_many :project_roles, :through => :user_projects end class Project < ActiveRecord::Base has_many :user_projects has_many :users, :through => :user_projects has_many :project_roles end class ProjectRole < ActiveRecord::Base belongs_to :projects belongs_to :user_projects end class UserProject < ActiveRecord::Base belongs_to :user belongs_to :project has_one :project_role attr_accessible :project_role_id end The project_roles model contains a user-defined role name, and booleans that define whether the given role has permissions for a specific task. I'm looking for an elegant solution to reference that from anywhere within the project piece of my application easily. I do already have a role system implemented for the entire application. What I'm really looking for though is that the users will be able to manage their own roles on a per-project basis. Every project gets setup with an immutable default admin role, and the project creator gets added upon project creation. Since the users are creating the roles, I would like to be able to pull a list of role names from the project and user models through association (for display purposes), but for testing access, I would like to simply reference them by what they have access to without having reference them by name. Perhaps something like this? def has_perm?(permission, user) # The permission that I'm testing user.current_project.project_roles.each do |role| if role.send(permission) # Not sure that's right... do_stuff end end end I think I'm in over my head on this one because I keep running in circles on how I can best implement this.

    Read the article

  • IList<T> vs IEnumerable<T>. What is more efficient IList<T> or IEnumerable<T>

    - by bigb
    What is more efficient way to make methods return IList<T> or IEnumerable<T>? IEnumerable<T> it is immutable collection but IList<T> mutable and contain a lot of useful methods and properties. To cast IList<T> to IEnumerable<T> it is just reference copy: IList<T> l = new List<T>(); IEnumerable<T> e = l; To cast IEnumerable<T> to List<T> we need to iterate each element or to call ToList() method: IEnumerable<T>.ToList(); or may pass IEnumerable<T> to List<T> constructor which doing the same iteration somewhere within its constructor. List<T> l = new List<T>(e); Which cases you think is more efficient? Which you prefer more in your practice?

    Read the article

  • one more time about loop that doesn't work

    - by unit
    I have asked a couple of questions about this for loop: String[] book = new String [ISBN_NUM]; bookNum.replaceAll("-",""); if (bookNum.length()!=ISBN_NUM) throw new ISBNException ("ISBN "+ bookNum + " must be 10 characters"); for (int i=0;i<bookNum.length();i++) { if (Character.isDigit(bookNum.charAt(i))) book[j]=bookNum.charAt(i); //this is the problem right here j++; if (book[9].isNotDigit()|| book[9]!="x" || book[9]!="X") throw new ISBNException ("ISBN " + bookNum + " must contain all digits" + "or 'X' in the last position"); } which will not compile. An answer I had from the other question I asked told me that the line where the error occurs is wrong in that bookNum.charAt(i) is an (immutable) string, and I can't get the values into a book array that way. What I need to do on my assignment is check an ISBN number (bookNum) to see that it is all numbers, except the last digit can be an 'x' (valid ISBN). Is this the best way to do it? If so, what the hell am I doing wrong? If not, what method would be a better one to use?

    Read the article

  • Fast serialization/deserialization of structs

    - by user256890
    I have huge amont of geographic data represented in simple object structure consisting only structs. All of my fields are of value type. public struct Child { readonly float X; readonly float Y; readonly int myField; } public struct Parent { readonly int id; readonly int field1; readonly int field2; readonly Child[] children; } The data is chunked up nicely to small portions of Parent[]-s. Each array contains a few thousands Parent instances. I have way too much data to keep all in memory, so I need to swap these chunks to disk back and forth. (One file would result approx. 2-300KB). What would be the most efficient way of serializing/deserializing the Parent[] to a byte[] for dumpint to disk and reading back? Concerning speed, I am particularly interested in fast deserialization, write speed is not that critical. Would simple BinarySerializer good enough? Or should I hack around with StructLayout (see accepted answer)? I am not sure if that would work with array field of Parent.children. UPDATE: Response to comments - Yes, the objects are immutable (code updated) and indeed the children field is not value type. 300KB sounds not much but I have zillions of files like that, so speed does matter.

    Read the article

  • CodePlex Daily Summary for Sunday, March 07, 2010

    CodePlex Daily Summary for Sunday, March 07, 2010New ProjectsAlgorithminator: Universal .NET algorithm visualizer, which helps you to illustrate any algorithm, written in any .NET language. Still in development.ALToolkit: Contains a set of handy .NET components/classes. Currently it contains: * A Numeric Text Box (an Extended NumericUpDown) * A Splash Screen base fo...Automaton Home: Automaton is a home automation software built with a n-Tier, MVVM pattern utilzing WCF, EF, WPF, Silverlight and XBAP.Developer Controls: Developer Controls contains various controls to help build applications that can script/write code.Dynamic Reference Manager: Dynamic Reference Manager is a set (more like a small group) of classes and attributes written in C# that allows any .NET program to reference othe...indiologic: Utilities of an IndioNeural Cryptography in F#: This project is my magistracy resulting work. It is intended to be an example of using neural networks in cryptography. Hashing functions are chose...Particle Filter Visualization: Particle Filter Visualization Program for the Intel Science and Engineering FairPólya: Efficient, immutable, polymorphic collections. .Net lacks them, we provide them*. * By we, we mean I; and by efficient, I mean hopefully so.project euler solutions from mhinze: mhinze project euler solutionsSilverlight 4 and WCF multi layer: Silverlight 4 and WCF multi layersqwarea: Project for a browser-based, minimalistic, massively multiplayer strategy game. Part of the "Génie logiciel et Cloud Computing" course of the ENS (...SuperSocket: SuperSocket, a socket application framework can build FTP/SMTP/POP server easilyToast (for ASP.NET MVC): Dynamic, developer & designer friendly content injection, compression and optimization for ASP.NET MVCNew ReleasesALToolkit: ALToolkit 1.0: Binary release of the libraries containing: NumericTextBox SplashScreen Based on the VB.NET code, but that doesn't really matter.Blacklist of Providers: 1.0-Milestone 1: Blacklist of Providers.Milestone 1In this development release implemented - Main interface (Work Item #5453) - Database (Work Item #5523)C# Linear Hash Table: Linear Hash Table b2: Now includes a default constructor, and will throw an exception if capacity is not set to a power of 2 or loadToMaintain is below 1.Composure: CassiniDev-Trunk-40745-VS2010.rc1.NET4: A simple port of the CassiniDev portable web server project for Visual Studio 2010 RC1 built against .NET 4.0. The WCF tests currently fail unless...Developer Controls: DevControls: These are the version 1.0 releases of these controls. Download the individually or all together (in a .zip file). More releases coming soon!Dynamic Reference Manager: DRM Alpha1: This is the first release. I'm calling it Alpha because I intend implementing other functions, but I do not intend changing the way current functio...ESB Toolkit Extensions: Tellago SOA ESB Extenstions v0.3: Windows Installer file that installs Library on a BizTalk ESB 2.0 system. This Install automatically configures the esb.config to use the new compo...GKO Libraries: GKO Libraries 0.1 Alpha: 0.1 AlphaHome Access Plus+: v3.0.3.0: Version 3.0.3.0 Release Change Log: Added Announcement Box Removed script files that aren't needed Fixed & issue in directory path Stylesheet...Icarus Scene Engine: Icarus Scene Engine 1.10.306.840: Icarus Professional, Icarus Player, the supporting software for Icarus Scene Engine, with some included samples, and the start of a tutorial (with ...mavjuz WndLpt: wndlpt-0.2.5: New: Response to 5 LPT inputs "test i 1" New: Reaction to 12 LPT outputs "test q 8" New: Reaction to all LPT pins "test pin 15" New: Syntax: ...Neural Cryptography in F#: Neural Cryptography 0.0.1: The most simple version of this project. It has a neural network that works just like logical AND and a possibility to recreate neural network from...Password Provider: 1.0.3: This release fixes a bug which caused the program to crash when double clicking on a generic item.RoTwee: RoTwee 6.2.0.0: New feature is as next. 16649 Add hashtag for tweet of tune.Now you can tweet your playing tune with hashtag.Visual Studio DSite: Picture Viewer (Visual C++ 2008): This example source code allows you to view any picture you want in the click of a button. All you got to do is click the button and browser via th...WatchersNET CKEditor™ Provider for DotNetNuke: CKEditor Provider 1.8.00: Whats New File Browser: Folders & Files View reworked File Browser: Folders & Files View reworked File Browser: Folders are displayed as TreeVi...WSDLGenerator: WSDLGenerator 0.0.0.4: - replaced CommonLibrary.dll by CommandLineParser.dll - added better support for custom complex typesMost Popular ProjectsMetaSharpSilverlight ToolkitASP.NET Ajax LibraryAll-In-One Code FrameworkWindows 7 USB/DVD Download Toolニコ生アラートWindows Double ExplorerVirtual Router - Wifi Hot Spot for Windows 7 / 2008 R2Caliburn: An Application Framework for WPF and SilverlightArkSwitchMost Active ProjectsUmbraco CMSRawrSDS: Scientific DataSet library and toolsBlogEngine.NETjQuery Library for SharePoint Web Servicespatterns & practices – Enterprise LibraryIonics Isapi Rewrite FilterFarseer Physics EngineFasterflect - A Fast and Simple Reflection APIFluent Assertions

    Read the article

  • To ref or not to ref

    - by nmarun
    So the question is what is the point of passing a reference type along with the ref keyword? I have an Employee class as below: 1: public class Employee 2: { 3: public string FirstName { get; set; } 4: public string LastName { get; set; } 5:  6: public override string ToString() 7: { 8: return string.Format("{0}-{1}", FirstName, LastName); 9: } 10: } In my calling class, I say: 1: class Program 2: { 3: static void Main() 4: { 5: Employee employee = new Employee 6: { 7: FirstName = "John", 8: LastName = "Doe" 9: }; 10: Console.WriteLine(employee); 11: CallSomeMethod(employee); 12: Console.WriteLine(employee); 13: } 14:  15: private static void CallSomeMethod(Employee employee) 16: { 17: employee.FirstName = "Smith"; 18: employee.LastName = "Doe"; 19: } 20: }   After having a look at the code, you’ll probably say, Well, an instance of a class gets passed as a reference, so any changes to the instance inside the CallSomeMethod, actually modifies the original object. Hence the output will be ‘John-Doe’ on the first call and ‘Smith-Doe’ on the second. And you’re right: So the question is what’s the use of passing this Employee parameter as a ref? 1: class Program 2: { 3: static void Main() 4: { 5: Employee employee = new Employee 6: { 7: FirstName = "John", 8: LastName = "Doe" 9: }; 10: Console.WriteLine(employee); 11: CallSomeMethod(ref employee); 12: Console.WriteLine(employee); 13: } 14:  15: private static void CallSomeMethod(ref Employee employee) 16: { 17: employee.FirstName = "Smith"; 18: employee.LastName = "Doe"; 19: } 20: } The output is still the same: Ok, so is there really a need to pass a reference type using the ref keyword? I’ll remove the ‘ref’ keyword and make one more change to the CallSomeMethod method. 1: class Program 2: { 3: static void Main() 4: { 5: Employee employee = new Employee 6: { 7: FirstName = "John", 8: LastName = "Doe" 9: }; 10: Console.WriteLine(employee); 11: CallSomeMethod(employee); 12: Console.WriteLine(employee); 13: } 14:  15: private static void CallSomeMethod(Employee employee) 16: { 17: employee = new Employee 18: { 19: FirstName = "Smith", 20: LastName = "John" 21: }; 22: } 23: } In line 17 you’ll see I’ve ‘new’d up the incoming Employee parameter and then set its properties to new values. The output tells me that the original instance of the Employee class does not change. Huh? But an instance of a class gets passed by reference, so why did the values not change on the original instance or how do I keep the two instances in-sync all the times? Aah, now here’s the answer. In order to keep the objects in sync, you pass them using the ‘ref’ keyword. 1: class Program 2: { 3: static void Main() 4: { 5: Employee employee = new Employee 6: { 7: FirstName = "John", 8: LastName = "Doe" 9: }; 10: Console.WriteLine(employee); 11: CallSomeMethod(ref employee); 12: Console.WriteLine(employee); 13: } 14:  15: private static void CallSomeMethod(ref Employee employee) 16: { 17: employee = new Employee 18: { 19: FirstName = "Smith", 20: LastName = "John" 21: }; 22: } 23: } Viola! Now, to prove it beyond doubt, I said, let me try with another reference type: string. 1: class Program 2: { 3: static void Main() 4: { 5: string name = "abc"; 6: Console.WriteLine(name); 7: CallSomeMethod(ref name); 8: Console.WriteLine(name); 9: } 10:  11: private static void CallSomeMethod(ref string name) 12: { 13: name = "def"; 14: } 15: } The output was as expected, first ‘abc’ and then ‘def’ - proves the 'ref' keyword works here as well. Now, what if I remove the ‘ref’ keyword? The output should still be the same as the above right, since string is a reference type? 1: class Program 2: { 3: static void Main() 4: { 5: string name = "abc"; 6: Console.WriteLine(name); 7: CallSomeMethod(name); 8: Console.WriteLine(name); 9: } 10:  11: private static void CallSomeMethod(string name) 12: { 13: name = "def"; 14: } 15: } Wrong, the output shows ‘abc’ printed twice. Wait a minute… now how could this be? This is because string is an immutable type. This means that any time you modify an instance of string, new memory address is allocated to the instance. The effect is similar to ‘new’ing up the Employee instance inside the CallSomeMethod in the absence of the ‘ref’ keyword. Verdict: ref key came to the rescue and saved the planet… again!

    Read the article

  • Liskov Substitution Principle and the Oft Forgot Third Wheel

    - by Stacy Vicknair
    Liskov Substitution Principle (LSP) is a principle of object oriented programming that many might be familiar with from the SOLID principles mnemonic from Uncle Bob Martin. The principle highlights the relationship between a type and its subtypes, and, according to Wikipedia, is defined by Barbara Liskov and Jeanette Wing as the following principle:   Let be a property provable about objects of type . Then should be provable for objects of type where is a subtype of .   Rectangles gonna rectangulate The iconic example of this principle is illustrated with the relationship between a rectangle and a square. Let’s say we have a class named Rectangle that had a property to set width and a property to set its height. 1: Public Class Rectangle 2: Overridable Property Width As Integer 3: Overridable Property Height As Integer 4: End Class   We all at some point here that inheritance mocks an “IS A” relationship, and by gosh we all know square IS A rectangle. So let’s make a square class that inherits from rectangle. However, squares do maintain the same length on every side, so let’s override and add that behavior. 1: Public Class Square 2: Inherits Rectangle 3:  4: Private _sideLength As Integer 5:  6: Public Overrides Property Width As Integer 7: Get 8: Return _sideLength 9: End Get 10: Set(value As Integer) 11: _sideLength = value 12: End Set 13: End Property 14:  15: Public Overrides Property Height As Integer 16: Get 17: Return _sideLength 18: End Get 19: Set(value As Integer) 20: _sideLength = value 21: End Set 22: End Property 23: End Class   Now, say we had the following test: 1: Public Sub SetHeight_DoesNotAffectWidth(rectangle As Rectangle) 2: 'arrange 3: Dim expectedWidth = 4 4: rectangle.Width = 4 5:  6: 'act 7: rectangle.Height = 7 8:  9: 'assert 10: Assert.AreEqual(expectedWidth, rectangle.Width) 11: End Sub   If we pass in a rectangle, this test passes just fine. What if we pass in a square?   This is where we see the violation of Liskov’s Principle! A square might "IS A” to a rectangle, but we have differing expectations on how a rectangle should function than how a square should! Great expectations Here’s where we pat ourselves on the back and take a victory lap around the office and tell everyone about how we understand LSP like a boss. And all is good… until we start trying to apply it to our work. If I can’t even change functionality on a simple setter without breaking the expectations on a parent class, what can I do with subtyping? Did Liskov just tell me to never touch subtyping again? The short answer: NO, SHE DIDN’T. When I first learned LSP, and from those I’ve talked with as well, I overlooked a very important but not appropriately stressed quality of the principle: our expectations. Our inclination is to want a logical catch-all, where we can easily apply this principle and wipe our hands, drop the mic and exit stage left. That’s not the case because in every different programming scenario, our expectations of the parent class or type will be different. We have to set reasonable expectations on the behaviors that we expect out of the parent, then make sure that those expectations are met by the child. Any expectations not explicitly expected of the parent aren’t expected of the child either, and don’t register as a violation of LSP that prevents implementation. You can see the flexibility mentioned in the Wikipedia article itself: A typical example that violates LSP is a Square class that derives from a Rectangle class, assuming getter and setter methods exist for both width and height. The Square class always assumes that the width is equal with the height. If a Square object is used in a context where a Rectangle is expected, unexpected behavior may occur because the dimensions of a Square cannot (or rather should not) be modified independently. This problem cannot be easily fixed: if we can modify the setter methods in the Square class so that they preserve the Square invariant (i.e., keep the dimensions equal), then these methods will weaken (violate) the postconditions for the Rectangle setters, which state that dimensions can be modified independently. Violations of LSP, like this one, may or may not be a problem in practice, depending on the postconditions or invariants that are actually expected by the code that uses classes violating LSP. Mutability is a key issue here. If Square and Rectangle had only getter methods (i.e., they were immutable objects), then no violation of LSP could occur. What this means is that the above situation with a rectangle and a square can be acceptable if we do not have the expectation for width to leave height unaffected, or vice-versa, in our application. Conclusion – the oft forgot third wheel Liskov Substitution Principle is meant to act as a guidance and warn us against unexpected behaviors. Objects can be stateful and as a result we can end up with unexpected situations if we don’t code carefully. Specifically when subclassing, make sure that the subclass meets the expectations held to its parent. Don’t let LSP think you cannot deviate from the behaviors of the parent, but understand that LSP is meant to highlight the importance of not only the parent and the child class, but also of the expectations WE set for the parent class and the necessity of meeting those expectations in order to help prevent sticky situations.   Code examples, in both VB and C# Technorati Tags: LSV,Liskov Substitution Principle,Uncle Bob,Robert Martin,Barbara Liskov,Liskov

    Read the article

  • Guidance: How to layout you files for an Ideal Solution

    - by Martin Hinshelwood
    Creating a solution and having it maintainable over time is an art and not a science. I like being pedantic and having a place for everything, no matter how small. For setting up the Areas to run Multiple projects under one solution see my post on  When should I use Areas in TFS instead of Team Projects and for an explanation of branching see Guidance: A Branching strategy for Scrum Teams. Update 17th May 2010 – We are currently trialling running a single Sprint branch to improve our history. Whenever I setup a new Team Project I implement the basic version control structure. I put “readme.txt” files in the folder structure explaining the different levels, and a solution file called “[Client].[Product].sln” located at “$/[Client]/[Product]/DEV/Main” within version control. Developers should add any projects you need to create to that solution in the format “[Client].[Product].[ProductArea].[Assembly]” and they will automatically be picked up and built automatically when you setup Automated Builds using Team Foundation Build. All test projects need to be done using MSTest to get proper IDE and Team Foundation Build integration out-of-the-box and be named for the assembly that it is testing with a naming convention of “[Client].[Product].[ProductArea].[Assembly].Tests” Here is a description of the folder layout; this content should be replicated in readme files under version control in the relevant locations so that even developers new to the project can see how to do it. Figure: The Team Project level - at this level there should be a folder for each the products that you are building if you are using Areas correctly in TFS 2010. You should try very hard to avoided spaces as these things always end up in a URL eventually e.g. "Code Auditor" should be "CodeAuditor". Figure: Product Level - At this level there should be only 3 folders (DEV, RELESE and SAFE) all of which should be in capitals. These folders represent the three stages of your application production line. Each of them may contain multiple branches but this format leaves all of your branches at the same level. Figure: The DEV folder is where all of the Development branches reside. The DEV folder will contain the "Main" branch and all feature branches is they are being used. The DEV designation specifies that all code in every branch under this folder has not been released or made ready for release. And feature branches MUST merge (Forward Integrate) from Main and stabilise prior to merging (Reverse Integration) back down into Main and being decommissioned. Figure: In the Feature branching scenario only merges are allowed onto Main, no development can be done there. Once we have a mature product it is important that new features being developed in parallel are kept separate. This would most likely be used if we had more than one Scrum team working on a single product. Figure: when we are ready to do a release of our software we will create a release branch that is then stabilised prior to deployment. This protects the serviceability of of our released code allowing developers to fix bugs and re-release an existing version. Figure: All bugs found on a release are fixed on the release.  All bugs found in a release are fixed on the release and a new deployment is created. After the deployment is created the bug fixes are then merged (Reverse Integration) into the Main branch. We do this so that we separate out our development from our production ready code.  Figure: SAFE or RTM is a read only record of what you actually released. Labels are not immutable so are useless in this circumstance.  When we have completed stabilisation of the release branch and we are ready to deploy to production we create a read-only copy of the code for reference. In some cases this could be a regulatory concern, but in most cases it protects the company building the product from legal entanglements based on what you did or did not release. Figure: This allows us to reference any particular version of our application that was ever shipped.   In addition I am an advocate of having a single solution with all the Project folders directly under the “Trunk”/”Main” folder and using the full name for the project folders.. Figure: The ideal solution If you must have multiple solutions, because you need to use more than one version of Visual Studio, name the solutions “[Client].[Product][VSVersion].sln” and have it reside in the same folder as the other solution. This makes it easier for Automated build and improves the discoverability of your code and its dependencies. Send me your feedback!   Technorati Tags: VS ALM,VSTS Developing,VS 2010,VS 2008,TFS 2010,TFS 2008,TFBS

    Read the article

  • Using Delegates in C# (Part 1)

    - by rajbk
    This post provides a very basic introduction of delegates in C#. Part 2 of this post can be read here. A delegate is a class that is derived from System.Delegate.  It contains a list of one or more methods called an invocation list. When a delegate instance is “invoked” with the arguments as defined in the signature of the delegate, each of the methods in the invocation list gets invoked with the arguments. The code below shows example with static and instance methods respectively: Static Methods 1: using System; 2: using System.Linq; 3: using System.Collections.Generic; 4: 5: public delegate void SayName(string name); 6: 7: public class Program 8: { 9: [STAThread] 10: static void Main(string[] args) 11: { 12: SayName englishDelegate = new SayName(SayNameInEnglish); 13: SayName frenchDelegate = new SayName(SayNameInFrench); 14: SayName combinedDelegate =(SayName)Delegate.Combine(englishDelegate, frenchDelegate); 15: 16: combinedDelegate.Invoke("Tom"); 17: Console.ReadLine(); 18: } 19: 20: static void SayNameInFrench(string name) { 21: Console.WriteLine("J'ai m'appelle " + name); 22: } 23: 24: static void SayNameInEnglish(string name) { 25: Console.WriteLine("My name is " + name); 26: } 27: } We have declared a delegate of type SayName with return type of void and taking an input parameter of name of type string. On line 12, we create a new instance of this delegate which refers to a static method - SayNameInEnglish.  SayNameInEnglish has the same return type and parameter list as the delegate declaration.  Once a delegate is instantiated, the instance will always refer to the same target. Delegates are immutable. On line 13, we create a new instance of the delegate but point to a different static method. As you may recall, a delegate instance encapsulates an invocation list. You create an invocation list by combining delegates using the Delegate.Combine method (there is an easier syntax as you will see later). When two non null delegate instances are combined, their invocation lists get combined to form a new invocation list. This is done in line 14.  On line 16, we invoke the delegate with the Invoke method and pass in the required string parameter. Since the delegate has an invocation list with two entries, each of the method in the invocation list is invoked. If an unhandled exception occurs during the invocation of one of these methods, the exception gets bubbled up to the line where the invocation was made (line 16). If a delegate is null and you try to invoke it, you will get a System.NullReferenceException. We see the following output when the method is run: My name is TomJ'ai m'apelle Tom Instance Methods The code below outputs the same results as before. The only difference here is we are creating delegates that point to a target object (an instance of Translator) and instance methods which have the same signature as the delegate type. The target object can never be null. We also use the short cut syntax += to combine the delegates instead of Delegate.Combine. 1: public delegate void SayName(string name); 2: 3: public class Program 4: { 5: [STAThread] 6: static void Main(string[] args) 7: { 8: Translator translator = new Translator(); 9: SayName combinedDelegate = new SayName(translator.SayNameInEnglish); 10: combinedDelegate += new SayName(translator.SayNameInFrench); 11:  12: combinedDelegate.Invoke("Tom"); 13: Console.ReadLine(); 14: } 15: } 16: 17: public class Translator { 18: public void SayNameInFrench(string name) { 19: Console.WriteLine("J'ai m'appelle " + name); 20: } 21: 22: public void SayNameInEnglish(string name) { 23: Console.WriteLine("My name is " + name); 24: } 25: } A delegate can be removed from a combination of delegates by using the –= operator. Removing a delegate from an empty list or removing a delegate that does not exist in a non empty list will not result in an exception. Delegates are invoked synchronously using the Invoke method. We can also invoke them asynchronously using the BeginInvoke and EndInvoke methods which are compiler generated.

    Read the article

  • C#/.NET Little Wonders &ndash; Cross Calling Constructors

    - by James Michael Hare
    Just a small post today, it’s the final iteration before our release and things are crazy here!  This is another little tidbit that I love using, and it should be fairly common knowledge, yet I’ve noticed many times that less experienced developers tend to have redundant constructor code when they overload their constructors. The Problem – repetitive code is less maintainable Let’s say you were designing a messaging system, and so you want to create a class to represent the properties for a Receiver, so perhaps you design a ReceiverProperties class to represent this collection of properties. Perhaps, you decide to make ReceiverProperties immutable, and so you have several constructors that you can use for alternative construction: 1: // Constructs a set of receiver properties. 2: public ReceiverProperties(ReceiverType receiverType, string source, bool isDurable, bool isBuffered) 3: { 4: ReceiverType = receiverType; 5: Source = source; 6: IsDurable = isDurable; 7: IsBuffered = isBuffered; 8: } 9: 10: // Constructs a set of receiver properties with buffering on by default. 11: public ReceiverProperties(ReceiverType receiverType, string source, bool isDurable) 12: { 13: ReceiverType = receiverType; 14: Source = source; 15: IsDurable = isDurable; 16: IsBuffered = true; 17: } 18:  19: // Constructs a set of receiver properties with buffering on and durability off. 20: public ReceiverProperties(ReceiverType receiverType, string source) 21: { 22: ReceiverType = receiverType; 23: Source = source; 24: IsDurable = false; 25: IsBuffered = true; 26: } Note: keep in mind this is just a simple example for illustration, and in same cases default parameters can also help clean this up, but they have issues of their own. While strictly speaking, there is nothing wrong with this code, logically, it suffers from maintainability flaws.  Consider what happens if you add a new property to the class?  You have to remember to guarantee that it is set appropriately in every constructor call. This can cause subtle bugs and becomes even uglier when the constructors do more complex logic, error handling, or there are numerous potential overloads (especially if you can’t easily see them all on one screen’s height). The Solution – cross-calling constructors I’d wager nearly everyone knows how to call your base class’s constructor, but you can also cross-call to one of the constructors in the same class by using the this keyword in the same way you use base to call a base constructor. 1: // Constructs a set of receiver properties. 2: public ReceiverProperties(ReceiverType receiverType, string source, bool isDurable, bool isBuffered) 3: { 4: ReceiverType = receiverType; 5: Source = source; 6: IsDurable = isDurable; 7: IsBuffered = isBuffered; 8: } 9: 10: // Constructs a set of receiver properties with buffering on by default. 11: public ReceiverProperties(ReceiverType receiverType, string source, bool isDurable) 12: : this(receiverType, source, isDurable, true) 13: { 14: } 15:  16: // Constructs a set of receiver properties with buffering on and durability off. 17: public ReceiverProperties(ReceiverType receiverType, string source) 18: : this(receiverType, source, false, true) 19: { 20: } Notice, there is much less code.  In addition, the code you have has no repetitive logic.  You can define the main constructor that takes all arguments, and the remaining constructors with defaults simply cross-call the main constructor, passing in the defaults. Yes, in some cases default parameters can ease some of this for you, but default parameters only work for compile-time constants (null, string and number literals).  For example, if you were creating a TradingDataAdapter that relied on an implementation of ITradingDao which is the data access object to retreive records from the database, you might want two constructors: one that takes an ITradingDao reference, and a default constructor which constructs a specific ITradingDao for ease of use: 1: public TradingDataAdapter(ITradingDao dao) 2: { 3: _tradingDao = dao; 4:  5: // other constructor logic 6: } 7:  8: public TradingDataAdapter() 9: { 10: _tradingDao = new SqlTradingDao(); 11:  12: // same constructor logic as above 13: }   As you can see, this isn’t something we can solve with a default parameter, but we could with cross-calling constructors: 1: public TradingDataAdapter(ITradingDao dao) 2: { 3: _tradingDao = dao; 4:  5: // other constructor logic 6: } 7:  8: public TradingDataAdapter() 9: : this(new SqlTradingDao()) 10: { 11: }   So in cases like this where you have constructors with non compiler-time constant defaults, default parameters can’t help you and cross-calling constructors is one of your best options. Summary When you have just one constructor doing the job of initializing the class, you can consolidate all your logic and error-handling in one place, thus ensuring that your behavior will be consistent across the constructor calls. This makes the code more maintainable and even easier to read.  There will be some cases where cross-calling constructors may be sub-optimal or not possible (if, for example, the overloaded constructors take completely different types and are not just “defaulting” behaviors). You can also use default parameters, of course, but default parameter behavior in a class hierarchy can be problematic (default values are not inherited and in fact can differ) so sometimes multiple constructors are actually preferable. Regardless of why you may need to have multiple constructors, consider cross-calling where you can to reduce redundant logic and clean up the code.   Technorati Tags: C#,.NET,Little Wonders

    Read the article

  • Announcing Solaris Technical Track at NLUUG Spring Conference on Operating Systems

    - by user9135656
    The Netherlands Unix Users Group (NLUUG) is hosting a full-day technical Solaris track during its spring 2012 conference. The official announcement page, including registration information can be found at the conference page.This year, the NLUUG spring conference focuses on the base of every computing platform; the Operating System. Hot topics like Cloud Computing and Virtualization; the massive adoption of mobile devices that have their special needs in the OS they run but that at the same time put the challenge of massive scalability onto the internet; the upspring of multi-core and multi-threaded chips..., all these developments cause the Operating System to still be a very interesting area where all kinds of innovations have taken and are taking place.The conference will focus specifically on: Linux, BSD Unix, AIX, Windows and Solaris. The keynote speech will be delivered by John 'maddog' Hall, infamous promotor and supporter of UNIX-based Operating Systems. He will talk the audience through several decades of Operating Systems developments, and share many stories untold so far. To make the conference even more interesting, a variety of talks is offered in 5 parallel tracks, covering new developments in and  also collaboration  between Linux, the BSD's, AIX, Solaris and Windows. The full-day Solaris technical track covers all innovations that have been delivered in Oracle Solaris 11. Deeply technically-skilled presenters will talk on a variety of topics. Each topic will first be introduced at a basic level, enabling visitors to attend to the presentations individually. Attending to the full day will give the audience a comprehensive overview as well as more in-depth understanding of the most important new features in Solaris 11.NLUUG Spring Conference details:* Date and time:        When : April 11 2012        Start: 09:15 (doors open: 8:30)        End  : 17:00, (drinks and snacks served afterwards)* Venue:        Nieuwegein Business Center        Blokhoeve 1             3438 LC Nieuwegein              The Nederlands          Tel     : +31 (0)30 - 602 69 00        Fax     : +31 (0)30 - 602 69 01        Email   : [email protected]        Route   : description - (PDF, Dutch only)* Conference abstracts and speaker info can be found here.* Agenda for the Solaris track: Note: talks will be in English unless marked with 'NL'.1.      Insights to Solaris 11         Joerg Moellenkamp - Solaris Technical Specialist         Oracle Germany2.      Lifecycle management with Oracle Solaris 11         Detlef Drewanz - Solaris Technical Specialist         Oracle Germany3.      Solaris 11 Networking - Crossbow Project        Andrew Gabriel - Solaris Technical Specialist        Oracle UK4.      ZFS: Data Integrity and Security         Darren Moffat - Senior Principal Engineer, Solaris Engineering         Oracle UK5.      Solaris 11 Zones and Immutable Zones (NL)         Casper Dik - Senior Staff Engineer, Software Platforms         Oracle NL6.      Experiencing Solaris 11 (NL)         Patrick Ale - UNIX Technical Specialist         UPC Broadband, NLTalks are 45 minutes each.There will be a "Solaris Meeting point" during the conference where people can meet-up, chat with the speakers and with fellow Solaris enthousiasts, and where live demos or other hands-on experiences can be shared.The official announcement page, including registration information can be found at the conference page on the NLUUG website. This site also has a complete list of all abstracts for all talks.Please register on the NLUUG website.

    Read the article

  • ensime scala errors (class scala.Array not found, object scala not found)

    - by Jeff Bowman
    I've installed ensime according to the README.md file, however, I get errors in the inferior-ensime-server buffer with the following: INFO: Fatal Error: scala.tools.nsc.MissingRequirementError: object scala not found. scala.tools.nsc.MissingRequirementError: object scala not found. at scala.tools.nsc.symtab.Definitions$definitions$.getModuleOrClass(Definitions.scala:516) at scala.tools.nsc.symtab.Definitions$definitions$.ScalaPackage(Definitions.scala:43) at scala.tools.nsc.symtab.Definitions$definitions$.ScalaPackageClass(Definitions.scala:44) at scala.tools.nsc.symtab.Definitions$definitions$.UnitClass(Definitions.scala:89) at scala.tools.nsc.symtab.Definitions$definitions$.init(Definitions.scala:786) at scala.tools.nsc.Global$Run.(Global.scala:593) at scala.tools.nsc.interactive.Global$TyperRun.(Global.scala:473) at scala.tools.nsc.interactive.Global.newTyperRun(Global.scala:535) at scala.tools.nsc.interactive.Global.reloadSources(Global.scala:289) at scala.tools.nsc.interactive.Global$$anonfun$reload$1.apply(Global.scala:300) at scala.tools.nsc.interactive.Global$$anonfun$reload$1.apply(Global.scala:300) at scala.tools.nsc.interactive.Global.respond(Global.scala:276) at scala.tools.nsc.interactive.Global.reload(Global.scala:300) at scala.tools.nsc.interactive.CompilerControl$$anon$1.apply$mcV$sp(CompilerControl.scala:81) at scala.tools.nsc.interactive.Global.pollForWork(Global.scala:132) at scala.tools.nsc.interactive.Global$$anon$2.run(Global.scala:192) also: INFO: Fatal Error: scala.tools.nsc.MissingRequirementError: class scala.Array not found. scala.tools.nsc.MissingRequirementError: class scala.Array not found. at scala.tools.nsc.symtab.Definitions$definitions$.getModuleOrClass(Definitions.scala:516) at scala.tools.nsc.symtab.Definitions$definitions$.getClass(Definitions.scala:474) at scala.tools.nsc.symtab.Definitions$definitions$.ArrayClass(Definitions.scala:217) at scala.tools.nsc.backend.icode.TypeKinds$REFERENCE.(TypeKinds.scala:258) at scala.tools.nsc.backend.icode.GenICode$ICodePhase.(GenICode.scala:55) at scala.tools.nsc.backend.icode.GenICode.newPhase(GenICode.scala:43) at scala.tools.nsc.backend.icode.GenICode.newPhase(GenICode.scala:25) at scala.tools.nsc.Global$Run$$anonfun$4.apply(Global.scala:606) at scala.tools.nsc.Global$Run$$anonfun$4.apply(Global.scala:605) at scala.collection.LinearSeqOptimized$class.foreach(LinearSeqOptimized.scala:62) at scala.collection.immutable.List.foreach(List.scala:46) at scala.tools.nsc.Global$Run.(Global.scala:605) at scala.tools.nsc.interactive.Global$TyperRun.(Global.scala:473) at scala.tools.nsc.interactive.Global.newTyperRun(Global.scala:535) at scala.tools.nsc.interactive.Global.reloadSources(Global.scala:289) at scala.tools.nsc.interactive.Global.typedTreeAt(Global.scala:309) at scala.tools.nsc.interactive.Global$$anonfun$getTypedTreeAt$1.apply(Global.scala:326) at scala.tools.nsc.interactive.Global$$anonfun$getTypedTreeAt$1.apply(Global.scala:326) at scala.tools.nsc.interactive.Global.respond(Global.scala:276) at scala.tools.nsc.interactive.Global.getTypedTreeAt(Global.scala:326) at scala.tools.nsc.interactive.CompilerControl$$anon$2.apply$mcV$sp(CompilerControl.scala:89) at scala.tools.nsc.interactive.Global.pollForWork(Global.scala:132) at scala.tools.nsc.interactive.Global$$anon$2.run(Global.scala:192) Also none of the type identification works for me, I get 'NA' if I get anything at all. C-c t causes emacs to lock up. I'm running: Ubuntu 10.04 (64bit version) emacs 23.1.50.1 ensime from git (as of 3 May 2010) scala is version 2.8.0.RC1 java is 1.6.0_20 (from sun) here is a copy of the log: http://dl.dropbox.com/u/5309017/ensime.log Thanks! Jeff

    Read the article

  • delta-dictionary/dictionary with revision awareness in python?

    - by shabbychef
    I am looking to create a dictionary with 'roll-back' capabilities in python. The dictionary would start with a revision number of 0, and the revision would be bumped up only by explicit method call. I do not need to delete keys, only add and update key,value pairs, and then roll back. I will never need to 'roll forward', that is, when rolling the dictionary back, all the newer revisions can be discarded, and I can start re-reving up again. thus I want behaviour like: >>> rr = rev_dictionary() >>> rr.rev 0 >>> rr["a"] = 17 >>> rr[('b',23)] = 'foo' >>> rr["a"] 17 >>> rr.rev 0 >>> rr.roll_rev() >>> rr.rev 1 >>> rr["a"] 17 >>> rr["a"] = 0 >>> rr["a"] 0 >>> rr[('b',23)] 'foo' >>> rr.roll_to(0) >>> rr.rev 0 >>> rr["a"] 17 >>> rr.roll_to(1) Exception ... Just to be clear, the state associated with a revision is the state of the dictionary just prior to the roll_rev() method call. thus if I can alter the value associated with a key several times 'within' a revision, and only have the last one remembered. I would like a fairly memory-efficient implementation of this: the memory usage should be proportional to the deltas. Thus simply having a list of copies of the dictionary will not scale for my problem. One should assume the keys are in the tens of thousands, and the revisions are in the hundreds of thousands. We can assume the values are immutable, but need not be numeric. For the case where the values are e.g. integers, there is a fairly straightforward implementation (have a list of dictionaries of the numerical delta from revision to revision). I am not sure how to turn this into the general form. Maybe bootstrap the integer version and add on an array of values? all help appreciated.

    Read the article

  • NSObject release destroys local copy of object's data

    - by Spider-Paddy
    I know this is something stupid on my part but I don't get what's happening. I create an object that fetches data & puts it into an array in a specific format, since it fetches asynchronously (has to download & parse data) I put a delegate method into the object that needs the data so that the data fetching object copies it's formatted array into an array in the calling object. The problem is that when the data fetching object is released, the copy it created in the caller is being erased, code is: In .h file @property (nonatomic, retain) NSArray *imagesDataSource; In .m file // Fetch item details ImagesParser *imagesParserObject = [[ImagesParser alloc] init:self]; [imagesParserObject getArticleImagesOfArticleId:(NSInteger)currentArticleId]; [imagesParserObject release] <-- problematic release // Called by parser when images parsing is finished -(void)imagesDataTransferComplete:(ImagesParser *)imagesParserObject { self.imagesDataSource = [ImagesParserObject.returnedArray copy]; // copy array to local variable // If there are more pics, they must be assembled in an array for possible UIImageView animation NSInteger picCount = [imagesDataSource count]; if(picCount > 1) // 1 image is assumed to be the pic already displayed { // Build image array NSMutableArray *tempPicArray = [[NSMutableArray alloc] init]; // Temp space to hold images while building for(int i = 0; i < picCount; i++) { // Get Nr from only article in detailDataSource & pic name (Small) from each item in imagesDataSource NSString *picAddress = [NSString stringWithFormat:@"http://some.url.com/shopdata/image/article/%@/%@", [[detailDataSource objectAtIndex:0] objectForKey:@"Nr"], [[imagesDataSource objectAtIndex:i] objectForKey:@"Small"]]; NSURL *picURL = [NSURL URLWithString:picAddress]; NSData *picData = [NSData dataWithContentsOfURL:picURL]; [tempPicArray addObject:[UIImage imageWithData:picData]]; } imagesArray = [tempPicArray copy]; // copy makes immutable copy of array [tempPicArray release]; currentPicIndex = 0; // Assume first pic is pic already being shown } else imagesArray = nil; // No need for a needless pic array // Remove please wait message [pleaseWaitViewControllerObject.view removeFromSuperview]; } I put in tons of NSLog lines to keep track of what was going on & self.imagesDataSource is populated with the returned array but when the parser object is released self.imagesDataSource becomes empty. I thought self.imagesDataSource = [ImagesParserObject.returnedArray copy]; is supposed to make an independant object, like as if it was alloc, init'ed, so that self.imagesDataSource is not just a pointer to the parser's array but is it's own array. So why does the release of the parser object clear the copy of the array. (I checked & double checked that it's not something overwriting self.imagesDataSource, commenting out [imagesParserObject release] consistently fixes the problem) Also, I have exactly the same problem with self.detailDataSource which is declared & populated in the exact same way as self.imagesDataSource I thought that once I call the parser I could release it because the caller no longer needs to refer to it, all further activity is carried out by the parser object through it's delegate method, what am I doing wrong?

    Read the article

  • Creating a System::String object from a BSTR in Managed C++ - is this way a good idea???

    - by Eli
    My co-worker is filling a System::String object with double-byte characters from an unmanaged library by the following method: RFC_PARAMETER aux; Object* target; RFC_UNICODE_TYPE_ELEMENT* elm; elm = &(m_coreObject->m_pStructMeta->m_typeElements[index]); aux.name = NULL; aux.nlen = 0; aux.type = elm->type; aux.leng = elm->c2_length; aux.addr = m_coreObject->m_rfcWa + elm->c2_offset; GlobalFunctions::CreateObjectForRFCField(target,aux,elm->decimals); GlobalFunctions::ReadRFCField(target,aux,elm->decimals); Where GlobalFunctions::CreateObjectForRFCField creates a System::String object filled with spaces (for padding) to what the unmanaged library states the max length should be: static void CreateObjectForRFCField(Object*& object, RFC_PARAMETER& par, unsigned dec) { switch (par.type) { case TYPC: object = new String(' ',par.leng / sizeof(_TCHAR)); break; // unimportant afterwards. } } And GlobalFunctions::ReadRFCField() copies the data from the library into the created String object and preserves the space padding: static void ReadRFCField(String* target, RFC_PARAMETER& par) { int lngt; _TCHAR* srce; switch (par.type) { case TYPC: case TYPDATE: case TYPTIME: case TYPNUM: lngt = par.leng / sizeof(_TCHAR); srce = (_TCHAR*)par.addr; break; case RFCTYPE_STRING: lngt = (*(_TCHAR**)par.addr != NULL) ? (int)_tcslen(*(_TCHAR**)par.addr) : 0; srce = *(_TCHAR**)par.addr; break; default: throw new DotNet_Incomp_RFCType2; } if (lngt > target->Length) lngt = target->Length; GCHandle gh = GCHandle::Alloc(target,GCHandleType::Pinned); wchar_t* buff = reinterpret_cast<wchar_t*>(gh.AddrOfPinnedObject().ToPointer()); _wcsnset(buff,' ',target->Length); _snwprintf(buff,lngt,_T2WFSP,srce); gh.Free(); } Now, on occasion, we see access violations getting thrown in the _snwprintf call. My question really is: Is it appropriate to create a string padded to a length (ideally to pre-allocate the internal buffer), and then to modify the String using GCHandle::Alloc and the mess above. And yes, I know that System::String objects are supposed to be immutable - I'm looking for a definitive "This is WRONG and here is why". Thanks, Eli.

    Read the article

  • NSMutableArray can't be added to

    - by Dan Ray
    I've had this sort of problem before, and it didn't get a satisfactory answer. I have a viewcontroller with a property called "counties" that is an NSMutableArray. I'm going to drill down a navigation screen to a view that is about selecting the counties for a geographical search. So the search page drills down to the "select counties" page. I pass NSMutableArray *counties to the second controller as I push the second one on the navigation stack. I actually set that second controller's "selectedCounties" property (also an NSMutableArray) with a pointer to my first controller's "counties", as you'll see below. When I go to addObject to that, though, I get this: *** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: '*** -[NSCFArray insertObject:atIndex:]: mutating method sent to immutable object' Here's my code: in SearchViewController.h: @interface SearchViewController : UIViewController { .... NSMutableArray *counties; } .... @property (nonatomic, retain) NSMutableArray *counties; in SearchViewController.m: - (void)getLocationsView { [keywordField resignFirstResponder]; SearchLocationsViewController *locationsController = [[SearchLocationsViewController alloc] initWithNibName:@"SearchLocationsView" bundle:nil]; [self.navigationController pushViewController:locationsController animated:YES]; [locationsController setSelectedCounties:self.counties]; [locationsController release]; } in SearchLocationsViewController.h: @interface EventsSearchLocationsViewController : UIViewController <UITableViewDelegate, UITableViewDataSource> { ... NSMutableArray *selectedCounties; } ... @property (nonatomic, retain) NSMutableArray *selectedCounties; in SearchLocationsViewController.m (the point here is, we're toggling each element of a table being active or not in the list of selected counties): -(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath]; if ([self.selectedCounties containsObject:[self.counties objectAtIndex:indexPath.row]]) { //we're deselcting! [self.selectedCounties removeObject:[self.counties objectAtIndex:indexPath.row]]; cell.accessoryView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"red_check_inactive.png"]]; } else { [self.selectedCounties addObject:[self.counties objectAtIndex:indexPath.row]]; cell.accessoryView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"red_check_active.png"]]; } [tableView deselectRowAtIndexPath:indexPath animated:YES]; } We die at [self.selectedCounties addObject.... there. Now, when I NSLog myself [self.selectedCounties class], it tells me it's an NSCFArray. How does this happen? I understand about class bundles (or I THINK I do anyway), but this is explicitly a specific type, and it's losing it subclassing at some point in a way that kills the whole thing. I just completely don't understand why that would happen.

    Read the article

  • How would you implement this "WorkerChain" functionality in .NET?

    - by Dan Tao
    Sorry for the vague question title -- not sure how to encapsulate what I'm asking below succinctly. (If someone with editing privileges can think of a more descriptive title, feel free to change it.) The behavior I need is this. I am envisioning a worker class that accepts a single delegate task in its constructor (for simplicity, I would make it immutable -- no more tasks can be added after instantiation). I'll call this task T. The class should have a simple method, something like GetToWork, that will exhibit this behavior: If the worker is not currently running T, then it will start doing so right now. If the worker is currently running T, then once it is finished, it will start T again immediately. GetToWork can be called any number of times while the worker is running T; the simple rule is that, during any execution of T, if GetToWork was called at least once, T will run again upon completion (and then if GetToWork is called while T is running that time, it will repeat itself again, etc.). Now, this is pretty straightforward with a boolean switch. But this class needs to be thread-safe, by which I mean, steps 1 and 2 above need to comprise atomic operations (at least I think they do). There is an added layer of complexity. I have need of a "worker chain" class that will consist of many of these workers linked together. As soon as the first worker completes, it essentially calls GetToWork on the worker after it; meanwhile, if its own GetToWork has been called, it restarts itself as well. Logically calling GetToWork on the chain is essentially the same as calling GetToWork on the first worker in the chain (I would fully intend that the chain's workers not be publicly accessible). One way to imagine how this hypothetical "worker chain" would behave is by comparing it to a team in a relay race. Suppose there are four runners, W1 through W4, and let the chain be called C. If I call C.StartWork(), what should happen is this: If W1 is at his starting point (i.e., doing nothing), he will start running towards W2. If W1 is already running towards W2 (i.e., executing his task), then once he reaches W2, he will signal to W2 to get started, immediately return to his starting point and, since StartWork has been called, start running towards W2 again. When W1 reaches W2's starting point, he'll immediately return to his own starting point. If W2 is just sitting around, he'll start running immediately towards W3. If W2 is already off running towards W3, then W2 will simply go again once he's reached W3 and returned to his starting point. The above is probably a little convoluted and written out poorly. But hopefully you get the basic idea. Obviously, these workers will be running on their own threads. Also, I guess it's possible this functionality already exists somewhere? If that's the case, definitely let me know!

    Read the article

  • Java replacement for C macros

    - by thkala
    Recently I refactored the code of a 3rd party hash function from C++ to C. The process was relatively painless, with only a few changes of note. Now I want to write the same function in Java and I came upon a slight issue. In the C/C++ code there is a C preprocessor macro that takes a few integer variables names as arguments and performs a bunch of bitwise operations with their contents and a few constants. That macro is used in several different places, therefore its presence avoids a fair bit of code duplication. In Java, however, there is no equivalent for the C preprocessor. There is also no way to affect any basic type passed as an argument to a method - even autoboxing produces immutable objects. Coupled with the fact that Java methods return a single value, I can't seem to find a simple way to rewrite the macro. Avenues that I considered: Expand the macro by hand everywhere: It would work, but the code duplication could make things interesting in the long run. Write a method that returns an array: This would also work, but it would repeatedly result into code like this: long tmp[] = bitops(k, l, m, x, y, z); k = tmp[0]; l = tmp[1]; m = tmp[2]; x = tmp[3]; y = tmp[4]; z = tmp[5]; Write a method that takes an array as an argument: This would mean that all variable names would be reduced to array element references - it would be rather hard to keep track of which index corresponds to which variable. Create a separate class e.g. State with public fields of the appropriate type and use that as an argument to a method: This is my current solution. It allows the method to alter the variables, while still keeping their names. It has the disadvantage, however, that the State class will get more and more complex, as more macros and variables are added, in order to avoid copying values back and forth among different State objects. How would you rewrite such a C macro in Java? Is there a more appropriate way to deal with this, using the facilities provided by the standard Java 6 Development Kit (i.e. without 3rd party libraries or a separate preprocessor)?

    Read the article

  • Correcting a plist with dictionaries

    - by ingenspor
    Plist is copyed to documents directory if it doesn't exist. If it already exists, I want to use the "Name" key from NSDictionary in bundleArray to find the matching NSDictionary in documentsArray. When the match is found, I want to check for changes in the strings and replace them if there is a change. If a match is not found it means this dictionary must be added to documents plist. This is my code: - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { [self managePlist]; return YES; } - (void)managePlist { NSError *error; NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *documentsDirectory = [paths objectAtIndex:0]; NSString *path = [documentsDirectory stringByAppendingPathComponent:@"Objects.plist"]; NSString *bundle = [[NSBundle mainBundle] pathForResource:@"Objects" ofType:@"plist"]; NSFileManager *fileManager = [NSFileManager defaultManager]; if (![fileManager fileExistsAtPath: path]) { [fileManager copyItemAtPath:bundle toPath:path error:&error]; } else { NSArray *bundleArray = [[NSArray alloc] initWithContentsOfFile:bundle]; NSMutableArray *documentArray = [[NSMutableArray alloc] initWithContentsOfFile:path]; BOOL updateDictionary = NO; for(int i=0;i<bundleArray.count;i++) { NSDictionary *bundleDict=[bundleArray objectAtIndex:i]; BOOL matchInDocuments = NO; for(int ii=0;ii<documentArray.count;ii++) { NSMutableDictionary *documentDict = [documentArray objectAtIndex:ii]; NSString *bundleObjectName = [bundleDict valueForKey:@"Name"]; NSString *documentsObjectName = [documentDict valueForKey:@"Name"]; NSRange range = [documentsObjectName rangeOfString:bundleObjectName options:NSCaseInsensitiveSearch]; if (range.location != NSNotFound) { matchInDocuments = YES; } if (matchInDocuments) { if ([bundleDict objectForKey:@"District"] != [documentDict objectForKey:@"District"]) { [documentDict setObject:[bundleDict objectForKey:@"District"] forKey:@"District"]; updateDictionary=YES; } } else { [documentArray addObject:bundleDict]; updateDictionary=YES; } } } if(updateDictionary){ [documentArray writeToFile:path atomically:YES]; } } } If I run my app now I get this message: '-[__NSCFDictionary setObject:forKey:]: mutating method sent to immutable object' How can I fix this? When this is fixed, do you think my code will work? If not, I would be happy for some suggestions on how to do this. I have struggled for a while and really need to publish the update with the corrections! Thanks a lot for your help.

    Read the article

  • Hot to get rid of memory allocations/deallocations in swig wrappers?

    - by Dmitriy Matveev
    I want to use swig for generation of read-only wrappers for a complex object. The object which I want to wrap will always be existent while I will read it. And also I will only use my wrappers at the time that object is existent, thus I don't need any memory management from SWIG. For following swig interface: %module test %immutable; %inline %{ struct Foo { int a; }; struct Bar { int b; Foo f; }; %} I will have a wrappers which will have a lot of garbage in generated interfaces and do useless work which will reduce performance in my case. Generated java wrapper for Bar class will be like this: public class Bar { private long swigCPtr; protected boolean swigCMemOwn; protected Bar(long cPtr, boolean cMemoryOwn) { swigCMemOwn = cMemoryOwn; swigCPtr = cPtr; } protected static long getCPtr(Bar obj) { return (obj == null) ? 0 : obj.swigCPtr; } protected void finalize() { delete(); } public synchronized void delete() { if (swigCPtr != 0) { if (swigCMemOwn) { swigCMemOwn = false; testJNI.delete_Bar(swigCPtr); } swigCPtr = 0; } } public int getB() { return testJNI.Bar_b_get(swigCPtr, this); } public Foo getF() { return new Foo(testJNI.Bar_f_get(swigCPtr, this), true); } public Bar() { this(testJNI.new_Bar(), true); } } I don't need 'swigCMemOwn' field in my wrapper since it always will be false. All code related to this field will also be useless. There are also unnecessary logic in native code: SWIGEXPORT jlong JNICALL Java_some_testJNI_Bar_1f_1get(JNIEnv *jenv, jclass jcls, jlong jarg1, jobject jarg1_) { jlong jresult = 0 ; struct Bar *arg1 = (struct Bar *) 0 ; Foo result; (void)jenv; (void)jcls; (void)jarg1_; arg1 = *(struct Bar **)&jarg1; result = ((arg1)->f); { Foo * resultptr = (Foo *) malloc(sizeof(Foo)); memmove(resultptr, &result, sizeof(Foo)); *(Foo **)&jresult = resultptr; } return jresult; } I don't need these calls to malloc and memmove. I want to force swig to resolve both of these problems, but don't know how. Is it possible?

    Read the article

  • Abstract class and an inheritor: is it possible to factorize .parent() here?

    - by fge
    Here are what I think are the relevant parts of the code of these two classes. First, TreePointer (original source here): public abstract class TreePointer<T extends TreeNode> implements Iterable<TokenResolver<T>> { //... /** * What this tree can see as a missing node (may be {@code null}) */ private final T missing; /** * The list of token resolvers */ protected final List<TokenResolver<T>> tokenResolvers; /** * Main protected constructor * * <p>This constructor makes an immutable copy of the list it receives as * an argument.</p> * * @param missing the representation of a missing node (may be null) * @param tokenResolvers the list of reference token resolvers */ protected TreePointer(final T missing, final List<TokenResolver<T>> tokenResolvers) { this.missing = missing; this.tokenResolvers = ImmutableList.copyOf(tokenResolvers); } /** * Alternate constructor * * <p>This is the same as calling {@link #TreePointer(TreeNode, List)} with * {@code null} as the missing node.</p> * * @param tokenResolvers the list of token resolvers */ protected TreePointer(final List<TokenResolver<T>> tokenResolvers) { this(null, tokenResolvers); } //... /** * Tell whether this pointer is empty * * @return true if the reference token list is empty */ public final boolean isEmpty() { return tokenResolvers.isEmpty(); } @Override public final Iterator<TokenResolver<T>> iterator() { return tokenResolvers.iterator(); } // .equals(), .hashCode(), .toString() follow } Then, JsonPointer, which contains this .parent() method which I'd like to factorize here (original source here: public final class JsonPointer extends TreePointer<JsonNode> { /** * The empty JSON Pointer */ private static final JsonPointer EMPTY = new JsonPointer(ImmutableList.<TokenResolver<JsonNode>>of()); /** * Return an empty JSON Pointer * * @return an empty, statically allocated JSON Pointer */ public static JsonPointer empty() { return EMPTY; } //... /** * Return the immediate parent of this JSON Pointer * * <p>The parent of the empty pointer is itself.</p> * * @return a new JSON Pointer representing the parent of the current one */ public JsonPointer parent() { final int size = tokenResolvers.size(); return size <= 1 ? EMPTY : new JsonPointer(tokenResolvers.subList(0, size - 1)); } // ... } As mentioned in the subject, the problem I have here is with JsonPointer's .parent() method. In fact, the logic behind this method applies to TreeNode all the same, and therefore to its future implementations. Except that I have to use a constructor, and of course such a constructor is implementation dependent :/ Is there a way to make that .parent() method available to each and every implementation of TreeNode or is it just a pipe dream?

    Read the article

< Previous Page | 8 9 10 11 12 13  | Next Page >