class NetworkSecurityGroup(Element): """NSG concept.""" inbound_rules = Relationship('InboundRule', 'INBOUND_RULE') outbound_rules = Relationship('OutboundRule', 'OUTBOUND_RULE') network_interfaces = Relationship('NetworkInterface', 'NETWORK_SECURITY_GROUP')
class VirtualMachine(Element): """Virtual Machine concept.""" disks = Relationship('Disk', 'DISK') network_interfaces = Relationship('NetworkInterface', 'NETWORK_INTERFACE') deployed_applications = Relationship('DeployedApplication', 'DEPLOYED_APPLICATION')
class AvailabilityZone(StructuredNode): """AV of a region where the elements are available.""" name = StringProperty() properties = JSONProperty() elements = Relationship('Element', 'ELEMENT') resource_groups = Relationship('ResourceGroup', 'RESOURCE_GROUP')
class User(StructuredNode): uid = UniqueIdProperty() first_name = StringProperty() last_name = StringProperty() email = StringProperty() password = StringProperty() signup_date = DateTimeProperty(default=lambda: datetime.now()) # Security login_ip = StringProperty() last_login = DateTimeProperty() failed_logins = IntegerProperty(default=0) bookmarks = Relationship(Bookmark, 'SAVED') tags = Relationship(Tag, 'TAGS') folders = RelationshipTo(Folder, 'ROOT_FOLDER') def get_gql_node(self) -> Dict: return { "first_name": self.first_name, "last_name": self.last_name, "email": self.email, "id": self.uid }
class Message(StructuredNode, models.Node): mid = UniqueIdProperty() message = StringProperty() timestamp = DateTimeProperty(default_now=True) chat = Relationship('Chat', 'IN_CHAT', cardinality=One) sender = Relationship('Person', 'SENDER', cardinality=One) unseen = Relationship('Person', 'READER')
class LoadBalancer(Element): """Load Balancer concept.""" network_interfaces = Relationship('NetworkInterface', 'VM_BACKEND_POOL') public_ip = Relationship('PublicIp', 'LB_PUBLIC_IP') inbound_rules = Relationship('InboundRule', 'INBOUND_RULE') outbound_rules = Relationship('OutboundRule', 'OUTBOUND_RULE') backend_pool_id = StringProperty()
class Event(StructuredNode): name = StringProperty(required=True) date = DateTimeProperty() description = StringProperty() location = StringProperty() joining = Relationship('Person', 'IS_JOINING') invited = Relationship('Person', 'IS_INVITED') declined = Relationship('Person', 'HAS_DECLINED')
class User(BaseNode, UserMixin): user_name = StringProperty(unique_index=True) email = StringProperty(unique_index=True) password_hash = StringProperty() secret_key = StringProperty(default=generate_uuid(3)) last_login = DateTimeProperty(default_now=True) followers = Relationship('User', 'FOLLOWING', model=UserFollowerRelationship, cardinality=ZeroOrMore) interests = Relationship('main.models.Interest', "INTERESTED_IN", model=UserInterestRelationship, cardinality=ZeroOrMore) # check if this user follows another user def follows(self, user_uuid): query = "MATCH (a:User) WHERE a.uuid ='{}' MATCH (a)-[:FOLLOWING]->(b:User) WHERE b.uuid='{}' RETURN b LIMIT 1".format(self.uuid, user_uuid) results, meta = db.cypher_query(query) result = [User.inflate(row[0]) for row in results] return len(result) > 0 # check if this user is being followed by other def followed_by(self, user_uuid): query = "MATCH (a:User) WHERE a.uuid ='{}' MATCH (a)-[:FOLLOWING]->(b:User) WHERE b.uuid='{}' RETURN b LIMIT 1".format(user_uuid, self.uuid) results, meta = db.cypher_query(query) result = [User.inflate(row[0]) for row in results] return len(result) > 0 # follow another user def follow(self, user): user.followers.connect(self) return user # get all users this users follow (maybe add pagination or something) @property def get_followed(self): query = "MATCH (a:User) WHERE a.uuid ='{}' MATCH (a)-[:FOLLOWING]->(b:User) RETURN b".format(self.uuid) results, meta = db.cypher_query(query) people = [User.inflate(row[0]) for row in results] return people def get_followed_paginate(self, page=1): page_size = DEFAULT_PAGE_SIZE current_skip = page * page_size query = "MATCH (a:User) WHERE a.uuid ='{}' MATCH (a)-[:FOLLOWING]->(b:User) RETURN b SKIP={} LIMIT={}".format(self.uuid, current_skip, page_size) results, meta = db.cypher_query(query) people = [User.inflate(row[0]) for row in results] return people def get_matches(self): query = "MATCH (p1:User {uuid:'%s'})-[:INTERESTED_IN]->(interests1) WITH p1, collect(id(interests1)) AS p1Interest " + \ "MATCH (p2:User)-[:INTERESTED_IN]->(interests2) WITH p1, p2, algo.similarity.jaccard(p1Interest, collect(id(interests2))) AS similarity " + \ "WHERE p1 <> p2 AND similarity > 0.1 RETURN p2.user_name AS name , p2.uuid AS uuid, similarity ORDER BY similarity DESC LIMIT 25;" query = query % self.uuid results, meta = db.cypher_query(query) return results
class ResourceGroup(StructuredNode): """RG that groups elements on an AV.""" name = StringProperty() subscription_id = StringProperty(unique_index=True) properties = JSONProperty() elements = Relationship('Element', 'ELEMENT_RESOURCE_GROUP') object_tags = Relationship('Tag', 'OBJ_TAG') object_properties = Relationship('Property', 'OBJ_PROPERTY')
class Busstop(StructuredNode): uid = UniqueIdProperty() name = StringProperty() latitude = FloatProperty(index=True) longitude = FloatProperty(index=True) # Relationship next_stop = Relationship('Busstop', 'ROUTE', model=Busroute) user = Relationship('User', 'OWNED_BY')
class Element(StructuredNode): """Base element type.""" __abstrac__abstract_node__ = True uid = StringProperty(unique_index=True) name = StringProperty() properties = JSONProperty() object_properties = Relationship('Property', 'OBJ_PROPERTY') tags = JSONProperty() object_tags = Relationship('Tag', 'OBJ_TAG')
class Class(BaseNode): model_id = StringProperty() _id = UniqueIdProperty() name = StringProperty() type = StringProperty() generalization = Relationship("Class", "generalization", model=GeneralizationRel) association = Relationship("Class", "association", model=AssociationRel) attribute = Relationship("Attribute", "has")
class Subject(StructuredNode): uid = UniqueIdProperty() code = StringProperty(unique_index=True, required=True) name = StringProperty(unique_index=True, required=True) level = IntegerProperty() prefix = StringProperty() credit = FloatProperty() type = StringProperty() availability = ArrayProperty(StringProperty()) prerequisites = Relationship('Subject', 'PREREQUISITES', model=SubjectRel) corequisites = Relationship('Subject', 'COREQUISITES', model=SubjectRel)
class Owner(StructuredNode): """Owner of an element.""" uid = StringProperty(unique_index=True) name = StringProperty() regions = Relationship('Region', 'REGION') elements = Relationship('Element', 'OWNED_ELEMENT') properties = JSONProperty() object_tags = Relationship('Tag', 'OBJ_TAG') object_properties = Relationship('Property', 'OBJ_PROPERTY') resource_groups = Relationship('ResourceGroup', 'OWNED_RESOURCE_GROUP')
class Movie(StructuredNode): idmovies = UniqueIdProperty() title = StringProperty() year = StringProperty() number = IntegerProperty() type = StringProperty() location = StringProperty() language = StringProperty() actors = Relationship('Actor', 'ACTED_IN') genres = Relationship('Genre', 'IN_GENRE')
class NeoTempEntity(StructuredNode): apis_uri = StringProperty(unique_index=True, required=True) n_name = StringProperty(unique=False) start_date = DateProperty() start_date_written = StringProperty() end_date = DateProperty() end_date_written = StringProperty() ent_type = StringProperty() rel_ent = Relationship('NeoTempEntity', 'RELATED', model=NeoTempEntRel) neo_project = Relationship('NeoProject', 'RELATED_PROJECT') def __str__(self): return f"{self.n_name}"
class PatientNode(BaseNode): primary_id = StringProperty(unique_index=True, required=True) genes = ArrayProperty(StringProperty()) # should this be a relationship? hpos = ArrayProperty(StringProperty()) has_phenotypes = Relationship('HPONode', 'HAS_PHENOTYPES', model=Patient_HPO_Edge)
class Router(NetworkingDevice): # Properties type = StringProperty(default='Router') # Relationships peers = Relationship('Router', 'BACKBONE', model=BackboneRelationship) switches = RelationshipFrom('Switch', 'ROUTER_FOR')
class Post(DjangoNode): post_id = UniqueIdProperty() date = DateTimeProperty(default=datetime.datetime.now()) link = StringProperty(required=True) text = StringProperty(required=False) upvoted = IntegerProperty(default=0) downvoted = IntegerProperty(default=0) tags = RelationshipTo("Tag", "TAGGED", cardinality=OneOrMore) user = RelationshipFrom("User", "POSTED", cardinality=One) comments = RelationshipFrom("Comment", "CONCERNING", cardinality=ZeroOrMore) votes = Relationship('User', 'RATED', model=VotingRel) @property def serialize(self): return { 'post_id': self.post_id, 'date': self.date, 'link': self.link, 'text': self.text, 'upvoted': self.upvoted, 'downvoted': self.downvoted, 'tags': [x.tag_id for x in self.tags.all()], 'user': [x.name for x in self.user.all()], 'comments': [x.comment_id for x in self.comments.all()], }
class Question(StructuredNode): nodeId = UniqueIdProperty() slug = StringProperty(unique_index=True) language = StringProperty(required=True, choices={ 'en': 'English', 'fr': 'French' } ) question = StringProperty(unique_index=True) addedOn = DateTimeProperty(default_now=True) options = ArrayProperty(base_property= StringProperty()) type = StringProperty( choices={ 'text': 'text', 'mcq': 'mcq', 'dropdown': 'dropdown' } ) related_questions = Relationship( 'Question', 'RELATED_QUESTION', model= Question_Question_Rel ) preQuestions = RelationshipFrom( 'PreQuestion', 'PREQUESTION_QUESTION' ) surveyVersions = RelationshipFrom( ".survey_model.SurveyVersion", "SURVEY_QUESTION" )
class ProductsCategory(StructuredNode): name = StringProperty() created_at = DateTimeProperty() updated_at = DateTimeProperty() subcategory = Relationship('ProductsCategory', 'SUB_CATEGORY') product = RelationshipTo('Product', 'HAS_PRODUCT')
class Author(StructuredNode): name = StringProperty() articles = RelationshipTo('Article', 'AUTHORED') coauthors = Relationship('Author', 'COAUTHORED') def __str__(self): # Call str function here since sometimes the object might not # found in the database... # Python sucks return "<Author: " + str(self.name) + ">" def __repr__(self): return "<Author: " + repr(self.name) + ">" def __hash__(self): """ We use name of the author as the hash value """ return hash(self.name) def __cmp__(self, other): return cmp(self.name, other.name) def toDict(self): return {"name": self.name}
class CompanyDB(StructuredNode): link = StringProperty() name = StringProperty(required=True) address = StringProperty() info = StringProperty() leaders = None leader = Relationship('LeaderDB', 'OWNED') def __init__(self, *args, **kwargs): self.leaders = set() super().__init__(*args, **kwargs) def is_in_db(self): try: CompanyDB.nodes.get(name=self.name) return True except neomodel.DoesNotExist: return False def __hash__(self): return hash( str(self.link) + str(self.name) + str(self.address) + str(self.info)) def __eq__(self, other): return hash(self) == hash(other)
class TextNode(StructuredNode): order_id = IntegerProperty(required=True, unique_index=True) label = StringProperty(required=True) text = StringProperty(required=True) alg_results = JSONProperty() link = Relationship('TextNode', 'ALG', model=TextRelation) def short(self): res = ''.join([ word.strip() + ' ' for word in re.split(r'[\n ]', self.text, 5)[:5] ]) return res def describe(self): return f""" <h1>Фрагмент: {self.order_id} </h1> <table border="1" width=100%> <caption> Информация о вершине </caption> <tr> <th>Количество символов</th> <td>{self.character_num()}</td> </tr> <tr> <th>Количество слов</th> <td>{self.words_num()}</td> </tr> <tr> <th>Количество предложений</th> <td>{self.sentences_num()}</td> </tr> <tr> <th>Количество связей</th> <td>{len(self.link)}</td> </tr> </table> """ def preview(self, frag_num=0): leading = 3 if frag_num > 0: leading = int(np.floor(np.log10(frag_num))) + 1 if str(self.order_id) != str(self.label): return f"{str(self.order_id).zfill(leading)}: " \ + f"[{self.label}] {self.short()}..." else: return f"{str(self.order_id).zfill(leading)}: " \ + f"[{self.label}] {self.short()}..." return f"[{self.label}] {self.short()}..." def words_num(self): return len(self.text.split()) def character_num(self): return len(self.text) def sentences_num(self): return len([s for s in self.text.split('.') if len(s) > 2])
class Person(StructuredNode): name = StringProperty(unique_index=True) friend = Relationship("Person", "KNOWS") politician = BooleanProperty() cricketer = BooleanProperty() actor = BooleanProperty() entertainment = BooleanProperty() team = BooleanProperty()
class Phrase(StructuredNode): phraseId = StringProperty(unique_index=True, required=True) name = StringProperty(unique_index=True, required=True) phraseType = StringProperty(required=True) identical = Relationship('Phrase', 'IDENTICAL', model=PhraseLink) overlap = Relationship('Phrase', 'OVERLAP', model=PhraseLink) cooccurence = Relationship('Phrase', 'CO-OCCURANCE', model=PhraseLink) center = RelationshipFrom('Phrase', 'Center', model=PhraseLink) before = RelationshipTo('Phrase', 'BEFORE', model=PhraseLink) modify = RelationshipTo('Phrase', 'MODIFY', model=PhraseLink) sub_procedure = RelationshipTo('Phrase', 'SUB_PROCEDURE', model=PhraseLink) after = RelationshipTo('Phrase', 'AFTER', model=PhraseLink) cause = RelationshipTo('Phrase', 'CAUSE', model=PhraseLink) decrease_to = RelationshipTo('Phrase', 'DECREASE_TO', model=PhraseLink) decrease_from = RelationshipTo('Phrase', 'DECREASE_FROM', model=PhraseLink) increase_from = RelationshipTo('Phrase', 'INCREASE_FROM', model=PhraseLink) increase_to = RelationshipTo('Phrase', 'INCREASE_TO', model=PhraseLink)
class Tweet(StructuredNode): id_str = IntegerProperty() text = StringProperty() retweet_count = IntegerProperty() favourites_count = IntegerProperty() created_at = StringProperty() lemm = StringProperty() valence = FloatProperty() arousal = FloatProperty() emotion = StringProperty() retweets = Relationship('Tweet', 'retweets') reply_to = Relationship('Tweet', 'reply_to') contains = Relationship('Url', 'contains') mentions = Relationship('User', 'mentions') using = Relationship('Source', 'using')
class Summoner(StructuredNode): summoner_name = StringProperty(unique_index=True) summoner_id = StringProperty(unique_index=True) account_id = StringProperty(unique_index=True) summoner_level = IntegerProperty(unique_index=True) profile_icon_id = IntegerProperty() last_match_history_update = DateProperty() games = Relationship("league_analytics_bot.model.GameInstance", "PLAYED_IN", model=PlayedInRel)
class Device(StructuredNode): def __init__(self, average_uptime, location): self.average_uptime = average_uptime self.location = location parent_cluster = Relationship('Cluster', 'PARENTS', model=ClusterOwnershipRel)
class Bus(StructuredNode): Name = StringProperty() Fare = IntegerProperty() name = StringProperty() Fare = IntegerProperty(default=0.0) # add kea hay int stopat = Relationship(Station, 'STOPAT')