def setUp(self): self.client = Redis(decode_responses=True) self.client.flushdb() self.peter = Relationship(self.client, "peter") self.jack = Relationship(self.client, "jack") self.common_following = CommonFollowing(self.client)
def testinsertRelationship(): #relationship 1 print("yes") r = Relationship("*****@*****.**", "101010", "Checked Out", "2021-01-01 01:01:01", None) # dao.insertRelationship(r) r = Relationship("*****@*****.**", "101010", "Checked Out", "2021-01-01 01:01:01", None) dao.insertRelationship(r)
def selectActiveQRcode(self, qrcode): try: logging.info("Entering selectActiveQRcode") sql = "SELECT * from hascontainer WHERE qrcode = '" + qrcode + "' and status != 'Verified Return'" myresult = self.handleSQL(sql, True, None) if (myresult[0] == False): return myresult #myresult = myresult[1] temp = [] for x in myresult[1]: email = x[0] qrcode = x[1] status = x[2] statusUpdateTime = str(x[3]) location_qrcode = x[4] descrption = x[5] r = Relationship(email, qrcode, status, statusUpdateTime, location_qrcode, descrption) temp.append(r) logging.info("selectActiveQRcode successful") return True, temp except Exception as e: logging.error("Error in selectActiveQRcode") logging.error(str(e)) return self.handleError(e)
def selectPendingReturns(self): try: logging.info("Entering selectPendingReturns") sql = "SELECT * from hascontainer WHERE status = 'Pending Return' " myresult = self.handleSQL(sql, True, None) if (myresult[0] == False): return myresult #myresult = myresult[1] #print(myresult) temp = [] for x in myresult[1]: email = x[0] qrcode = x[1] status = x[2] statusUpdateTime = str(x[3]) location_qrcode = x[4] descrption = x[5] r = Relationship(email, qrcode, status, statusUpdateTime, location_qrcode, descrption) temp.append(r) #print(temp) logging.info("selectPendingReturns successful") return True, temp except Exception as e: logging.error("Error in selectPendingReturns") logging.error(str(e)) return self.handleError(e)
def profile(username, page=1, viewPage=1): formModalMessage = PrivateMessageForm() logged_user = None rel = None friends_page = False user = User.objects.filter(username=username).first() profile_messages = [] if user: if session.get('username'): logged_user = User.objects.filter( username=session.get('username')).first() rel = Relationship.get_relationship(logged_user, user) fetchNotifications(logged_user) # get friends friends = Relationship.objects.filter(fromUser=user, rel_type=Relationship.FRIENDS, status=Relationship.APPROVED) friends_total = friends.count() if 'friends' in request.url: friends_page = True friends = friends.paginate(page=friends_page, per_page=8) else: friends = friends[:5] form = FeedPostForm() # get user messages if friends if logged_user and (rel == "SAME" or rel == "FRIENDS_APPROVED"): profile_messages = Message.objects.filter( Q(fromUser=user) | Q(toUser=user), messageType=POST, ).order_by('-create_date') viewPage = int(viewPage) print(viewPage) print(page) profile_messages = profile_messages.paginate(page=viewPage, per_page=5) return render_template('user/profile.html', user=user, logged_user=logged_user, rel=rel, friends=friends, friends_total=friends_total, friends_page=friends_page, form=form, profile_messages=profile_messages, formModalMessage=formModalMessage) else: abort(404)
class TestCommonFollow(unittest.TestCase): def setUp(self): self.client = Redis(decode_responses=True) self.client.flushdb() self.peter = Relationship(self.client, "peter") self.jack = Relationship(self.client, "jack") self.common_following = CommonFollowing(self.client) def follow_users(self): self.peter.follow("tom") self.peter.follow("mary") self.peter.follow("david") self.jack.follow("tom") self.jack.follow("mary") self.jack.follow("john") def test_calculate(self): self.assertEqual(self.common_following.calculate("peter", "jack"), set()) self.follow_users() self.assertEqual(self.common_following.calculate("peter", "jack"), {"tom", "mary"}) def test_calculate_and_store(self): self.assertEqual(self.client.smembers("peter-and-jack-common-follow"), set()) self.follow_users() self.assertEqual( self.common_following.calculate_and_store( "peter", "jack", "peter-and-jack-common-follow"), 2) self.assertEqual(self.client.smembers("peter-and-jack-common-follow"), {"tom", "mary"})
def changeOldRelationship(self, result): try: logging.info("Entering changeOldRelationship") sql = "SELECT * from hascontainer WHERE qrcode = '" + result[ 1] + "' and status <> 'Verified Return' ORDER BY statusUpdateTime DESC" myresult = self.handleSQL(sql, True, None) if (myresult[0] == False): return myresult if (myresult[1] != [] and myresult[1] is not None): oldEmail = myresult[1][0] tempR = Relationship(oldEmail[0], oldEmail[1], oldEmail[2], oldEmail[3], oldEmail[4], None) if (tempR.status == "Damaged Lost"): tempR.description = "" #return False, "Container has been marked as Damaged Lost" #if(result[2] != "Damaged Lost"): tempR.status = "Verified Return" self.updateRelationship(tempR) except Exception as e: logging.error("Error in changeOldRelationship") logging.error(str(e)) return self.handleError(e)
def unidirectional_network(redditor: str, reddit_interactions: DataFrame) -> nx.Graph: ''' Construct unidirectional reddit reply network. Edge exists between two users if either has interacted with the other (A replied to B, B replied to A, or A replied to B and B replied to A. ''' G = nx.Graph(user=redditor) for index, row in reddit_interactions.iterrows(): author = row['author'] subreddit = row['subreddit'] date = row['date'].to_pydatetime() replying_to = row['replyingTo'] polarity = row['polarity'] subjectivity = row['subjectivity'] reply_count = int(row['replyCount']) # Node if not G.has_node(author): G.add_node(author, membership=Membership()) elif not 'membership' in G.node[author]: G.node[author]['membership'] = Membership() G.node[author]['membership'].append(subreddit, date) # Edge # If not replying to anyone (submission is used in membership attribute but not relationship attribute) if replying_to is None: continue # Don't put self loops in graph if replying_to == author: continue # If edge is new: add edge to graph and construct Relationship object if not G.has_edge(author, replying_to): G.add_edge(author, replying_to, relationship=Relationship()) # Append comment data to Relationship attribute of edge G[author][replying_to]['relationship'].append(author, replying_to, subreddit, date, polarity, subjectivity, reply_count) # Remove nodes on periphery of network (not connected to central user) G.remove_nodes_from([ user for user, membership in G.nodes(data='membership') if membership is None ]) return G
def updateRelationship(self, r): try: myresult = self.checkStatus(r) if (myresult[0] == False): return myresult logging.info("Entering updateRelationship") #r.statusUpdateTime = (r.statusUpdateTime + timedelta(seconds = 2)).strftime('%Y-%m-%d %H:%M:%S') #if status is Pending Return, call updatePoints() result = r.relationshipToList() #sql = "SELECT * from hascontainer WHERE email = '" + result[0] + "' and qrcode = '" + result[1] + "' and status <> 'Verified Return'" + " ORDER BY statusUpdateTime DESC" sql = "SELECT * from hascontainer WHERE qrcode = '" + result[ 1] + "' and status != 'Verified Return'" myresult = self.handleSQL(sql, True, None) #print(myresult,"here") if (myresult[0] == False): return myresult myresult = myresult[1][0] myresult = list(myresult) myresult[3] = str(myresult[3]) r1 = Relationship(myresult[0], myresult[1], myresult[2], myresult[3], myresult[4], myresult[5]) #if(r1.status=="Damaged Lost"): #return False, "Container has been marked as Damaged Lost" #if(r.status == "Damaged Lost" and r.description == None): #return False, "Damaged Lost Container lacks description" sql = "UPDATE hascontainer SET status = '" + str( r.status) + "', location_qrcode = '" + str( r.location_qrcode) + "', statusUpdateTime = '" + str( r.statusUpdateTime) + "', description = '" + str( r.description) + "' WHERE email = '" + str( r1.email) + "' and " + "qrcode = '" + str( r1.qrcode ) + "'" " and statusUpdateTime = '" + str( r1.statusUpdateTime) + "'" myresult = self.handleSQL(sql, False, None) if (myresult[0] == False): return myresult return True, "" except Exception as e: logging.error("Error in updateRelationship") logging.error(str(e)) return self.handleError(e)
def generate_book(num): date = datetime.date.fromisoformat('2010-12-01') for i in range(num): logging.debug(f"Chapter {str(i + 1)}") # Print HTML header print(f''' <html> <head> <meta charset="UTF-8"> <link rel="stylesheet" type="text/css" href="style.css" /> </head> <body> <div id='container'> <div id='wrapper'> ''') print(f'<h4>Chapter {str(i + 1)}</h4>') new_person = generate_person() r = Relationship(protagonist, new_person, date) r.simulate() r.simulate_reflection() date = r.events[len(r.events) - 1]['date'] relationship_narrator.narrate(r) if (r.phase == Phase.COURTING and random.random() < 0.5) or (r.phase == Phase.DATING): print(f'<h4>Chapter {str(i + 1.5)}</h4>') print(epilogue.get_epilogue(r, date)) # Print HTML closing tags print(f''' <p><a href="{i+1}.html">Next</a></p> </div> </div> <div id="bar"> <h5 id="debug">Hide debug 🥵</h5> <h4>ALEX 1.0</h4> <a href="/">home</a><br> <a href="process.html">about</a><br> <a href="https://github.com/c-dacanay/nanogenmo"><img id="github" src="https://image.flaticon.com/icons/png/512/25/25231.png" width="20" height="20"></a> <div id="toc"></div> </div> <script src="script.js"></script> </body> </html> ''') # Print separator line so that we can turn this into multiple # HTML files later print('|')
def narrate(r: Relationship): # Given a relationship object, break the events within into their distinct # phases and pass them to narrate_phase events = r.events saved_events = [] print( f"<p>Alex met {events[0]['person']['name']} {events[0]['location']}.</p>") print( f"<p class='system'>{events[0]['person']['name']}:</p>") for prop in r.b: if (type(r.b[prop]) == float): print(f"<p class='system prop'>{prop}: {round(r.b[prop], 2)}</p>") print( f"<p class='system prop'>interests: {', '.join(r.b['interests'])}</p>") for phase in [Phase.COURTING, Phase.DATING, Phase.COMMITTED]: chunk = [] while True: if len(events) == 0: break if events[0].get('phase', phase) != phase: # Move on to next phase break event = events.pop(0) chunk.append(event) saved_events.append(event) narrate_phase(chunk, phase) r.events = saved_events events = saved_events # knock alex's confidence just a touch # logging.debug(f"Alex's confidence is {a['confidence']}") r.a['confidence'] *= .9 + random.random() * 0.1 # logging.debug(f"Alex's confidence is {a['confidence']}") print(f"<p>They never saw each other again.</p>") if len(events) > 0: print( f"<p class='system'>This relationship lasted for only {humanize.naturaldelta(events[-1]['date'] - events[0]['date'])}, reaching the <tt>{r.phase.value}</tt> stage before ending.</p>")
def set_relationship_level(self, user_id, value): relationship = Relationship.get_by_ids(self._db, self._id, user_id) relationship.level = value
def remove_relationship(self, user_id): relationship = Relationship.get_by_ids(self._db, self._id, user_id) relationship.remove()
def create_new_relationship(self, user_id): relationship = Relationship(self._db, first_id=self._id, second_id=user_id) relationship.save()
def commit(self, batched=True, batch_size=100): self.committing = True from node import Node from relationship import Relationship retry = True max_retry = 5 while retry and max_retry > 0: retry = False try: self._commit(batched=batched, batch_size=batch_size) except CommitError as e: exc = e.exc_info[1] if isinstance(exc, BatchError) and exc.status_code == 404: if re.match(r'^node/\d+($|/.*$)', exc.uri): id = re.sub(r'^node/(\d+)($|/.*$)', r'\1', exc.uri) if id.isdigit(): node = Node(int(id)) if node.is_deleted(): node.expunge() retry = True continue elif re.match(r'^relationship/\d+($|/.*$)', exc.uri): id = re.sub(r'^relationship/(\d+)($|/.*$)', r'\1', exc.uri) if id.isdigit(): rel = Relationship(int(id)) if rel.is_deleted(): rel.expunge() retry = True continue elif isinstance(exc, BatchError): if isinstance(exc.__cause__, EntityNotFoundException): try: entity = exc.batch.jobs[exc.job_id].entity if entity.is_deleted(): entity.expunge() retry = True continue except (IndexError, AttributeError): pass # for the rest of the handlers, use the cause directly exc = exc.__cause__ if isinstance(exc, DeadlockDetectedException): retry = True max_retry -= 1 continue elif isinstance(exc, GuardTimeoutException): retry = True max_retry = 0 continue elif isinstance(exc, EntityNotFoundException): error = unicode(exc) if re.search(r'Node \d+ not found', error): id = re.sub(r'^.*Node (\d+) not found.*$', r'\1', error) if id.isdigit(): node = Node(int(id)) if node.is_deleted(): node.expunge() retry = True continue elif re.search(r'Relationship \d+ not found', error): id = re.sub(r'^.*Relationship (\d+) not found.*$', r'\1', error) if id.isdigit(): rel = Relationship(int(id)) if rel.is_deleted(): rel.expunge() retry = True continue raise e self.events.fire_committed() self.committing = False
def relationships_from_json(json_data): return [Relationship.from_json(rel) for rel in json_data['objects']]
def addRelationship(self, direct, column=None, helperColumn=None): self.relationships.append(Relationship(direct, column, helperColumn))