Search Results

Search found 1102 results on 45 pages for 'recurrence relation'.

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

  • SQL Alchemy related Objects Error

    - by alex
    from sqlalchemy.orm import relation, backref from sqlalchemy import Table, Column, Integer, String, MetaData, ForeignKey, Date, Sequence from sqlalchemy.ext.declarative import declarative_base Base = declarative_base() class GUI_SCENARIO(Base): __tablename__ = 'GUI_SCENARIO' Scenario_ID = Column(Integer, primary_key=True) Definition_Date = Column(Date) guiScenarioDefinition = relation('GUI_SCENARIO_DEFINITION', order_by='GUI_SCENARIO_DEFINITION.Scenario_Definition_ID', backref='guiScenario') def __init__(self, Scenario_ID=None, Definition_Date=None): self.Scenario_ID = Scenario_ID self.Definition_Date = Definition_Date class GUI_SCENARIO_DEFINITION(Base): __tablename__='GUI_SCENARIO_DEFINITION' Scenario_Definition_ID = Column(Integer, Sequence('Scenario_Definition_ID_SEQ'), primary_key=True) Scenario_FK = Column(Integer, ForeignKey('GUI_SCENARIO.Scenario_ID')) Definition_Date=Column(Date) guiScenario = relation(GUI_SCENARIO, backref=backref('guiScenarioDefinition', order_by=Scenario_Definition_ID)) def __init__(self, Scenario_FK, Definition_Date): self.Scenario_FK = Scenario_FK self.Definition_Date = Definition_Date guiScenario = relation(GUI_SCENARIO, backref=backref('guiScenarioDefinition', order_by=Scenario_Definition_ID)) tableNameScenario = "GUI_SCENARIO" scenarioClass = getattr(MappingTablesScenario, tableNameScenario) tableScenario = Table(tableNameScenario, meta, autoload=True) mapper(scenarioClass, tableScenario) scenarioName = scenarioDefinition.name scenarioDefinitionDate = datetime.today() newScenario = MappingTablesScenario.GUI_SCENARIO(scenarioName, scenarioDefinitionDate) print newScenario.guiScenarioDefinition If I try to get the objects related to a scenarioObject, I always get this error: AttributeError: 'GUI_SCENARIO' object has no attribute 'guiScenarioDefinition' Does anyone know, why I get this error?

    Read the article

  • Django filter bool not iterable

    - by dana
    I want to filter all Relation Objects where (relation= following relation in a virtual community) the date one has initiated the following is in the past, related to the moment now. The following declaration seems to be wrong, as a bool object is not iterable. Is there another way to do that? d = Relations.objects.filter(date_follow < datetime.now())

    Read the article

  • How to test if a doctrine records has any relations that are used

    - by murze
    Hi, I'm using a doctrine table that has several optional relations (of types Doctrine_Relation_Association and Doctrine_Relation_ForeignKey) with other tables. How can I test if a record from that table has connections with records from the related table. Here is an example to make my question more clear. Assume that you have a User and a user has a many to many relation with Usergroups and a User can have one Userrole How can I test if a give user is part of any Usergroups or has a role. The solution starts I believe with $relations = Doctrine_Core::getTable('User')->getRelations(); $user = Doctrine_Core::getTable('User')->findOne(1); foreach($relations as $relation) { //here should go a test if the user has a related record for this relation if ($relation instanceof Doctrine_Relation_Association) { //here the related table probably has more then one foreign key (ex. user_id and group_id) } if ($relation instanceof Doctrine_Relation_ForeignKey) { //here the related table probably has the primary key of this table (id) as a foreign key (user_id) } } //true or false echo $result I'm looking for a general solution that will work no matter how many relations there are between user and other tables. Thanks!

    Read the article

  • Copy a Doctrine object with all relations

    - by elManolo
    I want to copy a record with all his relations. I'm trying with: $o = Doctrine::getTable('Table')->Find(x); $copy = $object->copy(); $relations = $o->getRelations(); foreach ($relations as $name => $relation) { $copy->$relation = $object->$relation->copy(); } $copy->save(); This code doesn't works, but I think it's on the way.

    Read the article

  • Selecting rows with references across tables in SQLite 3

    - by ChristianK
    Hey there, I have a problem with a SQLite photo/album database. The database contains 3 tables: Albums id name hide -------------------------- 1 Holiday 2010 1 2 Day Trip 0 Photos id file ----------------- 1 photo1.jpg 2 photo2.jpg 3 photo3.jpg 4 photo4.jpg Relation (connects photos with albums) album photo ----------------- 1 1 1 2 2 3 2 1 A photo can be assigned to zero, one or several albums. Each album has a column 'hide' that indicates, whether the photos of this album should be ignored. I'm trying to find a SELECT query that returns all photos that are not assigned to an album + all the photos that are in albums which are not hidden (i.e. that have their 'hide' value set to 0). I came up with a query that selects photos in visible albums, but I don't know how to include the photos that are not assigned to an album. SELECT file FROM photos, albums, relation WHERE photos.id = relation.photo AND albums.id = relation.album AND albums.hide = 0 This query returns photo3.jpg and the required result would be photo3.jpg photo4.jpg because photo4.jpg is not assigned to album in the Relation table. Do you know how to solve this? Thank you very much for your help!

    Read the article

  • Core Data not-reverse relationship subquery

    - by user561485
    Hi, I have the following entities in CoreData: Village - villageID Bookmark - (relation) village There are multiple villages with each an unique villageID. I have a entity Bookmark which only has a relation to a Village entity; it isn't possible to make a reverse relation. Now I would like to get the village entities where there exists a Bookmark relation. I've red something about subqueries, but I can't get it right for this situation. It must be something like: Village.villageID IN (Bookmark.village.villageID) It isn't possible to get first all the Bookmarks and then loop to get all the Villages, because of the design of the framework. Can this be done in CoreData (I presume the answer is "Yes, of course!") and how?

    Read the article

  • Dictionary not deserializing

    - by Shadow
    I'm having a problem where one Dictionary in my project is either not serializing or not deserializing. After deserializing, the data I serialized is simply not in the object. Here's the relevant snip of the class being serialized: class Person : ISerializable { private Dictionary<Relation,List<int>> Relationships = new Dictionary<Relation,List<int>>(); public Person(SerializationInfo info, StreamingContext context) { this.Relationships = (Dictionary<Relation, List<int>>) info.GetValue("Relationships", typeof(Dictionary<Relation, List<int>>)); } public void GetObjectData(SerializationInfo info, StreamingContext context) { info.AddValue("Relationships", this.Relationships); } } Note, this is binary serialization. Everything else in the project serializes and deserialzes correctly.

    Read the article

  • NHibernate Conventions

    - by Ricardo Peres
    Introduction It seems that nowadays everyone loves conventions! Not the ones that you go to, but the ones that you use, that is! It just happens that NHibernate also supports conventions, and we’ll see exactly how. Conventions in NHibernate are supported in two ways: Naming of tables and columns when not explicitly indicated in the mappings; Full domain mapping. Naming of Tables and Columns Since always NHibernate has supported the concept of a naming strategy. A naming strategy in NHibernate converts class and property names to table and column names and vice-versa, when a name is not explicitly supplied. In concrete, it must be a realization of the NHibernate.Cfg.INamingStrategy interface, of which NHibernate includes two implementations: DefaultNamingStrategy: the default implementation, where each column and table are mapped to identically named properties and classes, for example, “MyEntity” will translate to “MyEntity”; ImprovedNamingStrategy: underscores (_) are used to separate Pascal-cased fragments, for example, entity “MyEntity” will be mapped to a “my_entity” table. The naming strategy can be defined at configuration level (the Configuration instance) by calling the SetNamingStrategy method: 1: cfg.SetNamingStrategy(ImprovedNamingStrategy.Instance); Both the DefaultNamingStrategy and the ImprovedNamingStrategy classes offer singleton instances in the form of Instance static fields. DefaultNamingStrategy is the one NHibernate uses, if you don’t specify one. Domain Mapping In mapping by code, we have the choice of relying on conventions to do the mapping automatically. This means a class will inspect our classes and decide how they will relate to the database objects. The class that handles conventions is NHibernate.Mapping.ByCode.ConventionModelMapper, a specialization of the base by code mapper, NHibernate.Mapping.ByCode.ModelMapper. The ModelMapper relies on an internal SimpleModelInspector to help it decide what and how to map, but the mapper lets you override its decisions.  You apply code conventions like this: 1: //pick the types that you want to map 2: IEnumerable<Type> types = Assembly.GetExecutingAssembly().GetExportedTypes(); 3:  4: //conventions based mapper 5: ConventionModelMapper mapper = new ConventionModelMapper(); 6:  7: HbmMapping mapping = mapper.CompileMappingFor(types); 8:  9: //the one and only configuration instance 10: Configuration cfg = ...; 11: cfg.AddMapping(mapping); This is a very simple example, it lacks, at least, the id generation strategy, which you can add by adding an event handler like this: 1: mapper.BeforeMapClass += (IModelInspector modelInspector, Type type, IClassAttributesMapper classCustomizer) => 2: { 3: classCustomizer.Id(x => 4: { 5: //set the hilo generator 6: x.Generator(Generators.HighLow); 7: }); 8: }; The mapper will fire events like this whenever it needs to get information about what to do. And basically this is all it takes to automatically map your domain! It will correctly configure many-to-one and one-to-many relations, choosing bags or sets depending on your collections, will get the table and column names from the naming strategy we saw earlier and will apply the usual defaults to all properties, such as laziness and fetch mode. However, there is at least one thing missing: many-to-many relations. The conventional mapper doesn’t know how to find and configure them, which is a pity, but, alas, not difficult to overcome. To start, for my projects, I have this rule: each entity exposes a public property of type ISet<T> where T is, of course, the type of the other endpoint entity. Extensible as it is, NHibernate lets me implement this very easily: 1: mapper.IsOneToMany((MemberInfo member, Boolean isLikely) => 2: { 3: Type sourceType = member.DeclaringType; 4: Type destinationType = member.GetMemberFromDeclaringType().GetPropertyOrFieldType(); 5:  6: //check if the property is of a generic collection type 7: if ((destinationType.IsGenericCollection() == true) && (destinationType.GetGenericArguments().Length == 1)) 8: { 9: Type destinationEntityType = destinationType.GetGenericArguments().Single(); 10:  11: //check if the type of the generic collection property is an entity 12: if (mapper.ModelInspector.IsEntity(destinationEntityType) == true) 13: { 14: //check if there is an equivalent property on the target type that is also a generic collection and points to this entity 15: PropertyInfo collectionInDestinationType = destinationEntityType.GetProperties().Where(x => (x.PropertyType.IsGenericCollection() == true) && (x.PropertyType.GetGenericArguments().Length == 1) && (x.PropertyType.GetGenericArguments().Single() == sourceType)).SingleOrDefault(); 16:  17: if (collectionInDestinationType != null) 18: { 19: return (false); 20: } 21: } 22: } 23:  24: return (true); 25: }); 26:  27: mapper.IsManyToMany((MemberInfo member, Boolean isLikely) => 28: { 29: //a relation is many to many if it isn't one to many 30: Boolean isOneToMany = mapper.ModelInspector.IsOneToMany(member); 31: return (!isOneToMany); 32: }); 33:  34: mapper.BeforeMapManyToMany += (IModelInspector modelInspector, PropertyPath member, IManyToManyMapper collectionRelationManyToManyCustomizer) => 35: { 36: Type destinationEntityType = member.LocalMember.GetPropertyOrFieldType().GetGenericArguments().First(); 37: //set the mapping table column names from each source entity name plus the _Id sufix 38: collectionRelationManyToManyCustomizer.Column(destinationEntityType.Name + "_Id"); 39: }; 40:  41: mapper.BeforeMapSet += (IModelInspector modelInspector, PropertyPath member, ISetPropertiesMapper propertyCustomizer) => 42: { 43: if (modelInspector.IsManyToMany(member.LocalMember) == true) 44: { 45: propertyCustomizer.Key(x => x.Column(member.LocalMember.DeclaringType.Name + "_Id")); 46:  47: Type sourceType = member.LocalMember.DeclaringType; 48: Type destinationType = member.LocalMember.GetPropertyOrFieldType().GetGenericArguments().First(); 49: IEnumerable<String> names = new Type[] { sourceType, destinationType }.Select(x => x.Name).OrderBy(x => x); 50:  51: //set inverse on the relation of the alphabetically first entity name 52: propertyCustomizer.Inverse(sourceType.Name == names.First()); 53: //set mapping table name from the entity names in alphabetical order 54: propertyCustomizer.Table(String.Join("_", names)); 55: } 56: }; We have to understand how the conventions mapper thinks: For each collection of entities found, it will ask the mapper if it is a one-to-many; in our case, if the collection is a generic one that has an entity as its generic parameter, and the generic parameter type has a similar collection, then it is not a one-to-many; Next, the mapper will ask if the collection that it now knows is not a one-to-many is a many-to-many; Before a set is mapped, if it corresponds to a many-to-many, we set its mapping table. Now, this is tricky: because we have no way to maintain state, we sort the names of the two endpoint entities and we combine them with a “_”; for the first alphabetical entity, we set its relation to inverse – remember, on a many-to-many relation, only one endpoint must be marked as inverse; finally, we set the column name as the name of the entity with an “_Id” suffix; Before the many-to-many relation is processed, we set the column name as the name of the other endpoint entity with the “_Id” suffix, as we did for the set. And that’s it. With these rules, NHibernate will now happily find and configure many-to-many relations, as well as all the others. You can wrap this in a new conventions mapper class, so that it is more easily reusable: 1: public class ManyToManyConventionModelMapper : ConventionModelMapper 2: { 3: public ManyToManyConventionModelMapper() 4: { 5: base.IsOneToMany((MemberInfo member, Boolean isLikely) => 6: { 7: return (this.IsOneToMany(member, isLikely)); 8: }); 9:  10: base.IsManyToMany((MemberInfo member, Boolean isLikely) => 11: { 12: return (this.IsManyToMany(member, isLikely)); 13: }); 14:  15: base.BeforeMapManyToMany += this.BeforeMapManyToMany; 16: base.BeforeMapSet += this.BeforeMapSet; 17: } 18:  19: protected virtual Boolean IsManyToMany(MemberInfo member, Boolean isLikely) 20: { 21: //a relation is many to many if it isn't one to many 22: Boolean isOneToMany = this.ModelInspector.IsOneToMany(member); 23: return (!isOneToMany); 24: } 25:  26: protected virtual Boolean IsOneToMany(MemberInfo member, Boolean isLikely) 27: { 28: Type sourceType = member.DeclaringType; 29: Type destinationType = member.GetMemberFromDeclaringType().GetPropertyOrFieldType(); 30:  31: //check if the property is of a generic collection type 32: if ((destinationType.IsGenericCollection() == true) && (destinationType.GetGenericArguments().Length == 1)) 33: { 34: Type destinationEntityType = destinationType.GetGenericArguments().Single(); 35:  36: //check if the type of the generic collection property is an entity 37: if (this.ModelInspector.IsEntity(destinationEntityType) == true) 38: { 39: //check if there is an equivalent property on the target type that is also a generic collection and points to this entity 40: PropertyInfo collectionInDestinationType = destinationEntityType.GetProperties().Where(x => (x.PropertyType.IsGenericCollection() == true) && (x.PropertyType.GetGenericArguments().Length == 1) && (x.PropertyType.GetGenericArguments().Single() == sourceType)).SingleOrDefault(); 41:  42: if (collectionInDestinationType != null) 43: { 44: return (false); 45: } 46: } 47: } 48:  49: return (true); 50: } 51:  52: protected virtual new void BeforeMapManyToMany(IModelInspector modelInspector, PropertyPath member, IManyToManyMapper collectionRelationManyToManyCustomizer) 53: { 54: Type destinationEntityType = member.LocalMember.GetPropertyOrFieldType().GetGenericArguments().First(); 55: //set the mapping table column names from each source entity name plus the _Id sufix 56: collectionRelationManyToManyCustomizer.Column(destinationEntityType.Name + "_Id"); 57: } 58:  59: protected virtual new void BeforeMapSet(IModelInspector modelInspector, PropertyPath member, ISetPropertiesMapper propertyCustomizer) 60: { 61: if (modelInspector.IsManyToMany(member.LocalMember) == true) 62: { 63: propertyCustomizer.Key(x => x.Column(member.LocalMember.DeclaringType.Name + "_Id")); 64:  65: Type sourceType = member.LocalMember.DeclaringType; 66: Type destinationType = member.LocalMember.GetPropertyOrFieldType().GetGenericArguments().First(); 67: IEnumerable<String> names = new Type[] { sourceType, destinationType }.Select(x => x.Name).OrderBy(x => x); 68:  69: //set inverse on the relation of the alphabetically first entity name 70: propertyCustomizer.Inverse(sourceType.Name == names.First()); 71: //set mapping table name from the entity names in alphabetical order 72: propertyCustomizer.Table(String.Join("_", names)); 73: } 74: } 75: } Conclusion Of course, there is much more to mapping than this, I suggest you look at all the events and functions offered by the ModelMapper to see where you can hook for making it behave the way you want. If you need any help, just let me know!

    Read the article

  • How to implement child-parent aggregation link in C++?

    - by Giorgio
    Suppose that I have three classes P, C1, C2, composition (strong aggregation) relations between P <>- C1 and P <>- C2, i.e. every instance of P contains an instance of C1 and an instance of C2, which are destroyed when the parent P instance is destroyed. an association relation between instances of C1 and C2 (not necessarily between children of the same P). To implement this, in C++ I normally define three classes P, C1, C2, define two member variables of P of type boost::shared_ptr<C1>, boost::shared_ptr<C2>, and initialize them with newly created objects in P's constructor, implement the relation between C1 and C2 using a boost::weak_ptr<C2> member variable in C1 and a boost::weak_ptr<C1> member variable in C2 that can be set later via appropriate methods, when the relation is established. Now, I also would like to have a link from each C1 and C2 object to its P parent object. What is a good way to implement this? My current idea is to use a simple constant raw pointer (P * const) that is set from the constructor of P (which, in turn, calls the constructors of C1 and C2), i.e. something like: class C1 { public: C1(P * const p, ...) : paren(p) { ... } private: P * const parent; ... }; class P { public: P(...) : childC1(new C1(this, ...)) ... { ... } private: boost::shared_ptr<C1> childC1; ... }; Honestly I see no risk in using a private constant raw pointer in this way but I know that raw pointers are often frowned upon in C++ so I was wondering if there is an alternative solution.

    Read the article

  • [EF + ORACLE] Updating and Deleting Entities

    - by JTorrecilla
    Prologue In previous chapters we have seen how to insert data through EF, with and without sequences. In this one, we are going to see how to Update and delete Data from the DB. Updating data The update of the Entity Data (properties) is a very common and easy action. Before of change any of the properties of the Entity, we can check the EntityState property, and we can see that is EntityState.Unchanged.   For making an update it is needed to get the Entity which will be modified. In the following example, I use the GetEmployeeByNumber to get a valid Entity: 1: EMPLEADOS emp=GetEmployeeByNumber(2); 2: emp.Name="a"; 3: emp.Phone="2"; 4: emp.Mail="aa"; After modifying the desired properties of the Entity, we are going to check again Entitystate property, which now has the EntityState.Modified value. To persist the changes to the DB is necessary to invoke the SaveChanges function of our context. 1: context.SaveChanges(); After modifying the desired properties of the Entity, we are going to check again Entitystate property, which now has the EntityState.Modified value. To persist the changes to the DB is necessary to invoke the SaveChanges function of our context. If we check again the EntityState property we will see that the value will be EntityState.Unchanged.   Deleting Data Another easy action is to delete an Entity.   The first step to delete an Entity from the DB is to select the entity: 1: CLIENTS selectedClient = GetClientByNumber(15); 2: context.CLIENTES.DeleteObject(clienteSeleccionado); Before invoking the DeleteObject function, we will check EntityStet which value must be EntityState.Unchanged. After deleting the object, the state will be changed to EntitySate.Deleted. To commit the action we have to invoke the SaveChanges function. Aftar that, the EntityState property will be EntityState.Detached. Cascade Entity Framework lets cascade updates and deletes, although I never see cascade updates. What is a cascade delete? A cascade delete is an action that allows to delete all the related object to the object we desire to delete. This option could be established in the DB manager, or it could be in the EF model designer. For example: With a given relation (1-N) between clients and requests. The common situation must be to let delete those clients whose have no requests. If we select the relation between both entities, and press the second mouse button, we can see the properties panel of the relation. The props are: This grid shows the relations indicating the Master table(Clients) and the end point (Cabecera or Requests) The property “End 1 OnDelete” indicates the action to do when a Entity from the Master will be deleted. There are two options: - None: No action will be done, it is said, if a Entity has details entities it could not be deleted. - Cascade: It will delete all related entities to the master Entity. If we enable the cascade delete in a relation, and we invoke the DeleteObject function of the set, we could observe that all the related object indicates a Entitystate.Deleted state. Like an update, insert or common delete, until we commit the changes with SaveChanges function, the data would not be commited. Si habilitamos el borrado en cascada de una relación, e invocamos a la función DeleteObject del conjunto, podremos observar que todas las entidades de Detalle (de la relación indicada) presentan el valor EntityState.Deleted en la propiedad EntityState. Del mismo modo que en el borrado, inserción o actualización, hasta que no se invoque al método SaveChanges, los cambios no van a ser confirmados en la Base de Datos. Finally In this chapter we have seen how to update a Entity, how to delete an Entity and how to implement Cascade Deleting through EF. In next chapters we will see how to query the DB data.

    Read the article

  • LaTeX limitation?

    - by Jayen
    Hi, I've hit an annoying problem in LaTeX. I've got a tex file of about 1000 lines. I've already got a few figures, but when I try to add another figure, It barfs with: ! Undefined control sequence. <argument> ... \sf@size \z@ \selectfont \@currbox l.937 \begin{figure}[t] If I move the figure to other parts of the file, I can get similar errors on different lines: ! Undefined control sequence. <argument> ... \sf@size \z@ \selectfont \@currbox l.657 \paragraph {A Centering Algorithm} If I comment out the figure, all is ok. %\begin{figure}[t] % \caption{Example decision tree, from Reiter and Dale [2000]} % \label{fig:relation-decision-tree} % \centering % \includegraphics[keepaspectratio=true]{./relation-decision-tree.eps} %\end{figure} If I keep just the begin and end like: \begin{figure}%[t] % \caption{Example decision tree, from Reiter and Dale [2000]} % \label{fig:relation-decision-tree} % \centering % \includegraphics[keepaspectratio=true]{./relation-decision-tree.eps} \end{figure} I get: ! Undefined control sequence. <argument> ... \sf@size \z@ \selectfont \@currbox l.942 \end {figure} At first, I thought maybe LaTeX has hit some limit, and I tried playing with the ulimits, but that didn't help. Any ideas? i've got other figures with graphics already. my preamble looks like: \documentclass[acmcsur,acmnow]{acmtrans2n} \usepackage{array} \usepackage{lastpage} \usepackage{pict2e} \usepackage{amsmath} \usepackage{varioref} \usepackage{epsfig} \usepackage{graphics} \usepackage{qtree} \usepackage{rotating} \usepackage{tree-dvips} \usepackage{mdwlist} \makecompactlist{quote*}{quote} \usepackage{verbatim} \usepackage{ulem}

    Read the article

  • Creating self-referential tables with polymorphism in SQLALchemy

    - by Jace
    I'm trying to create a db structure in which I have many types of content entities, of which one, a Comment, can be attached to any other. Consider the following: from datetime import datetime from sqlalchemy import create_engine from sqlalchemy import Column, ForeignKey from sqlalchemy import Unicode, Integer, DateTime from sqlalchemy.orm import relation, backref from sqlalchemy.ext.declarative import declarative_base Base = declarative_base() class Entity(Base): __tablename__ = 'entities' id = Column(Integer, primary_key=True) created_at = Column(DateTime, default=datetime.utcnow, nullable=False) edited_at = Column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False) type = Column(Unicode(20), nullable=False) __mapper_args__ = {'polymorphic_on': type} # <...insert some models based on Entity...> class Comment(Entity): __tablename__ = 'comments' __mapper_args__ = {'polymorphic_identity': u'comment'} id = Column(None, ForeignKey('entities.id'), primary_key=True) _idref = relation(Entity, foreign_keys=id, primaryjoin=id == Entity.id) attached_to_id = Column(Integer, ForeignKey('entities.id'), nullable=False) #attached_to = relation(Entity, remote_side=[Entity.id]) attached_to = relation(Entity, foreign_keys=attached_to_id, primaryjoin=attached_to_id == Entity.id, backref=backref('comments', cascade="all, delete-orphan")) text = Column(Unicode(255), nullable=False) engine = create_engine('sqlite://', echo=True) Base.metadata.bind = engine Base.metadata.create_all(engine) This seems about right, except SQLAlchemy doesn't like having two foreign keys pointing to the same parent. It says ArgumentError: Can't determine join between 'entities' and 'comments'; tables have more than one foreign key constraint relationship between them. Please specify the 'onclause' of this join explicitly. How do I specify onclause?

    Read the article

  • Suggestions of the easiest algorithms for some Graph operations

    - by Nazgulled
    Hi, The deadline for this project is closing in very quickly and I don't have much time to deal with what it's left. So, instead of looking for the best (and probably more complicated/time consuming) algorithms, I'm looking for the easiest algorithms to implement a few operations on a Graph structure. The operations I'll need to do is as follows: List all users in the graph network given a distance X List all users in the graph network given a distance X and the type of relation Calculate the shortest path between 2 users on the graph network given a type of relation Calculate the maximum distance between 2 users on the graph network Calculate the most distant connected users on the graph network A few notes about my Graph implementation: The edge node has 2 properties, one is of type char and another int. They represent the type of relation and weight, respectively. The Graph is implemented with linked lists, for both the vertices and edges. I mean, each vertex points to the next one and each vertex also points to the head of a different linked list, the edges for that specific vertex. What I know about what I need to do: I don't know if this is the easiest as I said above, but for the shortest path between 2 users, I believe the Dijkstra algorithm is what people seem to recommend pretty often so I think I'm going with that. I've been searching and searching and I'm finding it hard to implement this algorithm, does anyone know of any tutorial or something easy to understand so I can implement this algorithm myself? If possible, with C source code examples, it would help a lot. I see many examples with math notations but that just confuses me even more. Do you think it would help if I "converted" the graph to an adjacency matrix to represent the links weight and relation type? Would it be easier to perform the algorithm on that instead of the linked lists? I could easily implement a function to do that conversion when needed. I'm saying this because I got the feeling it would be easier after reading a couple of pages about the subject, but I could be wrong. I don't have any ideas about the other 4 operations, suggestions?

    Read the article

  • LLBL Gen Predicate Filter

    - by Neil
    I am new to LLBLGen Pro and am checking for duplicate, I have the following SQL: SQL: select a.TopicId,atc.TopicCategoryId,a.Headline from article a inner join ArticleTopicCategory atc on atc.ArticleId = a.Id where a.TopicId = 'C0064FAE-093B-466E-8745-230534867D2F' and a.Headline = 'Test' and atc.TopicCategoryId in ('004D64F7-474C-48F9-9887-17B1E7532A84') Whenever I step though my function, it always returns 0: LLBLGen Code: public bool CheckDuplicateArticle(Guid topicId, List<Guid> categories, string headline) { ArticleCollection articles = new ArticleCollection(); PredicateExpression filter = new PredicateExpression(); RelationCollection relation = new RelationCollection(); relation.Add(ArticleEntity.Relations.ArticleTopicCategoryEntityUsingArticleId); filter.AddWithAnd(ArticleFields.TopicId == topicId); filter.AddWithAnd(ArticleTopicCategoryFields.Id == categories); filter.AddWithAnd(ArticleFields.Headline == headline); articles.GetMulti(filter, 0, null, relation); return articles.Count > 0; } Any help would be appreciated!

    Read the article

  • How do I do a join in ActiveRecord after records have been returned?

    - by Russ Bradberry
    I am using ActiveRecord in Rails 3 to pull data from two different tables in two different databases. These databases can not join on each other, but I have the need to do a simple join after-the-fact. I would like to preserve the relation so that I can chain it down the line. here is a simplified version of what I am doing browsers = Browser.all # <-- this is fairly small and can reside in memory events = Event.where(:row_date=>Date.today).select(:name, :browser_id) So as you can see, I want to join browsers in on the events relation, where browser_id should equal browsers.name. events is a relation and I can still add clauses to it down the line, so I dont want to run the query on the db just yet. How would I accomplish this?

    Read the article

  • MATLAB: Automatic detection of relations between workspace variables through functions

    - by Peterstone
    Hi all, I´m trying to write a function what detect this relation between the variables I have got in the workspace: v1 - fft(v2) = 0 Where v1, v2 are variables of my workspace. Sometimes I need to know which variables have a certain numerical relation. If I have thirty, I don´t want to be looking for this relation in "manual way", just itroducing a sentence for each pair of different variables. I would like a function in which I introuce (or I modify this function every time I need it) the sentence (for instance what I wrote before) and the function show me the pair of variables a I am looking for. Does anyone know how to do it? Thank you so much!

    Read the article

  • Display another field in the referenced table for multiple columns with performance issues in mind

    - by israkir
    I have a table of edge like this: ------------------------------- | id | arg1 | relation | arg2 | ------------------------------- | 1 | 1 | 3 | 4 | ------------------------------- | 2 | 2 | 6 | 5 | ------------------------------- where arg1, relation and arg2 reference to the ids of objects in another object table: -------------------- | id | object_name | -------------------- | 1 | book | -------------------- | 2 | pen | -------------------- | 3 | on | -------------------- | 4 | table | -------------------- | 5 | bag | -------------------- | 6 | in | -------------------- What I want to do is that, considering performance issues (a very big table more than 50 million of entries) display the object_name for each edge entry rather than id such as: --------------------------- | arg1 | relation | arg2 | --------------------------- | book | on | table | --------------------------- | pen | in | bag | --------------------------- What is the best select query to do this? Also, I am open to suggestions for optimizing the query - adding more index on the tables etc... EDIT: Based on the comments below: 1) @Craig Ringer: PostgreSQL version: 8.4.13 and only index is id for both tables. 2) @andrefsp: edge is almost x2 times bigger than object.

    Read the article

  • command design pattern usage

    - by sagie
    Hi. I've read 3 descriptions of the command design pattern: wikipedia, dofactory and source making. In all of them, the UML shows a relation between the client to the receiver & the concrete command, but no relation to the invoker. But in all 3 examples the client is the one that initiates the invoker and call its Execute method. I think that should be a relation to the invoker as well. Am I missing somthing in here? Maybe even a basic UML knowladge?

    Read the article

  • commad design pattern usage

    - by sagie
    Hi. I've read 3 descriptions of the command design pattern: wikipedia, dofactory and source making. In all of them, the UML shows a relation between the client to the receiver & the concrete command, but no relation to the invoker. But in all 3 examples the client is the one that initiates the invoker and call its Execute method. I think that should be a relation to the invoker as well. Am I missing somthing in here? Maybe even a basic UML knowladge?

    Read the article

  • MySQL query with JOINS and GROUP BY

    - by user1854049
    I'm building a MySQL query but I can't seem to get it right. I have four tables: - customers - orders - sales_rates - purchase_rates There is a 1:n relation 'customernr' between customers and orders. There is a 1:n relation 'ordernr' between orders and sales_rates. There is a 1:n relation 'ordernr' between orders and purchase_rates. What I would like to do is produce an output of all customers with their total purchase and sales amounts. So far I have the following query. SELECT c.customernr, c.customer_name, SUM(sr.sales_price) AS sales_price, SUM(pr.purchase_price) AS purchase_price FROM orders o, customers c, sales_rates sr, purchase_rates pr WHERE o.customernr = c.customernr AND o.ordernr = sr.ordernr AND o.ordernr = pr.ordernr GROUP BY k.bedrijfsnaam The result of the sales_price and purchase_price is far too high. I seem to be getting double counts. What am I doing wrong? Is it possible to perform this in a single query? Thank for your response!

    Read the article

  • Are proofs worth the effort?

    - by Shashank Jain
    I bought the de-facto book for learning about data structures and algorithms (CLRS). The book is though quite good but the singularity is in the proofs. The book is filled with Lemmas, theorems, peculiar symbols and unimaginable recurrence relations which are very hard to understand. I am able to somehow get the algorithms but the discrete mathematics just not for me. So should I leave them out and just concentrate on algorithims?

    Read the article

  • What Precalculus knowledge is required before learning Discrete Math Computer Science topics?

    - by Ein Doofus
    Below I've listed the chapters from a Precalculus book as well as the author recommended Computer Science chapters from a Discrete Mathematics book. Although these chapters are from two specific books on these subjects I believe the topics are generally the same between any Precalc or Discrete Math book. What Precalculus topics should one know before starting these Discrete Math Computer Science topics?: Discrete Mathematics CS Chapters 1.1 Propositional Logic 1.2 Propositional Equivalences 1.3 Predicates and Quantifiers 1.4 Nested Quantifiers 1.5 Rules of Inference 1.6 Introduction to Proofs 1.7 Proof Methods and Strategy 2.1 Sets 2.2 Set Operations 2.3 Functions 2.4 Sequences and Summations 3.1 Algorithms 3.2 The Growths of Functions 3.3 Complexity of Algorithms 3.4 The Integers and Division 3.5 Primes and Greatest Common Divisors 3.6 Integers and Algorithms 3.8 Matrices 4.1 Mathematical Induction 4.2 Strong Induction and Well-Ordering 4.3 Recursive Definitions and Structural Induction 4.4 Recursive Algorithms 4.5 Program Correctness 5.1 The Basics of Counting 5.2 The Pigeonhole Principle 5.3 Permutations and Combinations 5.6 Generating Permutations and Combinations 6.1 An Introduction to Discrete Probability 6.4 Expected Value and Variance 7.1 Recurrence Relations 7.3 Divide-and-Conquer Algorithms and Recurrence Relations 7.5 Inclusion-Exclusion 8.1 Relations and Their Properties 8.2 n-ary Relations and Their Applications 8.3 Representing Relations 8.5 Equivalence Relations 9.1 Graphs and Graph Models 9.2 Graph Terminology and Special Types of Graphs 9.3 Representing Graphs and Graph Isomorphism 9.4 Connectivity 9.5 Euler and Hamilton Ptahs 10.1 Introduction to Trees 10.2 Application of Trees 10.3 Tree Traversal 11.1 Boolean Functions 11.2 Representing Boolean Functions 11.3 Logic Gates 11.4 Minimization of Circuits 12.1 Language and Grammars 12.2 Finite-State Machines with Output 12.3 Finite-State Machines with No Output 12.4 Language Recognition 12.5 Turing Machines Precalculus Chapters R.1 The Real-Number System R.2 Integer Exponents, Scientific Notation, and Order of Operations R.3 Addition, Subtraction, and Multiplication of Polynomials R.4 Factoring R.5 Rational Expressions R.6 Radical Notation and Rational Exponents R.7 The Basics of Equation Solving 1.1 Functions, Graphs, Graphers 1.2 Linear Functions, Slope, and Applications 1.3 Modeling: Data Analysis, Curve Fitting, and Linear Regression 1.4 More on Functions 1.5 Symmetry and Transformations 1.6 Variation and Applications 1.7 Distance, Midpoints, and Circles 2.1 Zeros of Linear Functions and Models 2.2 The Complex Numbers 2.3 Zeros of Quadratic Functions and Models 2.4 Analyzing Graphs of Quadratic Functions 2.5 Modeling: Data Analysis, Curve Fitting, and Quadratic Regression 2.6 Zeros and More Equation Solving 2.7 Solving Inequalities 3.1 Polynomial Functions and Modeling 3.2 Polynomial Division; The Remainder and Factor Theorems 3.3 Theorems about Zeros of Polynomial Functions 3.4 Rational Functions 3.5 Polynomial and Rational Inequalities 4.1 Composite and Inverse Functions 4.2 Exponential Functions and Graphs 4.3 Logarithmic Functions and Graphs 4.4 Properties of Logarithmic Functions 4.5 Solving Exponential and Logarithmic Equations 4.6 Applications and Models: Growth and Decay 5.1 Systems of Equations in Two Variables 5.2 System of Equations in Three Variables 5.3 Matrices and Systems of Equations 5.4 Matrix Operations 5.5 Inverses of Matrices 5.6 System of Inequalities and Linear Programming 5.7 Partial Fractions 6.1 The Parabola 6.2 The Circle and Ellipse 6.3 The Hyperbola 6.4 Nonlinear Systems of Equations

    Read the article

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