Search Results

Search found 12058 results on 483 pages for 'abstract syntax tree'.

Page 1/483 | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >

  • Silverlight Tree View with Multiple Levels

    - by psheriff
    There are many examples of the Silverlight Tree View that you will find on the web, however, most of them only show you how to go to two levels. What if you have more than two levels? This is where understanding exactly how the Hierarchical Data Templates works is vital. In this blog post, I am going to break down how these templates work so you can really understand what is going on underneath the hood. To start, let’s look at the typical two-level Silverlight Tree View that has been hard coded with the values shown below: <sdk:TreeView>  <sdk:TreeViewItem Header="Managers">    <TextBlock Text="Michael" />    <TextBlock Text="Paul" />  </sdk:TreeViewItem>  <sdk:TreeViewItem Header="Supervisors">    <TextBlock Text="John" />    <TextBlock Text="Tim" />    <TextBlock Text="David" />  </sdk:TreeViewItem></sdk:TreeView> Figure 1 shows you how this tree view looks when you run the Silverlight application. Figure 1: A hard-coded, two level Tree View. Next, let’s create three classes to mimic the hard-coded Tree View shown above. First, you need an Employee class and an EmployeeType class. The Employee class simply has one property called Name. The constructor is created to accept a “name” argument that you can use to set the Name property when you create an Employee object. public class Employee{  public Employee(string name)  {    Name = name;  }   public string Name { get; set; }} Finally you create an EmployeeType class. This class has one property called EmpType and contains a generic List<> collection of Employee objects. The property that holds the collection is called Employees. public class EmployeeType{  public EmployeeType(string empType)  {    EmpType = empType;    Employees = new List<Employee>();  }   public string EmpType { get; set; }  public List<Employee> Employees { get; set; }} Finally we have a collection class called EmployeeTypes created using the generic List<> class. It is in the constructor for this class where you will build the collection of EmployeeTypes and fill it with Employee objects: public class EmployeeTypes : List<EmployeeType>{  public EmployeeTypes()  {    EmployeeType type;            type = new EmployeeType("Manager");    type.Employees.Add(new Employee("Michael"));    type.Employees.Add(new Employee("Paul"));    this.Add(type);     type = new EmployeeType("Project Managers");    type.Employees.Add(new Employee("Tim"));    type.Employees.Add(new Employee("John"));    type.Employees.Add(new Employee("David"));    this.Add(type);  }} You now have a data hierarchy in memory (Figure 2) which is what the Tree View control expects to receive as its data source. Figure 2: A hierachial data structure of Employee Types containing a collection of Employee objects. To connect up this hierarchy of data to your Tree View you create an instance of the EmployeeTypes class in XAML as shown in line 13 of Figure 3. The key assigned to this object is “empTypes”. This key is used as the source of data to the entire Tree View by setting the ItemsSource property as shown in Figure 3, Callout #1. Figure 3: You need to start from the bottom up when laying out your templates for a Tree View. The ItemsSource property of the Tree View control is used as the data source in the Hierarchical Data Template with the key of employeeTypeTemplate. In this case there is only one Hierarchical Data Template, so any data you wish to display within that template comes from the collection of Employee Types. The TextBlock control in line 20 uses the EmpType property of the EmployeeType class. You specify the name of the Hierarchical Data Template to use in the ItemTemplate property of the Tree View (Callout #2). For the second (and last) level of the Tree View control you use a normal <DataTemplate> with the name of employeeTemplate (line 14). The Hierarchical Data Template in lines 17-21 sets its ItemTemplate property to the key name of employeeTemplate (Line 19 connects to Line 14). The source of the data for the <DataTemplate> needs to be a property of the EmployeeTypes collection used in the Hierarchical Data Template. In this case that is the Employees property. In the Employees property there is a “Name” property of the Employee class that is used to display the employee name in the second level of the Tree View (Line 15). What is important here is that your lowest level in your Tree View is expressed in a <DataTemplate> and should be listed first in your Resources section. The next level up in your Tree View should be a <HierarchicalDataTemplate> which has its ItemTemplate property set to the key name of the <DataTemplate> and the ItemsSource property set to the data you wish to display in the <DataTemplate>. The Tree View control should have its ItemsSource property set to the data you wish to display in the <HierarchicalDataTemplate> and its ItemTemplate property set to the key name of the <HierarchicalDataTemplate> object. It is in this way that you get the Tree View to display all levels of your hierarchical data structure. Three Levels in a Tree View Now let’s expand upon this concept and use three levels in our Tree View (Figure 4). This Tree View shows that you now have EmployeeTypes at the top of the tree, followed by a small set of employees that themselves manage employees. This means that the EmployeeType class has a collection of Employee objects. Each Employee class has a collection of Employee objects as well. Figure 4: When using 3 levels in your TreeView you will have 2 Hierarchical Data Templates and 1 Data Template. The EmployeeType class has not changed at all from our previous example. However, the Employee class now has one additional property as shown below: public class Employee{  public Employee(string name)  {    Name = name;    ManagedEmployees = new List<Employee>();  }   public string Name { get; set; }  public List<Employee> ManagedEmployees { get; set; }} The next thing that changes in our code is the EmployeeTypes class. The constructor now needs additional code to create a list of managed employees. Below is the new code. public class EmployeeTypes : List<EmployeeType>{  public EmployeeTypes()  {    EmployeeType type;    Employee emp;    Employee managed;     type = new EmployeeType("Manager");    emp = new Employee("Michael");    managed = new Employee("John");    emp.ManagedEmployees.Add(managed);    managed = new Employee("Tim");    emp.ManagedEmployees.Add(managed);    type.Employees.Add(emp);     emp = new Employee("Paul");    managed = new Employee("Michael");    emp.ManagedEmployees.Add(managed);    managed = new Employee("Sara");    emp.ManagedEmployees.Add(managed);    type.Employees.Add(emp);    this.Add(type);     type = new EmployeeType("Project Managers");    type.Employees.Add(new Employee("Tim"));    type.Employees.Add(new Employee("John"));    type.Employees.Add(new Employee("David"));    this.Add(type);  }} Now that you have all of the data built in your classes, you are now ready to hook up this three-level structure to your Tree View. Figure 5 shows the complete XAML needed to hook up your three-level Tree View. You can see in the XAML that there are now two Hierarchical Data Templates and one Data Template. Again you list the Data Template first since that is the lowest level in your Tree View. The next Hierarchical Data Template listed is the next level up from the lowest level, and finally you have a Hierarchical Data Template for the first level in your tree. You need to work your way from the bottom up when creating your Tree View hierarchy. XAML is processed from the top down, so if you attempt to reference a XAML key name that is below where you are referencing it from, you will get a runtime error. Figure 5: For three levels in a Tree View you will need two Hierarchical Data Templates and one Data Template. Each Hierarchical Data Template uses the previous template as its ItemTemplate. The ItemsSource of each Hierarchical Data Template is used to feed the data to the previous template. This is probably the most confusing part about working with the Tree View control. You are expecting the content of the current Hierarchical Data Template to use the properties set in the ItemsSource property of that template. But you need to look to the template lower down in the XAML to see the source of the data as shown in Figure 6. Figure 6: The properties you use within the Content of a template come from the ItemsSource of the next template in the resources section. Summary Understanding how to put together your hierarchy in a Tree View is simple once you understand that you need to work from the bottom up. Start with the bottom node in your Tree View and determine what that will look like and where the data will come from. You then build the next Hierarchical Data Template to feed the data to the previous template you created. You keep doing this for each level in your Tree View until you get to the last level. The data for that last Hierarchical Data Template comes from the ItemsSource in the Tree View itself. NOTE: You can download the sample code for this article by visiting my website at http://www.pdsa.com/downloads. Select “Tips & Tricks”, then select “Silverlight TreeView with Multiple Levels” from the drop down list.

    Read the article

  • Switching from abstract class to interface

    - by nischayn22
    I have an abstract class which has all abstract methods except one which constructs objects of the subclasses. Now my mentor asked me to move this abstract class to an interface. Having an interface is no problem except with the method used to construct subclass objects. Where should this method go now? Also, I read somewhere that interfaces are more efficient than abstract classes. Is this true? Here's an example of my classes abstract class Animal { //many abstract methods getAnimalobject(some parameter) { return //appropriate subclass } } class Dog extends Animal {} class Elephant extends Animal {}

    Read the article

  • Finding if a Binary Tree is a Binary Search Tree

    - by dharam
    Today I had an interview where I was asked to write a program which takes a Binary Tree and returns true if it is also a Binary Search Tree otherwise false. My Approach1: Perform an inroder traversal and store the elements in O(n) time. Now scan through the array/list of elements and check if element at ith index is greater than element at (i+1)th index. If such a condition is encountered, return false and break out of the loop. (This takes O(n) time). At the end return true. But this gentleman wanted me to provide an efficient solution. I tried but I was unsuccessfult, because to find if it is a BST I have to check each node. Moreover he was pointing me to think over recusrion. My Approach 2: A BT is a BST if for any node N N-left is < N and N-right N , and the INorder successor of left node of N is less than N and the inorder successor of right node of N is greater than N and the left and right subtrees are BSTs. But this is going to be complicated and running time doesn't seem to be good. Please help if you know any optimal solution. Thanks.

    Read the article

  • Insert Record by Drag & Drop from ADF Tree to ADF Tree Table

    - by arul.wilson(at)oracle.com
    If you want to create record based on the values Dragged from ADF Tree and Dropped on a ADF Tree Table, then here you go.UseCase DescriptionUser Drags a tree node from ADF Tree and Drops it on a ADF Tree Table node. A new row gets added in the Tree Table based on the source tree node, subsequently a record gets added to the database table on which Tree table in based on.Following description helps to achieve this using ADF BC.Run the DragDropSchema.sql to create required tables.Create Business Components from tables (PRODUCTS, COMPONENTS, SUB_COMPONENTS, USERS, USER_COMPONENTS) created above.Add custom method to App Module Impl, this method will be used to insert record from view layer.   public String createUserComponents(String p_bugdbId, String p_productId, String p_componentId, String p_subComponentId){    Row newUserComponentsRow = this.getUserComponentsView1().createRow();    try {      newUserComponentsRow.setAttribute("Bugdbid", p_bugdbId);      newUserComponentsRow.setAttribute("ProductId", new oracle.jbo.domain.Number(p_productId));      newUserComponentsRow.setAttribute("Component1", p_componentId);      newUserComponentsRow.setAttribute("SubComponent", p_subComponentId);    } catch (Exception e) {        e.printStackTrace();        return "Failure";    }        return "Success";  }Expose this method to client interface.To display the root node we need a custom VO which can be achieved using below query. SELECT Users.ACTIVE, Users.BUGDB_ID, Users.EMAIL, Users.FIRSTNAME, Users.GLOBAL_ID, Users.LASTNAME, Users.MANAGER_ID, Users.MANAGER_PRIVILEGEFROM USERS UsersWHERE Users.MANAGER_ID is NULLCreate VL between UsersView and UsersRootNodeView VOs.Drop ProductsView from DC as ADF Tree to jspx page.Add Tree Level Rule based on ComponentsView and SubComponentsView.Drop UsersRootNodeView as ADF Tree TableAdd Tree Level Rules based on UserComponentsView and UsersView.Add DragSource to ADF Tree and CollectionDropTarget to ADF Tree Table respectively.Bind CollectionDropTarget's DropTarget to backing bean and implement method of signature DnDAction (DropEvent), this method gets invoked when Tree Table encounters a drop action, here details required for creating new record are captured from the drag source and passed to 'createUserComponents' method. public DnDAction onTreeDrop(DropEvent dropEvent) {      String newBugdbId = "";      String msgtxt="";            try {          // Getting the target node bugdb id          Object serverRowKey = dropEvent.getDropSite();          if (serverRowKey != null) {                  //Code for Tree Table as target              String dropcomponent = dropEvent.getDropComponent().toString();              dropcomponent = (String)dropcomponent.subSequence(0, dropcomponent.indexOf("["));              if (dropcomponent.equals("RichTreeTable")){                RichTreeTable richTreeTable = (RichTreeTable)dropEvent.getDropComponent();                richTreeTable.setRowKey(serverRowKey);                int rowIndexTreeTable = richTreeTable.getRowIndex();                //Drop Target Logic                if (((JUCtrlHierNodeBinding)richTreeTable.getRowData(rowIndexTreeTable)).getAttributeValue()==null) {                  //Get Parent                  newBugdbId = (String)((JUCtrlHierNodeBinding)richTreeTable.getRowData(rowIndexTreeTable)).getParent().getAttributeValue();                } else {                  if (isNum(((JUCtrlHierNodeBinding)richTreeTable.getRowData(rowIndexTreeTable)).getAttributeValue().toString())) {                    //Get Parent's parent                              newBugdbId = (String)((JUCtrlHierNodeBinding)richTreeTable.getRowData(rowIndexTreeTable)).getParent().getParent().getAttributeValue();                  } else{                      //Dropped on USER                                          newBugdbId = (String)((JUCtrlHierNodeBinding)richTreeTable.getRowData(rowIndexTreeTable)).getAttributeValue();                  }                  }              }           }                     DataFlavor<RowKeySet> df = DataFlavor.getDataFlavor(RowKeySet.class);          RowKeySet droppedValue = dropEvent.getTransferable().getData(df);            Object[] keys = droppedValue.toArray();          Key componentKey = null;          Key subComponentKey = null;           // binding for createUserComponents method defined in AppModuleImpl class  to insert record in database.                      operationBinding = bindings.getOperationBinding("createUserComponents");            // get the Product, Component, Subcomponent details and insert to UserComponents table.          // loop through the keys if more than one comp/subcomponent is select.                   for (int i = 0; i < keys.length; i++) {                  System.out.println("in for :"+i);              List list = (List)keys[i];                  System.out.println("list "+i+" : "+list);              System.out.println("list size "+list.size());              if (list.size() == 1) {                                // we cannot drag and drop  the highest node !                                msgtxt="You cannot drop Products, please drop Component or SubComponent from the Tree.";                  System.out.println(msgtxt);                                this.showInfoMessage(msgtxt);              } else {                  if (list.size() == 2) {                    // were doing the first branch, in this case all components.                    componentKey = (Key)list.get(1);                    Object[] droppedProdCompValues = componentKey.getAttributeValues();                    operationBinding.getParamsMap().put("p_bugdbId",newBugdbId);                    operationBinding.getParamsMap().put("p_productId",droppedProdCompValues[0]);                    operationBinding.getParamsMap().put("p_componentId",droppedProdCompValues[1]);                    operationBinding.getParamsMap().put("p_subComponentId","ALL");                    Object result = operationBinding.execute();              } else {                    subComponentKey = (Key)list.get(2);                    Object[] droppedProdCompSubCompValues = subComponentKey.getAttributeValues();                    operationBinding.getParamsMap().put("p_bugdbId",newBugdbId);                    operationBinding.getParamsMap().put("p_productId",droppedProdCompSubCompValues[0]);                    operationBinding.getParamsMap().put("p_componentId",droppedProdCompSubCompValues[1]);                    operationBinding.getParamsMap().put("p_subComponentId",droppedProdCompSubCompValues[2]);                    Object result = operationBinding.execute();                  }                   }            }                        /* this.getCil1().setDisabled(false);            this.getCil1().setPartialSubmit(true); */                      return DnDAction.MOVE;        } catch (Exception ex) {          System.out.println("drop failed with : " + ex.getMessage());          ex.printStackTrace();                  /* this.getCil1().setDisabled(true); */          return DnDAction.NONE;          }    } Run jspx page and drop a Component or Subcomponent from Products Tree to UserComponents Tree Table.

    Read the article

  • Abstract class + Inheritance vs Interface

    - by RealityDysfunction
    Hello fellow programmers, I am reading a book on C# and the author is comparing Abstract classes and Interfaces. He claims that if you have the following "abstract class:" abstract class CloneableType { public abstract object Clone(); } Then you cannot do this: public class MiniVan : Car, CloneableType {} This, I understand. However he claims that because of this inability to do multiple inheritance that you should use an interface for CloneableType, like so: public interface ICloneable { object Clone(); } My question is, isn't this somewhat misleading, because you can create an abstract class which is "above" class Car with the method Clone, then have Car inherit that class and then Minivan will inherit Car with all these methods, CloneAble class - Car class - Minivan Class. What do you think? Thanks.

    Read the article

  • C++: Create abstract class with abstract method and override the method in a subclass

    - by Martijn Courteaux
    Hi, How to create in C++ an abstract class with some abstract methods that I want to override in a subclass? How should the .h file look? Is there a .cpp, if so how should it look? In Java it would look like this: abstract class GameObject { public abstract void update(); public abstract void paint(Graphics g); } class Player extends GameObject { @Override public void update() { // ... } @Override public void paint(Graphics g) { // ... } } // In my game loop: for (int i = 0; i < objects.size(); i++) { objects.get(i).update(); } for (int i = 0; i < objects.size(); i++) { objects.get(i).paint(g); } Translating this code to C++ is enough for me.

    Read the article

  • Abstract exception super type

    - by marcof
    If throwing System.Exception is considered so bad, why wasn't Exception made abstract in the first place? That way, it would not be possible to call: throw new Exception("Error occurred."); This would enforce using derived exceptions to provide more details about the error that occurred. For example, when I want to provide a custom exception hierarchy for a library, I usually declare an abstract base class for my exceptions: public abstract class CustomExceptionBase : Exception { /* some stuff here */ } And then some derived exception with a more specific purpose: public class DerivedCustomException : CustomExceptionBase { /* some more specific stuff here */ } Then when calling any library method, one could have this generic try/catch block to directly catch any error coming from the library: try { /* library calls here */ } catch (CustomExceptionBase ex) { /* exception handling */ } Is this a good practice? Would it be good if Exception was made abstract? EDIT : My point here is that even if an exception class is abstract, you can still catch it in a catch-all block. Making it abstract is only a way to forbid programmers to throw a "super-wide" exception. Usually, when you voluntarily throw an exception, you should know what type it is and why it happened. Thus enforcing to throw a more specific exception type.

    Read the article

  • Can't find a Windows Explorer alternative that has FULL-TREE View

    - by samJL
    I cannot find a Windows Explorer alternative that has full-tree view functionality like Path Finder on the Mac This is the type of view I am looking for (screenshot of Path Finder on Mac): By full-tree I mean: A tree view that includes files in addition to folders, and can be operated as its own pane-- not as a shared pane or attached pane which is characteristic of Q-Dir. Q-Dir and most others simply stick a folder tree pane on to a file list pane, which is not as useful (think Ruby on Rails application or anything with MVC-- I want to be able to pop open folders in the tree and have them stay open as I work between them). I have tried xplorer2 XYplorer Nexus File Free Commander muCommander CubicExplorer Double Commander Q-Dir Explorer++ Unreal Commander wxCommander Power Desk Directory Opus Has anyone seen a Windows app that has a full-tree view? I can't believe such a simple feature is so hard to find Thanks

    Read the article

  • make tree in scheme

    - by ???
    (define (entry tree) (car tree)) (define (left-branch tree) (cadr tree)) (define (right-branch tree) (caddr tree)) (define (make-tree entry left right) (list entry left right)) (define (mktree order items_list) (cond ((= (length items_list) 1) (make-tree (car items_list) '() '())) (else (insert2 order (car items_list) (mktree order (cdr items_list)))))) (define (insert2 order x t) (cond ((null? t) (make-tree x '() '())) ((order x (entry t)) (make-tree (entry t) (insert2 order x (left-branch t)) (right-branch t))) ((order (entry t) x ) (make-tree (entry t) (left-branch t) (insert2 order x (right-branch t)))) (else t))) The result is: (mktree (lambda (x y) (< x y)) (list 7 3 5 1 9 11)) (11 (9 (1 () (5 (3 () ()) (7 () ()))) ()) ()) But I'm trying to get: (7 (3 (1 () ()) (5 () ())) (9 () (11 () ()))) Where is the problem?

    Read the article

  • Figuring a max repetitive sub-tree in an object tree

    - by bonomo
    I am trying to solve a problem of finding a max repetitive sub-tree in an object tree. By the object tree I mean a tree where each leaf and node has a name. Each leaf has a type and a value of that type associated with that leaf. Each node has a set of leaves / nodes in certain order. Given an object tree that - we know - has a repetitive sub-tree in it. By repetitive I mean 2 or more sub-trees that are similar in everything (names/types/order of sub-elements) but the values of leaves. No nodes/leaves can be shared between sub-trees. Problem is to identify these sub-trees of the max height. I know that the exhaustive search can do the trick. I am rather looking for more efficient approach.

    Read the article

  • abstract class extends abstract class in php?

    - by user151841
    I am working on a simple abstract database class. In my usage of this class, I'll want to have some instance be a singleton. I was thinking of having a abstract class that is not a singleton, and then extend it into another abstract class that is a singleton. Is this possible? Recommended?

    Read the article

  • What are the differences between abstract classes, interfaces, and when to use them

    - by user66662
    Recently I have started to wrap my head around OOP, and I am now to the point where the more I read about the differences between Abstract classes and Interfaces the more confused I become. So far, neither can be instantiated. Interfaces are more or less structural blueprints that determine the skeleton and abstracts are different by being able to partially develop code. I would like to learn more about these through my specific situation. Here is a link to my first question if you would like a little more background information: What is a good design model for my new class? Here are two classes I created: class Ad { $title; $description $price; function get_data($website){ } function validate_price(){ } } class calendar_event { $title; $description $start_date; function get_data($website){ //guts } function validate_dates(){ //guts } } So, as you can see these classes are almost identical. Not shown here, but there are other functions, like get_zip(), save_to_database() that are common across my classes. I have also added other classes Cars and Pets which have all the common methods and of course properties specific to those objects (mileage, weight, for example). Now I have violated the DRY principle and I am managing and changing the same code across multiple files. I intend on having more classes like boats, horses, or whatever. So is this where I would use an interface or abstract class? From what I understand about abstract classes I would use a super class as a template with all of the common elements built into the abstract class, and then add only the items specifically needed in future classes. For example: abstract class content { $title; $description function get_data($website){ } function common_function2() { } function common_function3() { } } class calendar_event extends content { $start_date; function validate_dates(){ } } Or would I use an interface and, because these are so similar, create a structure that each of the subclasses are forced to use for integrity reasons, and leave it up to the end developer who fleshes out that class to be responsible for each of the details of even the common functions. my thinking there is that some 'common' functions may need to be tweaked in the future for the needs of their specific class. Despite all that above, if you believe I am misunderstanding the what and why of abstracts and interfaces altogether, by all means let a valid answer to be stop thinking in this direction and suggest the proper way to move forward! Thanks!

    Read the article

  • UML Class Diagram: Abstract or Interface?

    - by J Smith
    I am modeling a class diagram and have spotted an opportunity to simplify it slightly. What I want to know is, would this it be better to implement an abstract class or an interface? The scenario is this, I have the classes: Artist Genre Album Song All of which share the methods getName, setName, and getCount (playcount that is). Would it be best to create an abstract 'Music' class with the aforementioned abstract methods, or should I create an interface, since the classes that implement the interface have to include all of the interface's methods (I think, correct me if I'm wrong). I hope I've given enough detail, please ask questions if I haven't. Thanks!

    Read the article

  • Followup: Python 2.6, 3 abstract base class misunderstanding

    - by Aaron
    I asked a question at Python 2.6, 3 abstract base class misunderstanding. My problem was that python abstract base classes didn't work quite the way I expected them to. There was some discussion in the comments about why I would want to use ABCs at all, and Alex Martelli provided an excellent answer on why my use didn't work and how to accomplish what I wanted. Here I'd like to address why one might want to use ABCs, and show my test code implementation based on Alex's answer. tl;dr: Code after the 16th paragraph. In the discussion on the original post, statements were made along the lines that you don't need ABCs in Python, and that ABCs don't do anything and are therefore not real classes; they're merely interface definitions. An abstract base class is just a tool in your tool box. It's a design tool that's been around for many years, and a programming tool that is explicitly available in many programming languages. It can be implemented manually in languages that don't provide it. An ABC is always a real class, even when it doesn't do anything but define an interface, because specifying the interface is what an ABC does. If that was all an ABC could do, that would be enough reason to have it in your toolbox, but in Python and some other languages they can do more. The basic reason to use an ABC is when you have a number of classes that all do the same thing (have the same interface) but do it differently, and you want to guarantee that that complete interface is implemented in all objects. A user of your classes can rely on the interface being completely implemented in all classes. You can maintain this guarantee manually. Over time you may succeed. Or you might forget something. Before Python had ABCs you could guarantee it semi-manually, by throwing NotImplementedError in all the base class's interface methods; you must implement these methods in derived classes. This is only a partial solution, because you can still instantiate such a base class. A more complete solution is to use ABCs as provided in Python 2.6 and above. Template methods and other wrinkles and patterns are ideas whose implementation can be made easier with full-citizen ABCs. Another idea in the comments was that Python doesn't need ABCs (understood as a class that only defines an interface) because it has multiple inheritance. The implied reference there seems to be Java and its single inheritance. In Java you "get around" single inheritance by inheriting from one or more interfaces. Java uses the word "interface" in two ways. A "Java interface" is a class with method signatures but no implementations. The methods are the interface's "interface" in the more general, non-Java sense of the word. Yes, Python has multiple inheritance, so you don't need Java-like "interfaces" (ABCs) merely to provide sets of interface methods to a class. But that's not the only reason in software development to use ABCs. Most generally, you use an ABC to specify an interface (set of methods) that will likely be implemented differently in different derived classes, yet that all derived classes must have. Additionally, there may be no sensible default implementation for the base class to provide. Finally, even an ABC with almost no interface is still useful. We use something like it when we have multiple except clauses for a try. Many exceptions have exactly the same interface, with only two differences: the exception's string value, and the actual class of the exception. In many exception clauses we use nothing about the exception except its class to decide what to do; catching one type of exception we do one thing, and another except clause catching a different exception does another thing. According to the exception module's doc page, BaseException is not intended to be derived by any user defined exceptions. If ABCs had been a first class Python concept from the beginning, it's easy to imagine BaseException being specified as an ABC. But enough of that. Here's some 2.6 code that demonstrates how to use ABCs, and how to specify a list-like ABC. Examples are run in ipython, which I like much better than the python shell for day to day work; I only wish it was available for python3. Your basic 2.6 ABC: from abc import ABCMeta, abstractmethod class Super(): __metaclass__ = ABCMeta @abstractmethod def method1(self): pass Test it (in ipython, python shell would be similar): In [2]: a = Super() --------------------------------------------------------------------------- TypeError Traceback (most recent call last) /home/aaron/projects/test/<ipython console> in <module>() TypeError: Can't instantiate abstract class Super with abstract methods method1 Notice the end of the last line, where the TypeError exception tells us that method1 has not been implemented ("abstract methods method1"). That was the method designated as @abstractmethod in the preceding code. Create a subclass that inherits Super, implement method1 in the subclass and you're done. My problem, which caused me to ask the original question, was how to specify an ABC that itself defines a list interface. My naive solution was to make an ABC as above, and in the inheritance parentheses say (list). My assumption was that the class would still be abstract (can't instantiate it), and would be a list. That was wrong; inheriting from list made the class concrete, despite the abstract bits in the class definition. Alex suggested inheriting from collections.MutableSequence, which is abstract (and so doesn't make the class concrete) and list-like. I used collections.Sequence, which is also abstract but has a shorter interface and so was quicker to implement. First, Super derived from Sequence, with nothing extra: from abc import abstractmethod from collections import Sequence class Super(Sequence): pass Test it: In [6]: a = Super() --------------------------------------------------------------------------- TypeError Traceback (most recent call last) /home/aaron/projects/test/<ipython console> in <module>() TypeError: Can't instantiate abstract class Super with abstract methods __getitem__, __len__ We can't instantiate it. A list-like full-citizen ABC; yea! Again, notice in the last line that TypeError tells us why we can't instantiate it: __getitem__ and __len__ are abstract methods. They come from collections.Sequence. But, I want a bunch of subclasses that all act like immutable lists (which collections.Sequence essentially is), and that have their own implementations of my added interface methods. In particular, I don't want to implement my own list code, Python already did that for me. So first, let's implement the missing Sequence methods, in terms of Python's list type, so that all subclasses act as lists (Sequences). First let's see the signatures of the missing abstract methods: In [12]: help(Sequence.__getitem__) Help on method __getitem__ in module _abcoll: __getitem__(self, index) unbound _abcoll.Sequence method (END) In [14]: help(Sequence.__len__) Help on method __len__ in module _abcoll: __len__(self) unbound _abcoll.Sequence method (END) __getitem__ takes an index, and __len__ takes nothing. And the implementation (so far) is: from abc import abstractmethod from collections import Sequence class Super(Sequence): # Gives us a list member for ABC methods to use. def __init__(self): self._list = [] # Abstract method in Sequence, implemented in terms of list. def __getitem__(self, index): return self._list.__getitem__(index) # Abstract method in Sequence, implemented in terms of list. def __len__(self): return self._list.__len__() # Not required. Makes printing behave like a list. def __repr__(self): return self._list.__repr__() Test it: In [34]: a = Super() In [35]: a Out[35]: [] In [36]: print a [] In [37]: len(a) Out[37]: 0 In [38]: a[0] --------------------------------------------------------------------------- IndexError Traceback (most recent call last) /home/aaron/projects/test/<ipython console> in <module>() /home/aaron/projects/test/test.py in __getitem__(self, index) 10 # Abstract method in Sequence, implemented in terms of list. 11 def __getitem__(self, index): ---> 12 return self._list.__getitem__(index) 13 14 # Abstract method in Sequence, implemented in terms of list. IndexError: list index out of range Just like a list. It's not abstract (for the moment) because we implemented both of Sequence's abstract methods. Now I want to add my bit of interface, which will be abstract in Super and therefore required to implement in any subclasses. And we'll cut to the chase and add subclasses that inherit from our ABC Super. from abc import abstractmethod from collections import Sequence class Super(Sequence): # Gives us a list member for ABC methods to use. def __init__(self): self._list = [] # Abstract method in Sequence, implemented in terms of list. def __getitem__(self, index): return self._list.__getitem__(index) # Abstract method in Sequence, implemented in terms of list. def __len__(self): return self._list.__len__() # Not required. Makes printing behave like a list. def __repr__(self): return self._list.__repr__() @abstractmethod def method1(): pass class Sub0(Super): pass class Sub1(Super): def __init__(self): self._list = [1, 2, 3] def method1(self): return [x**2 for x in self._list] def method2(self): return [x/2.0 for x in self._list] class Sub2(Super): def __init__(self): self._list = [10, 20, 30, 40] def method1(self): return [x+2 for x in self._list] We've added a new abstract method to Super, method1. This makes Super abstract again. A new class Sub0 which inherits from Super but does not implement method1, so it's also an ABC. Two new classes Sub1 and Sub2, which both inherit from Super. They both implement method1 from Super, so they're not abstract. Both implementations of method1 are different. Sub1 and Sub2 also both initialize themselves differently; in real life they might initialize themselves wildly differently. So you have two subclasses which both "is a" Super (they both implement Super's required interface) although their implementations are different. Also remember that Super, although an ABC, provides four non-abstract methods. So Super provides two things to subclasses: an implementation of collections.Sequence, and an additional abstract interface (the one abstract method) that subclasses must implement. Also, class Sub1 implements an additional method, method2, which is not part of Super's interface. Sub1 "is a" Super, but it also has additional capabilities. Test it: In [52]: a = Super() --------------------------------------------------------------------------- TypeError Traceback (most recent call last) /home/aaron/projects/test/<ipython console> in <module>() TypeError: Can't instantiate abstract class Super with abstract methods method1 In [53]: a = Sub0() --------------------------------------------------------------------------- TypeError Traceback (most recent call last) /home/aaron/projects/test/<ipython console> in <module>() TypeError: Can't instantiate abstract class Sub0 with abstract methods method1 In [54]: a = Sub1() In [55]: a Out[55]: [1, 2, 3] In [56]: b = Sub2() In [57]: b Out[57]: [10, 20, 30, 40] In [58]: print a, b [1, 2, 3] [10, 20, 30, 40] In [59]: a, b Out[59]: ([1, 2, 3], [10, 20, 30, 40]) In [60]: a.method1() Out[60]: [1, 4, 9] In [61]: b.method1() Out[61]: [12, 22, 32, 42] In [62]: a.method2() Out[62]: [0.5, 1.0, 1.5] [63]: a[:2] Out[63]: [1, 2] In [64]: a[0] = 5 --------------------------------------------------------------------------- TypeError Traceback (most recent call last) /home/aaron/projects/test/<ipython console> in <module>() TypeError: 'Sub1' object does not support item assignment Super and Sub0 are abstract and can't be instantiated (lines 52 and 53). Sub1 and Sub2 are concrete and have an immutable Sequence interface (54 through 59). Sub1 and Sub2 are instantiated differently, and their method1 implementations are different (60, 61). Sub1 includes an additional method2, beyond what's required by Super (62). Any concrete Super acts like a list/Sequence (63). A collections.Sequence is immutable (64). Finally, a wart: In [65]: a._list Out[65]: [1, 2, 3] In [66]: a._list = [] In [67]: a Out[67]: [] Super._list is spelled with a single underscore. Double underscore would have protected it from this last bit, but would have broken the implementation of methods in subclasses. Not sure why; I think because double underscore is private, and private means private. So ultimately this whole scheme relies on a gentleman's agreement not to reach in and muck with Super._list directly, as in line 65 above. Would love to know if there's a safer way to do that.

    Read the article

  • Unit testing to prove balanced tree

    - by Darrel Hoffman
    I've just built a self-balancing tree (red-black) in Java (language should be irrelevant for this question though), and I'm trying to come up with a good means of testing that it's properly balanced. I've tested all the basic tree operations, but I can't think of a way to test that it is indeed well and truly balanced. I've tried inserting a large dictionary of words, both pre-sorted and un-sorted. With a balanced tree, those should take roughly the same amount of time, but an unbalanced tree would take significantly longer on the already-sorted list. But I don't know how to go about testing for that in any reasonable, reproducible way. (I've tried doing millisecond tests on these, but there's no noticeable difference - probably because my source data is too small.) Is there a better way to be sure that the tree is really balanced? Say, by looking at the tree after it's created and seeing how deep it goes? (That is, without modifying the tree itself by adding a depth field to each node, which is just wasteful if you don't need it for anything other than testing.)

    Read the article

  • Java - abstract class, equals(), and two subclasses

    - by msr
    Hello, I have an abstract class named Xpto and two subclasses that extend it named Person and Car. I have also a class named Test with main() and a method foo() that verifies if two persons or cars (or any object of a class that extends Xpto) are equals. Thus, I redefined equals() in both Person and Car classes. Two persons are equal when they have the same name and two cars are equal when they have the same registration. However, when I call foo() in the Test class I always get "false". I understand why: the equals() is not redefined in Xpto abstract class. So... how can I compare two persons or cars (or any object of a class that extends Xpto) in that foo() method? In summary, this is the code I have: public abstract class Xpto { } public class Person extends Xpto{ protected String name; public Person(String name){ this.name = name; } public boolean equals(Person p){ System.out.println("Person equals()?"); return this.name.compareTo(p.name) == 0 ? true : false; } } public class Car extends Xpto{ protected String registration; public Car(String registration){ this.registration = registration; } public boolean equals(Car car){ System.out.println("Car equals()?"); return this.registration.compareTo(car.registration) == 0 ? true : false; } } public class Teste { public static void foo(Xpto xpto1, Xpto xpto2){ if(xpto1.equals(xpto2)) System.out.println("xpto1.equals(xpto2) -> true"); else System.out.println("xpto1.equals(xpto2) -> false"); } public static void main(String argv[]){ Car c1 = new Car("ABC"); Car c2 = new Car("DEF"); Person p1 = new Person("Manel"); Person p2 = new Person("Manel"); foo(p1,p2); } }

    Read the article

  • Help to understand the abstract factory pattern

    - by Chobeat
    I'm learning the 23 design patterns of the GoF. I think I've found a way to understand and simplify how the Abstract Factory works but I would like to know if this is a correct assumption or if I am wrong. What I want to know is if we can see the result of the Abstract Factory method as a matrix of possible products where there's a Product for every "Concrete Factory" x "AbstractProduct" where the Concrete Factory is a single implementation among the implementations of an AbstractFactory and an AbstractProduct is an interface among the interfaces to create Products. Is this correct or am I missing something?

    Read the article

  • Using C# and gppg, how would I construct an abstract syntax tree?

    - by Rupert
    Is there a way to do this almost out-of-the-box? I could go and write a big method that would use the collected tokens to figure out which leaves should be put in which branches and in the end populate a TreeNode object, but since gppg already handled everything by using supplied regular expressions, I was wondering if there's an easier way? Even if not, any pointers as to how best to approach the problem of creating an AST would be appreciated. Apologies if I said anything silly, I'm only just beginning to play the compiler game. :)

    Read the article

  • VIM does not detect syntax of .ssh/config

    - by Erik
    On a plain Ubuntu installation (12.04 in my case) when I have no ~/.vimrc VIM does not detect syntax of .ssh/config. Syntax highlighting works, but it does not set the correct filetype. vi ~/.ssh/config :set syn? >syntax=conf When I do: set syn=sshconfig Then the syntax highlighting is as it should be. Why isn't the filetype automatically identified? And how can it be set automatically?

    Read the article

  • Max Value of a Multiway Tree in OCaml

    - by Trigork
    I'm an IT Student and kind of a newbie to OCaml Recently, studying for an exam I found this exercise. Given: type 'a tree = Tree of 'a * 'a tree list Define a function mtree : 'a tree -'a, that returns the greatest value of all the nodes in a multiway tree, following the usual order relation in OCaml (<=) I've come to do something like this below, which, of course, is not working. let rec mtree (Tree (r, sub)) = let max_node (Tree(a, l1)) (Tree(b, l2)) = if a >= b then (Tree(a, l1)) else (Tree(b, l2)) in List.fold_left max_node r sub;; After reading an answer to this I'm posting the fixed code. let rec mtree (Tree(r,sub)) = let max_node (Tree(a, l1)) (Tree(b, l2)) = if a >= b then a else b in List.fold_left (max_node) r (List.map mtree sub);; The idea is the same, fold the list comparing the nodes making use of my local function to do so and travel through the tree by calling the function itself over the nodes lists of the consecutive levels. Is still not working, though. Now complains about max_node in the fold_left part. Error: This expression has type 'a tree -> 'a tree -> 'a but an expression was expected of type 'a tree -> 'a tree -> 'a tree And here I'm definitely lost because I can't see why does it expects to return an 'a tree

    Read the article

  • HP to Cisco spanning tree root flapping

    - by Tim Brigham
    Per a recent question I recently configured both my HP (2x 2900) and Cisco (1x 3750) hardware to use MSTP for interoperability. I thought this was functional until I applied the change to the third device (HP switch 1 below) at which time the spanning tree root started flapping causing performance issues (5% packet loss) between my two HP switches. I'm not sure why. HP Switch 1 A4 connected to Cisco 1/0/1. HP Switch 2 B2 connected to Cisco 2/0/1. HP Switch 1 A2 connected to HP Switch 2 A1. I'd prefer the Cisco stack to act as the root. EDIT: There is one specific line - 'spanning-tree 1 path-cost 500000' in the HP switch 2 that I didn't add and was preexisting. I'm not sure if it could have the kind of impact that I'm describing. I'm more a security and monitoring guy then networking. EDIT 2: I'm starting to believe the problem lies in the fact that the value for my MST 0 instance on the Cisco is still at the default 32768. I worked up a diagram: This is based on every show command I could find for STP. I'll make this change after hours and see if it helps. Cisco 3750 Config: version 12.2 spanning-tree mode mst spanning-tree extend system-id spanning-tree mst configuration name mstp revision 1 instance 1 vlan 1, 40, 70, 100, 250 spanning-tree mst 1 priority 0 vlan internal allocation policy ascending interface TenGigabitEthernet1/1/1 switchport trunk encapsulation dot1q switchport mode trunk ! interface TenGigabitEthernet2/1/1 switchport trunk encapsulation dot1q switchport mode trunk ! interface Vlan1 no ip address ! interface Vlan100 ip address 192.168.100.253 255.255.255.0 ! Cisco 3750 show spanning tree: show spanning-tree MST0 Spanning tree enabled protocol mstp Root ID Priority 32768 Address 0004.ea84.5f80 Cost 200000 Port 53 (TenGigabitEthernet1/1/1) Hello Time 2 sec Max Age 20 sec Forward Delay 15 sec Bridge ID Priority 32768 (priority 32768 sys-id-ext 0) Address a44c.11a6.7c80 Hello Time 2 sec Max Age 20 sec Forward Delay 15 sec Interface Role Sts Cost Prio.Nbr Type ------------------- ---- --- --------- -------- -------------------------------- Te1/1/1 Root FWD 2000 128.53 P2p MST1 Spanning tree enabled protocol mstp Root ID Priority 1 Address a44c.11a6.7c80 This bridge is the root Hello Time 2 sec Max Age 20 sec Forward Delay 15 sec Bridge ID Priority 1 (priority 0 sys-id-ext 1) Address a44c.11a6.7c80 Hello Time 2 sec Max Age 20 sec Forward Delay 15 sec Interface Role Sts Cost Prio.Nbr Type ------------------- ---- --- --------- -------- -------------------------------- Te1/1/1 Desg FWD 2000 128.53 P2p Cisco 3750 show logging: %LINEPROTO-5-UPDOWN: Line protocol on Interface Vlan1, changed state to down %LINEPROTO-5-UPDOWN: Line protocol on Interface Vlan100, changed state to down %LINEPROTO-5-UPDOWN: Line protocol on Interface Vlan1, changed state to up %LINEPROTO-5-UPDOWN: Line protocol on Interface Vlan100, changed state to up %LINEPROTO-5-UPDOWN: Line protocol on Interface Vlan1, changed state to down %LINEPROTO-5-UPDOWN: Line protocol on Interface Vlan1, changed state to up HP Switch 1: ; J9049A Configuration Editor; Created on release #T.13.71 vlan 1 name "DEFAULT_VLAN" untagged 1-8,10,13-16,18-23,A1-A4 ip address 100.100.100.17 255.255.255.0 no untagged 9,11-12,17,24 exit vlan 100 name "192.168.100" untagged 9,11-12,17,24 tagged 1-8,10,13-16,18-23,A1-A4 no ip address exit vlan 21 name "Users_2" tagged 1,A1-A4 no ip address exit vlan 40 name "Cafe" tagged 1,4,7,A1-A4 no ip address exit vlan 250 name "Firewall" tagged 1,4,7,A1-A4 no ip address exit vlan 70 name "DMZ" tagged 1,4,7-8,13,A1-A4 no ip address exit spanning-tree spanning-tree config-name "mstp" spanning-tree config-revision 1 spanning-tree instance 1 vlan 1 40 70 100 250 password manager password operator HP Switch 1 show spanning tree: show spanning-tree Multiple Spanning Tree (MST) Information STP Enabled : Yes Force Version : MSTP-operation IST Mapped VLANs : 2-39,41-69,71-99,101-249,251-4094 Switch MAC Address : 0021f7-126580 Switch Priority : 32768 Max Age : 20 Max Hops : 20 Forward Delay : 15 Topology Change Count : 363,490 Time Since Last Change : 14 hours CST Root MAC Address : 0004ea-845f80 CST Root Priority : 32768 CST Root Path Cost : 200000 CST Root Port : 1 IST Regional Root MAC Address : 0021f7-126580 IST Regional Root Priority : 32768 IST Regional Root Path Cost : 0 IST Remaining Hops : 20 Root Guard Ports : TCN Guard Ports : BPDU Protected Ports : BPDU Filtered Ports : PVST Protected Ports : PVST Filtered Ports : | Prio | Designated Hello Port Type | Cost rity State | Bridge Time PtP Edge ----- --------- + --------- ---- ---------- + ------------- ---- --- ---- A1 | Auto 128 Disabled | A2 10GbE-CX4 | 2000 128 Forwarding | 0021f7-126580 2 Yes No A3 10GbE-CX4 | Auto 128 Disabled | A4 10GbE-SR | Auto 128 Disabled | HP Switch 1 Logging: I removed the date / time fields since they are inaccurate (no NTP configured on these switches) 00839 stp: MSTI 1 Root changed from 0:a44c11-a67c80 to 32768:0021f7-126580 00839 stp: MSTI 1 Root changed from 32768:0021f7-126580 to 0:a44c11-a67c80 00842 stp: MSTI 1 starved for an MSTI Msg Rx on port A4 from 0:a44c11-a67c80 00839 stp: MSTI 1 Root changed from 0:a44c11-a67c80 to 32768:0021f7-126580 00839 stp: MSTI 1 Root changed from 32768:0021f7-126580 to 0:a44c11-a67c80 00839 stp: MSTI 1 Root changed from 0:a44c11-a67c80 to ... HP Switch 2 Configuration: ; J9146A Configuration Editor; Created on release #W.14.49 vlan 1 name "DEFAULT_VLAN" untagged 1,3-17,21-24,A1-A2,B2 ip address 100.100.100.36 255.255.255.0 no untagged 2,18-20,B1 exit vlan 100 name "192.168.100" untagged 2,18-20 tagged 1,3-17,21-24,A1-A2,B1-B2 no ip address exit vlan 21 name "Users_2" tagged 1,A1-A2,B2 no ip address exit vlan 40 name "Cafe" tagged 1,13-14,16,A1-A2,B2 no ip address exit vlan 250 name "Firewall" tagged 1,13-14,16,A1-A2,B2 no ip address exit vlan 70 name "DMZ" tagged 1,13-14,16,A1-A2,B2 no ip address exit logging 192.168.100.18 spanning-tree spanning-tree 1 path-cost 500000 spanning-tree config-name "mstp" spanning-tree config-revision 1 spanning-tree instance 1 vlan 1 40 70 100 250 HP Switch 2 Spanning Tree: show spanning-tree Multiple Spanning Tree (MST) Information STP Enabled : Yes Force Version : MSTP-operation IST Mapped VLANs : 2-39,41-69,71-99,101-249,251-4094 Switch MAC Address : 0024a8-cd6000 Switch Priority : 32768 Max Age : 20 Max Hops : 20 Forward Delay : 15 Topology Change Count : 21,793 Time Since Last Change : 14 hours CST Root MAC Address : 0004ea-845f80 CST Root Priority : 32768 CST Root Path Cost : 200000 CST Root Port : A1 IST Regional Root MAC Address : 0021f7-126580 IST Regional Root Priority : 32768 IST Regional Root Path Cost : 2000 IST Remaining Hops : 19 Root Guard Ports : TCN Guard Ports : BPDU Protected Ports : BPDU Filtered Ports : PVST Protected Ports : PVST Filtered Ports : | Prio | Designated Hello Port Type | Cost rity State | Bridge Time PtP Edge ----- --------- + --------- ---- ---------- + ------------- ---- --- ---- A1 10GbE-CX4 | 2000 128 Forwarding | 0021f7-126580 2 Yes No A2 10GbE-CX4 | Auto 128 Disabled | B1 SFP+SR | 2000 128 Forwarding | 0024a8-cd6000 2 Yes No B2 | Auto 128 Disabled | HP Switch 2 Logging: I removed the date / time fields since they are inaccurate (no NTP configured on these switches) 00839 stp: CST Root changed from 32768:0021f7-126580 to 32768:0004ea-845f80 00839 stp: IST Root changed from 32768:0021f7-126580 to 32768:0024a8-cd6000 00839 stp: CST Root changed from 32768:0004ea-845f80 to 32768:0024a8-cd6000 00839 stp: CST Root changed from 32768:0024a8-cd6000 to 32768:0004ea-845f80 00839 stp: CST Root changed from 32768:0004ea-845f80 to 32768:0024a8-cd6000 00435 ports: port B1 is Blocked by STP 00839 stp: CST Root changed from 32768:0024a8-cd6000 to 32768:0021f7-126580 00839 stp: IST Root changed from 32768:0024a8-cd6000 to 32768:0021f7-126580 00839 stp: CST Root changed from 32768:0021f7-126580 to 32768:0004ea-845f80

    Read the article

  • If you had to reinvent a new syntax for regular expressions, what would it look like?

    - by Timwi
    Regular expressions as they are today are pretty much as concise and compact as they can be. Consequently, they are often criticised for being unreadable and hard to debug. If you had to reinvent a new syntax for regular expressions, what would it look like? Do you prefer the concise syntax they already have (or a different but similarly concise syntax)? If so, please justify why you think regular expressions deserve to be this concise, but your favourite programming language doesn’t (unless it’s Perl). Or do you think regular expressions should have a slightly more spaced-out syntax and look a bit more like operators and syntax elements normally do in programming languages? If so, provide examples of what you think the syntax should look like, and justify why it is better than the current syntax. Or do you think there shouldn’t even be a special syntax for regular expressions, and instead they should be constructed from syntax elements already present in the programming language? If so, give examples of a syntax that might be used to construct such regular expressions.

    Read the article

  • drawing hierarchical tree with orthogonal lines ( HV-Drawing – Binary Tree)

    - by user267530
    Hi I need to work on drawing a hierarchical tree structure (HV-Drawing – Binary Tree) with orthogonal lines(straight rectangular connecting lines) between root and children ( like the following: http://lab.kapit.fr/display/visualizationlayouts/Hierarchical+Tree+layout ). I want to know if there are any open source examples of the algorithm of drawing trees like that so that I can implement the same algorithm in actionscript. Thanks Palash

    Read the article

1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >