Search Results

Search found 1068 results on 43 pages for 'relation'.

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

  • 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

  • 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

  • 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

  • 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

  • How to represent a tree structure in NoSQL

    - by Vlad Nicula
    I'm new to NoSQL and have been playing around with a personal project on the MEAN stack (Mongo ExpressJs AngularJs NodeJs). I'm building a document editor of sorts that manages nodes of data. Each document is actually a tree. I have a CRUD api for documents, to create new trees and a CRUD api for nodes in a given document. Right now the documents are represented as a collection that holds everything, including nodes. The children parent relationship is done by ids. So the nodes are an map by id, and each node has references to what nodes are their children. I chose this "flat" approach because it is easier to get a node by id from a document. Being used to having a relation table between nodes and documents, a relation table between nodes and children nodes I find it a bit weird that I have to save the entire "nodes" map each time I update a node. Is there a better way to represent such a data type in NoSQL?

    Read the article

  • RTS game diplomacy heuristics

    - by kd304
    I'm reimplementing an old 4X space-rts game which has diplomacy options. The original was based on a relation scoring system (0..100) and a set of negotiation options (improve relations, alliance, declare war, etc.) The AI player usually had 3 options: yes, maybe and no; each adding or removing some amount to the relation score. How should the AI chose between the options? How does the diplomacy work in other games and how are they imlemented? Any good books/articles on the subject? (Googling the term diplomacy yields the game Diplomacy, which is unhelpful.)

    Read the article

  • Find related field in Dynamics AX

    - by DAXShekhar
    static void findRelatedFieldId(Args _args) {     SysDictTable    dictTable = new SysDictTable(tablenum(InventTrans));     int             i,j;     SysDictRelation dictRelation;     TableId         externId = tablenum(SalesLine);     IndexId         indexId;     ; // Search the explicit relations     for (i = 1; i <= dictTable.relationCnt(); ++i)     {         dictRelation = new SysDictRelation(dictTable.id());         dictRelation.loadNameRelation(dictTable.relation(i)); // If it is a 'relation' then you use externTable(), but for extended data types you use table() (see next block).         if (SysDictRelation::externId(dictRelation) == externId)         {             for (j =1; j <= dictRelation.lines(); j++)             {                 info(strfmt("%1", dictRelation.lineExternTableValue(j)));                 info(fieldid2name(dictRelation.externTable(),dictRelation.lineExternTableValue(j)));             }         }     }     info(strfmt("%1", dictRelation.loadFieldRelation(fieldnum(InventTrans, InventTransId)))); }

    Read the article

  • Can software company claim the intellectual property rights on my paintings?

    - by maksymko
    This is somewhat related to this question. I'm about to sign a contract with a company that this sort of "all your base are belong to us" clause in it: it says that all programs, designs, sketches, drawings I create in relation to my job belong to the company. More or less usual stuff (unfortunately). What worries me, however, is this "drawings, sketches" thing, because I'm a hobby-artist and I paint and draw at my spare time. Can the company somehow claim ownership of intellectual rights on this work? Should I ask them to explicitly state that this clause does not extend to work of art or is this "in relation to the job" part is good enough?

    Read the article

  • Logic or Algorithm to solve this problem [closed]

    - by jade
    I have two lists. List1 {a,b,c,d,e} and List2 {f,g,h,i,j} The relation between the two list is as follows a->g,a->h,h->c,h->d,d->i,d->j Now I have these two lists displayed. Based on the relation above on selecting element a from List1, List2 shows g,h. On selecting h from List2, in List1 c,d are shown in List1. On selecting d from List1 it shows i,j in List2. How to trace back to initial state by deselecting the elements in reverse order in which they have been selected?

    Read the article

  • Asynchronously returning a hierarchal data using .NET TPL... what should my return object "look" like?

    - by makerofthings7
    I want to use the .NET TPL to asynchronously do a DIR /S and search each subdirectory on a hard drive, and want to search for a word in each file... what should my API look like? In this scenario I know that each sub directory will have 0..10000 files or 0...10000 directories. I know the tree is unbalanced and want to return data (in relation to its position in the hierarchy) as soon as it's available. I am interested in getting data as quickly as possible, but also want to update that result if "better" data is found (better means closer to the root of c:) I may also be interested in finding all matches in relation to its position in the hierarchy. (akin to a report) Question: How should I return data to my caller? My first guess is that I think I need a shared object that will maintain the current "status" of the traversal (started | notstarted | complete ) , and might base it on the System.Collections.Concurrent. Another idea that I'm considering is the consumer/producer pattern (which ConcurrentCollections can handle) however I'm not sure what the objects "look" like. Optional Logical Constraint: The API doesn't have to address this, but in my "real world" design, if a directory has files, then only one file will ever contain the word I'm looking for.  If someone were to literally do a DIR /S as described above then they would need to account for more than one matching file per subdirectory. More information : I'm using Azure Tables to store a hierarchy of data using these TPL extension methods. A "node" is a table. Not only does each node in the hierarchy have a relation to any number of nodes, but it's possible for each node to have a reciprocal link back to any other node. This may have issues with recursion but I'm addressing that with a shared object in my recursion loop. Note that each "node" also has the ability to store local data unique to that node. It is this information that I'm searching for. In other words, I'm searching for a specific fixed RowKey in a hierarchy of nodes. When I search for the fixed RowKey in the hierarchy I'm interested in getting the results FAST (first node found) but prefer data that is "closer" to the starting point of the hierarchy. Since many nodes may have the particular RowKey I'm interested in, sometimes I may want to get a report of ALL the nodes that contain this RowKey.

    Read the article

  • Quelle est la place des mobiles en entreprise ? De quel service de téléphonie votre entreprise a-t-e

    Quelle est la place des mobiles en entreprise ? De quel service de téléphonie votre entreprise a-t-elle le plus besoin ? Microsoft lance une grande campagne pour promouvoir son OS mobile Windows Phone. La firme cherche particulièrement à atteindre les entreprises, en leur promettant que "grande entreprise ou PME, il existe forcément une solution Windows Phone pour vous." Voici les cinq grands axes autour desquels s'articulent l'emploi de Windows Phone dans les entreprises : - Gestion de la relation client Grâce aux solutions de gestion de la relation client, vous pouvez consulter les toutes dernières données de vente...

    Read the article

  • C Programming arrays, I dont understand how I would go about making this program, If anyone can just guide me through the basic outline please :) [on hold]

    - by Rashmi Kohli
    Problem The temperature of a car engine has been measured, from real-world experiments, as shown in the table and graph below: Time (min) Temperature (oC) 0 20 1 36 2 61 3 68 4 77 5 110 Use linear regression to find the engine’s temperature at 1.5 minutes, 4.3 minutes, and any other time specified by the user. Background In engineering, many times we measure several data points in an experiment, but then we need to predict a value that we have not measured which lies between two measured values, such as the problem statement above. If the relation between the measured parameters seems to be roughly linear, then we can use linear regression to find the relationship between those parameters. In the graph of the problem statement above, the relation seems to be roughly linear. Hence, we can apply linear regression to the above problem. Assuming y {y0, y1, …yn-1} has a linear relation with x {x0, x1, … xn-1}, we can say that: y = mx+b where m and b can be found with linear regression as follows: For the problem in this lab, using linear regression gives us the following line (in blue) compared to the measured curve (in red). As you can see, there is usually a difference between the measured values and the estimated (predicted) values. What linear regression does is to minimize those differences and still give us a straight line (blue). Other methods, such as non-linear regression, are also possible to achieve higher accuracy and better curve fitting. Requirements Your program should first print the table of the temperatures similar to the way it’s printed in the problem statement. It should then calculate the temperature at minute 1.5 and 4.3 and show the answers to the user. Next, it should prompt the user to enter a time in minutes (or -1 to quit), and after reading the user’s specified time it should give the value of the engine’s temperature at that time. It should then go back to the prompt. Hints •Use a one dimensional array to store the temperature values given in the problem statement. •Use functions to separate tasks such as calculating m, calculating b, calculating the temperature at a given time, printing the prompt, etc. You can then give your algorithm as well as you pseudo code per function, as opposed to one large algorithm diagram or one large sequence of pseudo code.

    Read the article

  • Choose Your Boss : un tiers de recruteurs en plus par mois, le nouveau site d'emploi IT inspiré des sites de rencontres trouve son public

    Choose Your Boss : un nouveau site d'emplois IT qui s'inspire des sites de rencontres Plus de deux cent offres qualifiées de postes disponibles Choose Your Boss est un site original. Il s'inspire de Meetic et autres Attractive World pour mettre en relation développeurs et professionnels de l'IT d'une part et recruteurs d'autre part. Créé par Laurent Chollat-Namy, qui bénéficie d'une expérience professionnelle de 15 ans dans l'IT, celui-ci explique : « Nous avons longuement discuté avec des recruteurs et des informaticiens pour identifier leurs besoins et leurs pratiques. Cette réflexion nous a amenés à réinventer la mise en relation candidat / recruteur en nous inspirant des sites de r...

    Read the article

  • Choose Your Boss : un nouveau site d'emplois IT qui s'inspire des sites de rencontres, plus de 200 offres qualifiées

    Choose Your Boss : un nouveau site d'emplois IT qui s'inspire des sites de rencontres Plus de deux cent offres qualifiées de postes disponibles Choose Your Boss est un site original. Il s'inspire de Meetic et autres Attractive World pour mettre en relation développeurs et professionnels de l'IT d'une part et recruteurs d'autre part. Créé par Laurent Chollat-Namy, qui bénéficie d'une expérience professionnelle de 15 ans dans l'IT, celui-ci explique : « Nous avons longuement discuté avec des recruteurs et des informaticiens pour identifier leurs besoins et leurs pratiques. Cette réflexion nous a amenés à réinventer la mise en relation candidat / recruteur en nous inspirant des sites de r...

    Read the article

  • Choose Your Boss : un nouveau site d'emplois IT qui s'inspire des sites de rencontres, plus de 200 offres qualifiées

    Choose Your Boss : un nouveau site d'emplois IT qui s'inspire des sites de rencontres Plus de deux cent offres qualifiées de postes disponibles Choose Your Boss est un site original. Il s'inspire de Meetic et autres Attractive World pour mettre en relation développeurs et professionnels de l'IT d'une part et les recruteurs d'autre part. Créé par Laurent Chollat-Namy, qui bénéficie d'une expérience professionnelle de 15 ans dans l'IT, celui-ci explique : « Nous avons longuement discuté avec des recruteurs et des informaticiens pour identifier leurs besoins et leurs pratiques. Cette réflexion nous a amenés à réinventer la mise en relation candidat / recruteur en nous inspirant des sites ...

    Read the article

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