def _correct_dot_character(self, license_plate, image_original, width, height, m, c, x_interval): ''' Move dot character to other position. ''' found_dot = False characters = [] for character in license_plate.subrects: if character.x < 0: character.x = 0 if character.y < 0: character.y = 0 if character.x > license_plate.image.width - 1: character.x = license_plate.image.width - 1 if character.y > license_plate.image.height - 1: character.y = license_plate.image.height - 1 if character.x + character.w > license_plate.image.width - 1: character.w = license_plate.image.width - 1 - character.x if character.y + character.h > license_plate.image.height - 1: character.y = license_plate.image.height - 1 - character.y if not found_dot: character_image = license_plate.image.crop( Point(character.x, character.y), Point(character.x + character.w - 1, character.y + character.h - 1)) if character_image.data.size > 0 and character_image.data is not None: mean_value = np.mean(character_image.data) else: mean_value = 0 if mean_value > 200: found_dot = True else: characters.append(character) else: characters.append(character) if found_dot: # Remove dot character and add new character. license_plate.subrects = characters # Insert new character. license_plate, inserted, width, height, m, c, x_interval = self._insert_between_characters( license_plate, image_original, width, height, m, c, x_interval) if not inserted: license_plate, width, height, m, c, x_interval = self._insert_in_limits( license_plate, image_original, width, height, m, c, x_interval) return license_plate
def get_best_license_plate(self, license_plates, image_original, resize_width=400): ''' Get best license plate. ''' best_license_plate = None # Detect characters in license plate. for license_plate in license_plates: character_validator = CharacterValidator() image = image_original.crop(Point(license_plate.x, license_plate.y), Point(license_plate.x + license_plate.w, license_plate.y + license_plate.h)) image = image.resize(resize_width, resize_width * image.height / image.width) image = pre_process_license_plate_image(image, adaptative=False) license_plate.image = image license_plate.subrects = image.compute_rectangles_for_characters() character_validator.remove_wrong_characters(license_plate) # If not enough characters detected, binarize image using adaptative method. if len(license_plate.subrects) < 2: image = image_original.crop(Point(license_plate.x, license_plate.y), Point(license_plate.x + license_plate.w, license_plate.y + license_plate.h)) image = image.resize(resize_width, resize_width * image.height / image.width) image = pre_process_license_plate_image(image, True) license_plate.image = image license_plate.subrects = image.compute_rectangles_for_characters() character_validator.remove_wrong_characters(license_plate) # Find best license plate by total of characters and area. if len(license_plates) > 0: license_plates = sorted(license_plates, key=lambda x: len(x.subrects) -math.tanh(x.h*x.w*1.0/(x.image.width*x.image.height))) license_plates = license_plates[::-1] best_license_plate = license_plates[0] filtera = FilterCharacters() best_license_plate.subrects = filtera.filter_characters_by_color(best_license_plate.subrects, best_license_plate.image) return best_license_plate
def mutate(self, info, linkType, url, parentRootURLsafe, rootURLsafe, vote): user = info.context.current_user point, pointRoot = PointModel.getCurrentByUrl(url) if point: if user: pp, ppr = PointModel.getCurrentByRootKey(parentRootURLsafe) result, newRelevance, newVoteCount = user.addRelevanceVote( parentRootURLsafe, rootURLsafe, linkType, vote) if result: return RelevanceVote( point=point, parentPoint=pp, link=Link(type=linkType, relevance=newRelevance, sortScore=LinkModel.calcSortScore( newRelevance, point.pointValueCached), relevanceVote=vote, voteCount=newVoteCount, parentURLsafe=parentRootURLsafe, childURLsafe=rootURLsafe)) else: raise Exception(str('vote failed: ' + str(vote))) else: raise Exception(str('user not defined ' + str(user))) else: raise Exception(str('point not defined ' + str(point)))
def get(self): user = self.current_user linkType = 'supporting' p1, pRoot1 = Point.getCurrentByUrl('CCC') p2, pRoot2 = Point.getCurrentByUrl('bbb') #result, newRelevance, newVoteCount = \ # user.addRelevanceVote(pRoot1.key.urlsafe(), pRoot2.key.urlsafe(), linkType, 50) """newRelVote = RelevanceVote( parent=user.key, parentPointRootKey = pRoot1.key, childPointRootKey = pRoot2.key, value = 50, linkType=linkType) newRelVote.put()""" # GET THE VOTE BACK q = RelevanceVote.query(RelevanceVote.parentPointRootKey == pRoot1.key, RelevanceVote.childPointRootKey == pRoot2.key, RelevanceVote.linkType == linkType) votes = q.fetch(20) message = "" message = 'Got %d votes on retrieval.' % len(votes) template_values = { 'user': user, 'message': message, 'currentArea':self.session.get('currentArea'), 'currentAreaDisplayName':self.session.get('currentAreaDisplayName') } self.response.out.write(self.template_render('message.html', template_values))
def post(self): resultJSON = json.dumps({'result': False}) supportingPoint, supportingPointRoot = Point.getCurrentByUrl(self.request.get('supportingPointURL')) oldPoint, oldPointRoot = Point.getCurrentByUrl(self.request.get('parentPointURL')) user = self.current_user linkType = self.request.get('linkType') if user: try: newLink = [{'pointRoot':supportingPointRoot, 'pointCurrentVersion':supportingPoint, 'linkType':self.request.get('linkType')} ] oldPoint.update( pointsToLink=newLink, user=user ) except WhysaurusException as e: resultJSON = json.dumps({'result': False, 'error': str(e)}) else: path = os.path.join(constants.ROOT, 'templates/pointBox.html') newLinkPointHTML = json.dumps(template.render(path, {'point': supportingPoint})) resultJSON = json.dumps({'result': True, 'numLinkPoints': supportingPoint.linkCount(linkType), 'newLinkPoint':newLinkPointHTML}) else: resultJSON = json.dumps({'result': 'ACCESS DENIED!'}) self.response.headers.add_header('content-type', 'application/json', charset='utf-8') self.response.out.write(resultJSON)
def getPointCreator(self): result = {'result': False} point, pointRoot = Point.getCurrentByUrl(self.request.get('pointURL')) versionsOfThisPoint = Point.query(ancestor=pointRoot.key).order( Point.version) firstVersion = versionsOfThisPoint.get() authors = [] """code for listing number of contributors""" """ for point in versionsOfThisPoint: thisAuthor = {"authorName": point.authorName, "authorURL": point.authorURL } if thisAuthor not in authors: authors.append(thisAuthor) """ resultJSON = json.dumps({ 'result': True, 'creatorName': firstVersion.authorName, 'creatorURL': firstVersion.authorURL, 'numAuthors': len(authors) }) self.response.headers[ "Content-Type"] = 'application/json; charset=utf-8' self.response.out.write(resultJSON)
def mutate(self, info, url, parentURL, linkType): supportingPoint, supportingPointRoot = PointModel.getCurrentByUrl(url) oldPoint, oldPointRoot = PointModel.getCurrentByUrl(parentURL) user = info.context.current_user if user: # NOTE: ported this over from handlers/linkpoint.py, don't totally understand it all # This code is if the vote existed before and the point was unlinked, and now # it is being re-linked voteCount, rating, myVote = RelevanceVoteModel.getExistingVoteNumbers( oldPointRoot.key, supportingPointRoot.key, linkType, user) supportingPoint._relevanceVote = myVote newLink = [{ 'pointRoot': supportingPointRoot, 'pointCurrentVersion': supportingPoint, 'linkType': linkType, 'voteCount': voteCount, 'fRating': rating }] newVersion = oldPoint.update(pointsToLink=newLink, user=user) user.addRelevanceVote(oldPointRoot.key.urlsafe(), supportingPointRoot.key.urlsafe(), linkType, 100) # get my vote for this point, to render it in the linkPoint template supportingPoint.addVote(user) # these two are in service of the SubPointConnection logic - we should find a way to DRY this up supportingPoint.parent = newVersion supportingPoint.link_type = linkType return LinkPoint(parent=newVersion, point=supportingPoint) else: raise Exception("User not logged in.")
def get_calf_points(front: Person, side: Person) -> Tuple[Point, Point, Point, Point]: # calf_left_c = get_max_coord_with_min(front.leg.calf.right) # calf_right_c = front.leg.calf.right[1].min() # calf_left_col = np.where(front.leg.calf.right[1] == calf_left_c) # calf_left_r = calf_right_r = front.leg.calf.right[0][calf_left_col[0].max()] calf_back_c = side.leg.calf.right[1].min() calf_front_c = get_max_coord_with_min(side.leg.calf.right) calf_height_row = np.where(side.leg.calf.right[1] == calf_back_c) calf_height = side.leg.calf.right[0][calf_height_row[0].max()] calf_height_ratio = (calf_height - side.all[0].min()) / ( side.all[0].max() - side.all[0].min()) calf_front_height = int( ((front.all[0].max() + front.leg.calf.right[0].max()) / 2 - front.all[0].min()) * calf_height_ratio) + \ front.all[0].min() calf_row = np.where(front.leg.calf.right[0] == calf_front_height) # print(calf_row[0]) calf_left_c = front.leg.calf.right[1][calf_row[0].max()] calf_right_c = front.leg.calf.right[1][calf_row[0].min()] calf_left = Point(calf_left_c, calf_front_height) calf_right = Point(calf_right_c, calf_front_height) calf_back = Point(calf_back_c, calf_height) calf_front = Point(calf_front_c, calf_height) return calf_left, calf_right, calf_back, calf_front
def get_hip_points( front: Person, side: Person, crotch: Point, above_pelvis: Point) -> Tuple[Point, Point, Point, Point]: hip_r = (crotch[1] + above_pelvis[1]) // 2 hip_row = np.where(front.hip[0] == hip_r) hip_left_c = front.hip[1][hip_row[0].max()] hip_right_c = front.hip[1][hip_row[0].min()] hip_left = Point(hip_left_c, hip_r) hip_right = Point(hip_right_c, hip_r) # hip_left_c = front[1].max() # hip_left_row = np.where(front[1] == front[1].max()) # hip_left_r = front[0][hip_left_row[0].max()] # hip_left = (hip_left_c, hip_left_r) # hip_right_c = front[1].min() # hip_right_row = np.where(front[1] == front[1].min()) # hip_right_r = front[0][hip_right_row[0].min()] # hip_right = (hip_right_c, hip_right_r) hip_back_c = side.hip[1].min() hip_back_col = np.where(side.hip[1] == hip_back_c) hip_back_r = side.hip[0][hip_back_col[0].min()] hip_back = Point(hip_back_c, hip_back_r) hip_front_col = np.where(side.hip[1] == hip_back_c) hip_front_r = side.hip[0][hip_front_col[0][0]] hip_front_row = np.where(side.all[0] == hip_front_r) hip_front_c = side.all[1][hip_front_row[0].max()] # hip_front_c = get_max_coord_with_min(side) # hip_front_col = np.where(side[1] == hip_front_c) # hip_front_r = side[0][hip_front_col[0].max()] hip_front = Point(hip_front_c, hip_front_r) return hip_left, hip_right, hip_back, hip_front
def get_shoulder_points(front: Person) -> Tuple[Point, Point]: front_shoulder_left = Point(front.arm.left.upper[1][0], front.arm.left.upper[0][0]) front_shoulder_right = Point(front.arm.right.upper[1][0], front.arm.right.upper[0][0]) return front_shoulder_left, front_shoulder_right
def getPointCreator(self): result = {'result': False} point, pointRoot = Point.getCurrentByUrl(self.request.get('pointURL')) versionsOfThisPoint = Point.query(ancestor=pointRoot.key).order(Point.version) firstVersion = versionsOfThisPoint.get() authors = [] """code for listing number of contributors""" """ for point in versionsOfThisPoint: thisAuthor = {"authorName": point.authorName, "authorURL": point.authorURL } if thisAuthor not in authors: authors.append(thisAuthor) """ resultJSON = json.dumps({ 'result': True, 'creatorName' : firstVersion.authorName, 'creatorURL' : firstVersion.authorURL, 'numAuthors' : len(authors) }) self.response.headers["Content-Type"] = 'application/json; charset=utf-8' self.response.out.write(resultJSON)
def post(self): jsonOutput = {'result': False} user = self.current_user linkType = self.request.get('linkType') sourcesURLs=json.loads(self.request.get('sourcesURLs')) sourcesNames=json.loads(self.request.get('sourcesNames')) parentNewScore = None if user: try: parentPointURL = self.request.get('pointUrl') oldPoint, oldPointRoot = Point.getCurrentByUrl(parentPointURL) if oldPointRoot: newPoint, newLinkPoint = Point.addSupportingPoint( oldPointRoot=oldPointRoot, title=self.request.get('title'), content=self.request.get('content'), summaryText=self.request.get('plainText'), user=user, # backlink=oldPoint.key.parent(), linkType = linkType, imageURL=self.request.get('imageURL'), imageAuthor=self.request.get('imageAuthor'), imageDescription=self.request.get('imageDescription'), sourcesURLs=sourcesURLs, sourcesNames=sourcesNames ) # TODO: Gene: Probably have a more efficient retrieval here no? oldPoint, oldPointRoot = Point.getCurrentByUrl(parentPointURL) if oldPoint: parentNewScore = oldPoint.pointValue() else: raise WhysaurusException('Point with URL %s not found' % parentPointURL) except WhysaurusException as e: jsonOutput = { 'result': False, 'errMessage': str(e) } else: ReportEvent.queueEventRecord(user.key.urlsafe(), newLinkPoint.key.urlsafe(), newPoint.key.urlsafe(), "Create Point") newLinkPointHTML = self.template_render('linkPoint.html', { 'point': newLinkPoint, 'linkType': linkType }) jsonOutput = { 'result': True, 'version': newPoint.version, 'author': newPoint.authorName, 'dateEdited': newPoint.PSTdateEdited.strftime('%b. %d, %Y, %I:%M %p'), 'numLinkPoints': newPoint.linkCount(linkType), 'newLinkPoint': newLinkPointHTML, 'authorURL': self.current_user.url, 'parentNewScore': parentNewScore } self.response.headers["Content-Type"] = 'application/json; charset=utf-8' self.response.out.write(json.dumps(jsonOutput)) else: self.response.out.write('Need to be logged in')
def mutate(self, info, comment_data): point_root = PointRootModel.getByUrlsafe(comment_data.pointID) user = info.context.current_user text = comment_data.text comment = CommentModel.create(text, user, point_root, comment_data.parentCommentID) PointModel.addNotificationTask(point_root.key, user.key, 3, text) return NewComment(comment=comment)
def post(self): jsonOutput = {'result': False} oldPoint, oldPointRoot = Point.getCurrentByUrl( self.request.get('pointUrl')) user = self.current_user linkType = self.request.get('linkType') nodeType = self.request.get('nodeType') if \ self.request.get('nodeType') else 'Point' sourcesURLs=json.loads(self.request.get('sourcesURLs')) sourcesNames=json.loads(self.request.get('sourcesNames')) if user: newLinkPoint, newLinkPointRoot = Point.create( title=self.request.get('title'), nodetype=nodeType, content=self.request.get('content'), summaryText=self.request.get('plainText'), user=user, backlink=oldPoint.key.parent(), linktype = linkType, imageURL=self.request.get('imageURL'), imageAuthor=self.request.get('imageAuthor'), imageDescription=self.request.get('imageDescription'), sourceURLs=sourcesURLs, sourceNames=sourcesNames) try: logging.info('Adding newLink: ' + linkType) newLinks = [{'pointRoot':newLinkPointRoot, 'pointCurrentVersion':newLinkPoint, 'linkType':linkType}, ] newPoint = oldPoint.update( pointsToLink=newLinks, user=user ) except WhysaurusException as e: jsonOutput = { 'result': False, 'err': str(e) } else: path = os.path.join(constants.ROOT, 'templates/pointBox.html') newLinkPointHTML = json.dumps(template.render(path, {'point': newLinkPoint})) jsonOutput = { 'result': True, 'version': newPoint.version, 'author': newPoint.authorName, 'dateEdited': newPoint.dateEdited.strftime("%Y-%m-%d %H: %M: %S %p"), 'numLinkPoints': newPoint.linkCount(linkType), 'newLinkPoint':newLinkPointHTML } resultJSON = json.dumps(jsonOutput) self.response.headers.add_header('content-type', 'application/json', charset='utf-8') self.response.out.write(resultJSON) else: self.response.out.write('Need to be logged in')
def create_room_reflections(current_room: Room, reflections_list: List[Room]): left_reflection = deepcopy(current_room) left_reflection.move_room_left() switch_coefficient(left_reflection.left_wall, left_reflection.right_wall) left_reflection_transmitter_x = \ left_reflection.left_wall.start_point.x + current_room.length - abs(left_reflection.transmitter.x - left_reflection.left_wall.start_point.x) left_reflection_transmitter_y = left_reflection.transmitter.y left_ref_transmitter = Point(left_reflection_transmitter_x, left_reflection_transmitter_y) left_reflection.transmitter = left_ref_transmitter top_reflection = deepcopy(current_room) top_reflection.move_room_up() switch_coefficient(top_reflection.top_wall, top_reflection.down_wall) top_ref_transmitter_x = top_reflection.transmitter.x top_ref_transmitter_y = \ top_reflection.left_wall.start_point.y + current_room.height - abs(top_reflection.transmitter.y - top_reflection.left_wall.start_point.y) top_ref_transmitter = Point(top_ref_transmitter_x, top_ref_transmitter_y) top_reflection.transmitter = top_ref_transmitter right_reflection = deepcopy(current_room) right_reflection.move_room_right() switch_coefficient(right_reflection.left_wall, right_reflection.right_wall) right_reflection_transmitter_x = \ right_reflection.left_wall.start_point.x + current_room.length - abs(right_reflection.transmitter.x - right_reflection.left_wall.start_point.x) right_reflection_transmitter_y = right_reflection.transmitter.y right_ref_transmitter = Point(right_reflection_transmitter_x, right_reflection_transmitter_y) right_reflection.transmitter = right_ref_transmitter down_reflection = deepcopy(current_room) down_reflection.move_room_down() switch_coefficient(down_reflection.top_wall, down_reflection.down_wall) down_ref_transmitter_x = down_reflection.transmitter.x down_ref_transmitter_y = \ down_reflection.left_wall.start_point.y + current_room.height - abs(down_reflection.transmitter.y - down_reflection.left_wall.start_point.y) down_ref_transmitter = Point(down_ref_transmitter_x, down_ref_transmitter_y) down_reflection.transmitter = down_ref_transmitter if left_reflection not in reflections_list: reflections_list.append(left_reflection) if top_reflection not in reflections_list: reflections_list.append(top_reflection) if right_reflection not in reflections_list: reflections_list.append(right_reflection) if down_reflection not in reflections_list: reflections_list.append(down_reflection)
def get_neck_points(front: Person, side: Person) -> Tuple[Point, Point, Point, Point]: body_middle = (front.body[1].max() + front.body[1].min()) // 2 body_left_coords = np.where( front.body[1] > (front.body[1].max() + 9 * body_middle) / 10) # body_left_coords = np.where(front.body[1] > body_middle) body_right_coords = np.where( front.body[1] < (front.body[1].min() + 9 * body_middle) / 10) # body_right_coords = np.where(front.body[1] < body_middle) neck_left_row = np.where( front.body[0] == front.body[0][body_left_coords[0]].min()) neck_right_row = np.where( front.body[0] == front.body[0][body_right_coords[0]].min()) neck_start = side.body[0][0] neck_row = np.where(side.face.all[0] == neck_start) side_coord = side.body side_row_arr = [] side_col_arr = [] for i in range(side_coord[1].max(), side_coord[1].min(), -1): col = np.where(side_coord[1] == i) if col[0].shape[0] == 0: continue side_row_arr.append(side_coord[0][col[0][0]]) side_col_arr.append(side_coord[1][col[0][0]]) i = 0 # print(side_row_arr) # print(side_col_arr) while True: if side_row_arr[i] >= side_row_arr[i + 1]: i += 1 continue else: break # print(side_row_arr[i], side_col_arr[i]) front_neck_left_point = Point(front.body[1][neck_left_row[0].max()], front.body[0][body_left_coords[0]].min()) front_neck_right_point = Point( front.body[1][neck_right_row[0].min()], front.body[0][body_right_coords[0]].min()) side_neck_left_point = Point(side.face.all[1][neck_row[0].min()], neck_start) # side_neck_right_point = (side.face.all[1][neck_row[0].max()], neck_start) side_neck_right_point = Point(side_col_arr[i], side_row_arr[i]) return front_neck_left_point, front_neck_right_point, side_neck_left_point, side_neck_right_point
def post(self): self.response.headers["Content-Type"] = 'application/json; charset=utf-8' resultJSON = json.dumps({'result': False}) supportingPoint, supportingPointRoot = Point.getCurrentByUrl(self.request.get('supportingPointURL')) oldPoint, oldPointRoot = Point.getCurrentByUrl(self.request.get('parentPointURL')) user = self.current_user linkType = self.request.get('linkType') if user: try: # This code is if the vote existed before and the point was unlinked, and now # it is being re-linked voteCount, rating, myVote = RelevanceVote.getExistingVoteNumbers( oldPointRoot.key, supportingPointRoot.key, linkType, user) supportingPoint._relevanceVote = myVote linkType = self.request.get('linkType') newLink = [{'pointRoot':supportingPointRoot, 'pointCurrentVersion':supportingPoint, 'linkType':linkType, 'voteCount': voteCount, 'fRating':rating } ] newVersion = oldPoint.update( pointsToLink=newLink, user=user ) user.addRelevanceVote( oldPointRoot.key.urlsafe(), supportingPointRoot.key.urlsafe(), linkType, 100) # get my vote for this point, to render it in the linkPoint template supportingPoint.addVote(user) except WhysaurusException as e: resultJSON = json.dumps({'result': False, 'error': e.message}) else: if newVersion: newLinkPointHTML = self.template_render('linkPoint.html', { 'point': supportingPoint, 'linkType': linkType }) resultJSON = json.dumps({ 'result': True, 'numLinkPoints': newVersion.linkCount(linkType), 'newLinkPoint':newLinkPointHTML, 'authorURL': self.current_user.url, 'author': newVersion.authorName, 'dateEdited': newVersion.PSTdateEdited.strftime('%b. %d, %Y, %I:%M %p'), }) else: json.dumps({'result': False, 'error': 'There was a problem updating the point.'}) else: resultJSON = json.dumps({'result': 'User not logged in. ACCESS DENIED!'}) self.response.out.write(resultJSON)
def post(self): self.response.headers["Content-Type"] = "application/json; charset=utf-8" resultJSON = json.dumps({"result": False}) supportingPoint, supportingPointRoot = Point.getCurrentByUrl(self.request.get("supportingPointURL")) oldPoint, oldPointRoot = Point.getCurrentByUrl(self.request.get("parentPointURL")) user = self.current_user linkType = self.request.get("linkType") if user: try: # This code is if the vote existed before and the point was unlinked, and now # it is being re-linked voteCount, rating, myVote = RelevanceVote.getExistingVoteNumbers( oldPointRoot.key, supportingPointRoot.key, linkType, user ) supportingPoint._relevanceVote = myVote linkType = self.request.get("linkType") newLink = [ { "pointRoot": supportingPointRoot, "pointCurrentVersion": supportingPoint, "linkType": linkType, "voteCount": voteCount, "fRating": rating, } ] newVersion = oldPoint.update(pointsToLink=newLink, user=user) user.addRelevanceVote(oldPointRoot.key.urlsafe(), supportingPointRoot.key.urlsafe(), linkType, 100) # get my vote for this point, to render it in the linkPoint template supportingPoint.addVote(user) except WhysaurusException as e: resultJSON = json.dumps({"result": False, "error": e.message}) else: if newVersion: newLinkPointHTML = self.template_render( "linkPoint.html", {"point": supportingPoint, "linkType": linkType} ) resultJSON = json.dumps( { "result": True, "numLinkPoints": newVersion.linkCount(linkType), "newLinkPoint": newLinkPointHTML, "authorURL": self.current_user.url, "author": newVersion.authorName, "dateEdited": newVersion.PSTdateEdited.strftime("%b. %d, %Y, %I:%M %p"), } ) else: json.dumps({"result": False, "error": "There was a problem updating the point."}) else: resultJSON = json.dumps({"result": "User not logged in. ACCESS DENIED!"}) self.response.out.write(resultJSON)
def post(self): jsonOutput = {'result': False} user = self.current_user linkType = self.request.get('linkType') sourcesURLs=json.loads(self.request.get('sourcesURLs')) sourcesNames=json.loads(self.request.get('sourcesNames')) if user: try: parentPointURL = self.request.get('pointUrl') oldPoint, oldPointRoot = Point.getCurrentByUrl(parentPointURL) if oldPointRoot: newPoint, newLinkPoint = Point.addSupportingPoint( oldPointRoot=oldPointRoot, title=self.request.get('title'), content=self.request.get('content'), summaryText=self.request.get('plainText'), user=user, # backlink=oldPoint.key.parent(), linkType = linkType, imageURL=self.request.get('imageURL'), imageAuthor=self.request.get('imageAuthor'), imageDescription=self.request.get('imageDescription'), sourcesURLs=sourcesURLs, sourcesNames=sourcesNames ) else: raise WhysaurusException('Point with URL %s not found' % parentPointURL) except WhysaurusException as e: jsonOutput = { 'result': False, 'errMessage': str(e) } else: ReportEvent.queueEventRecord(user.key.urlsafe(), newLinkPoint.key.urlsafe(), newPoint.key.urlsafe(), "Create Point") newLinkPointHTML = self.template_render('linkPoint.html', { 'point': newLinkPoint, 'linkType': linkType }) jsonOutput = { 'result': True, 'version': newPoint.version, 'author': newPoint.authorName, 'dateEdited': newPoint.PSTdateEdited.strftime('%b. %d, %Y, %I:%M %p'), 'numLinkPoints': newPoint.linkCount(linkType), 'newLinkPoint': newLinkPointHTML, 'authorURL': self.current_user.url } self.response.headers["Content-Type"] = 'application/json; charset=utf-8' self.response.out.write(json.dumps(jsonOutput)) else: self.response.out.write('Need to be logged in')
def get_sole_points(front: Person, side: Person) -> Tuple[Point, Point]: front_sole_row = (front.leg.calf.right[0].max() + front.all[0].max()) // 2 front_sole_cols = np.where(front.all[0] == front_sole_row) front_sole_col = front.all[1][front_sole_cols[0].min()] side_sole_row = side.all[0].max() side_sole_cols = np.where(side.all[0] == side.all[0].max()) side_sole_col = side.all[1][side_sole_cols[0].min()] front_sole_point = Point(front_sole_col, front_sole_row) side_sole_point = Point(side_sole_col, side_sole_row) return front_sole_point, side_sole_point
def saveComment(self): results = {'result': False} text = self.request.get('commentText') pointRootUrlsafe = self.request.get('p') parentCommentUrlsafe = self.request.get('parentKey') user = self.current_user if user: try: pointRoot = PointRoot.getByUrlsafe(pointRootUrlsafe) if pointRoot: comment = Comment.create(text, user, pointRoot, parentCommentUrlsafe) if comment: pst_date = PST.convert(comment.date) results = { 'result': True, 'userName': user.name, 'userURL': user.url, 'avatar_url': user.avatar_url if hasattr(user, 'avatar_url') else '/static/img/icon_triceratops_black_47px.png', 'text': text, 'date': pst_date.strftime('%b. %d, %Y, %I:%M %p'), 'parentUrlsafe': parentCommentUrlsafe, 'myUrlSafe': comment.key.urlsafe(), 'level': comment.level } Point.addNotificationTask(pointRoot.key, user.key, 3, text) else: results[ 'error'] = 'Unable to find the point to add this comment' except WhysaurusException as e: results['error'] = str(e) resultJSON = json.dumps(results) self.response.headers[ "Content-Type"] = 'application/json; charset=utf-8' self.response.out.write(resultJSON)
def relevanceVote(self): resultJSON = json.dumps({'result': False}) parentRootURLsafe = self.request.get('parentRootURLsafe') childRootURLsafe = self.request.get('childRootURLsafe') linkType = self.request.get('linkType') vote = self.request.get('vote') user = self.current_user if int(vote) > 100 or int(vote) < 0: resultJSON = json.dumps({'result': False, 'error':'Vote value out of range.'}) # logging.info('ABOUT TO CHECK ALL THE DATA 1:%s 2:%s 3:%s 4:%s ' % (parentRootURLsafe,childRootURLsafe,linkType, vote)) elif parentRootURLsafe and childRootURLsafe and linkType and user: result, newRelevance, newVoteCount = user.addRelevanceVote( parentRootURLsafe, childRootURLsafe, linkType, int(vote)) if result: # Hacky, parent score retrieval could be pushed into addRelevanceVote parentNewScore = None parentPoint, parentPointRoot = Point.getCurrentByRootKey(parentRootURLsafe) if parentPoint: parentNewScore = parentPoint.pointValue() else: parentNewScore = -999 resultJSON = json.dumps({ 'result': True, 'newVote': vote, 'newRelevance': str(newRelevance) + '%', 'newVoteCount': newVoteCount, 'parentNewScore': parentNewScore }) self.response.headers["Content-Type"] = 'application/json; charset=utf-8' self.response.out.write(resultJSON)
def checkNamespace(self, areaName): bigMessage = [] noErrors = 0 pointCount = 0 bigMessage.append("ooooooooooooooooooooooooooooooooooooooooooooooooooo") bigMessage.append(" NAMESPACE: " + areaName) bigMessage.append("ooooooooooooooooooooooooooooooooooooooooooooooooooo") namespace_manager.set_namespace(areaName) # Take every point version query = Point.query() for point in query.iter(): foundError, newMessages = self.checkPoint(point) bigMessage = bigMessage + newMessages if not foundError: noErrors = noErrors + 1 pointCount = pointCount + 1 bigMessage.append( "%d points checked. No errors detected in %d points" % (pointCount, noErrors)) noErrors = 0 rootCount = 0 query = PointRoot.query() for pointRoot in query.iter(): foundError, newMessages = self.checkRoot(pointRoot) bigMessage = bigMessage + newMessages if not foundError: noErrors = noErrors + 1 rootCount = rootCount + 1 bigMessage.append( "%d roots checked. No errors detected in %d roots" % (rootCount, noErrors)) return bigMessage
def get(self): query = Point.query() i = 0 for point in query.iter(): if point.supportingPoints: for pointKey in point.supportingPoints: point.supportingPointsRoots.append(pointKey) point.supportingPoints = [] for rootKey in point.supportingPointsRoots: root = rootKey.get() if root: pointVer = root.getCurrent() point.supportingPointsLastChange.append(pointVer.key) else: logging.info('ROOTKEY %s WAS NOT FOUND' % rootKey) else: point.supportingPointsRoots = [] point.supportingPointsLastChange = [] point.put() logging.info('Updating %s' % point.title) i = i + 1 template_values = {'message': "Edits made: %d" % i} path = os.path.join(os.path.dirname(__file__), '../templates/message.html') self.response.out.write(template.render(path, template_values))
def get_arm_points(front: Person) -> Tuple[Point, Point]: try: shoulder_point = Point(front.arm.right.upper[1][0], front.arm.right.upper[0][0]) except: raise MeasureKeypointsFailedException('front.shoulder_point') try: right_inner_wrist_point = Point(front.arm.right.lower[1][-1], front.arm.right.lower[0][-1]) except: raise MeasureKeypointsFailedException('front.wrist_right_in') return shoulder_point, right_inner_wrist_point
def post(self): user = self.current_user resultJSON = json.dumps({'result': False, 'error': 'Not authorized'}) if user: if not self.request.get('title'): resultJSON = json.dumps({'result': False, 'error': 'Your point must have a title'}) else: sourcesURLs=json.loads(self.request.get('sourcesURLs')) if self.request.get('sourcesURLs') else None sourcesNames=json.loads(self.request.get('sourcesNames')) if self.request.get('sourcesNames') else None newPoint, newPointRoot = Point.create( title=self.request.get('title'), nodetype=self.request.get('nodetype'), content=self.request.get('content'), summaryText=self.request.get('plainText'), user=user, imageURL=self.request.get('imageURL'), imageAuthor=self.request.get('imageAuthor'), imageDescription=self.request.get('imageDescription'), sourceURLs=sourcesURLs, sourceNames=sourcesNames) if newPoint: resultJSON = json.dumps({'result': True, 'pointURL': newPoint.url, 'rootKey': newPointRoot.key.urlsafe()}) else: resultJSON = json.dumps({'result': False, 'error': 'Failed to create point.'}) else: resultJSON = json.dumps({'result': False, 'error': 'You appear not to be logged in.'}) self.response.headers.add_header('content-type', 'application/json', charset='utf-8') self.response.out.write(resultJSON)
def relevanceVote(self): resultJSON = json.dumps({'result': False}) parentRootURLsafe = self.request.get('parentRootURLsafe') childRootURLsafe = self.request.get('childRootURLsafe') linkType = self.request.get('linkType') vote = self.request.get('vote') user = self.current_user if int(vote) > 100 or int(vote) < 0: resultJSON = json.dumps({'result': False, 'error':'Vote value out of range.'}) # logging.info('ABOUT TO CHECK ALL THE DATA 1:%s 2:%s 3:%s 4:%s ' % (parentRootURLsafe,childRootURLsafe,linkType, vote)) elif parentRootURLsafe and childRootURLsafe and linkType and user: result, newRelevance, newVoteCount = user.addRelevanceVote( parentRootURLsafe, childRootURLsafe, linkType, int(vote)) if result: # Hacky, parent score retrieval could be pushed into addRelevanceVote parentNewScore = None parentPoint, parentPointRoot = Point.getCurrentByRootKey(parentRootURLsafe) if parentPoint: parentNewScore = parentPoint.pointValue() else: parentNewScore = 17 resultJSON = json.dumps({ 'result': True, 'newVote': vote, 'newRelevance': str(newRelevance) + '%', 'newVoteCount': newVoteCount, 'parentNewScore': parentNewScore }) self.response.headers["Content-Type"] = 'application/json; charset=utf-8' self.response.out.write(resultJSON)
def checkDBPointRoot(pointRoot): logging.info('Checking %s ' % pointRoot.url) point, pr = Point.getCurrentByUrl(pointRoot.url) isError1 = False isError2 = False messages1 = [] messages2 = [] dbc = DBIntegrityCheck() if point: isError1, messages1 = dbc.checkPoint(point) if pointRoot: isError2, messages2 = dbc.checkRoot(pointRoot) if not isError1 and not isError2: message = 'No errors were found in %s.' % pointRoot.url logging.info(message) else: message = [] if messages1: message = message + messages1 if messages2: message = message + messages2 if message == []: message = ['Errors generated, but no messages generated.'] if isError1: logging.info(messages1) if isError2: logging.info(messages2) for m in message: logging.info(message) return message
def post(self): jsonOutput = {'result': False} user = self.current_user titles = json.loads(self.request.get('titles')) levels = json.loads(self.request.get('levels')) dataRefs = json.loads(self.request.get('dataRefs')) furtherInfos = json.loads(self.request.get('furtherInfos')) sources = json.loads(self.request.get('sources')) pointsData = processTreeArrays(titles, levels, dataRefs, furtherInfos, sources) if user: try: newMainPoint, newMainPointRoot = Point.createTree(pointsData, user) except WhysaurusException as e: jsonOutput = { 'result': False, 'err': str(e) } else: jsonOutput = { 'result': True, 'url': newMainPoint.url, 'rootKey': newMainPointRoot.key.urlsafe() } resultJSON = json.dumps(jsonOutput) logging.info('Tree %s' % resultJSON) else: resultJSON = json.dumps({'result': False, 'error': 'You appear not to be logged in.'}) self.response.headers["Content-Type"] = 'application/json; charset=utf-8' self.response.out.write(resultJSON)
def post(self): resultJSON = json.dumps({'result': False}) searchResultsFuture = Point.search( searchTerms=self.request.get('searchTerms'), user=self.current_user, excludeURL=self.request.get('exclude'), linkType=self.request.get('linkType') ) searchResults = None if searchResultsFuture: searchResults = searchResultsFuture.get_result() template_values = { 'points': searchResults, 'linkType': self.request.get('linkType'), } resultsHTML = self.template_render('pointBoxList.html', template_values) if searchResults: resultJSON = json.dumps({ 'result': True, 'resultsHTML': resultsHTML, 'searchString': self.request.get('searchTerms') }) self.response.headers["Content-Type"] = 'application/json; charset=utf-8' self.response.out.write(resultJSON)
def resolve_search(self, info, **args): searchResultsFuture = PointModel.search(user=info.context.current_user, searchTerms="\"" + (args['query'] or "") + "\"") searchResults = searchResultsFuture.get_result( ) if searchResultsFuture else [] return searchResults
def resolve_full_claim_search(self, info, **args): searchResultsFuture = PointModel.search(user=info.context.current_user, searchTerms="\"" + (args['q'] or "") + "\"") searchResults = searchResultsFuture.get_result( ) if searchResultsFuture else [] return PagedPoints(points=searchResults, hasMore=False)
def checkDBPoint(self, pointURL): point, pointRoot = Point.getCurrentByUrl(pointURL) if point: isError1, messages1 = self.checkPointNew(point) if pointRoot: isError2, messages2 = self.checkRoot(pointRoot) if not isError1 and not isError2: message = 'No errors were found.' else: messages = [] if messages1: messages += messages1 if messages2: messages += messages2 if messages == []: messages = ['Errors generated, but no messages generated.'] template_values = { 'messages': messages, 'user': self.current_user, 'currentArea': self.session.get('currentArea') } self.response.out.write( self.template_render('message.html', template_values))
def get(self): query = Point.query() i = 0 for point in query.iter(): if point.supportingPoints: for pointKey in point.supportingPoints: point.supportingPointsRoots.append(pointKey) point.supportingPoints = [] for rootKey in point.supportingPointsRoots: root = rootKey.get() if root: pointVer = root.getCurrent() point.supportingPointsLastChange.append(pointVer.key) else: logging.info('ROOTKEY %s WAS NOT FOUND' % rootKey) else: point.supportingPointsRoots = [] point.supportingPointsLastChange = [] point.put() logging.info('Updating %s' % point.title) i = i + 1 template_values = { 'message': "Edits made: %d" % i } path = os.path.join(os.path.dirname(__file__), '../templates/message.html') self.response.out.write(template.render(path, template_values))
def post(self): resultJSON = json.dumps({'result': False}) if self.current_user: if self.current_user.isLimited: resultJSON = json.dumps({'result': False, 'error': 'This account cannot unlink points.'}) elif self.request.get('mainPointURL'): mainPoint, pointRoot = Point.getCurrentByUrl(self.request.get('mainPointURL')) if self.request.get('supportingPointURL'): supportingPointURL = self.request.get('supportingPointURL') newVersion = mainPoint.unlink(self.request.get('supportingPointURL'), self.request.get('linkType'), self.current_user) if newVersion: resultJSON = json.dumps({ 'result': True, 'pointURL': supportingPointURL, 'authorURL': self.current_user.url, 'author': newVersion.authorName, 'dateEdited': newVersion.PSTdateEdited.strftime('%b. %d, %Y, %I:%M %p'), }) else: resultJSON = json.dumps({'result': False, 'error': 'URL of main point was not supplied.'}) else: resultJSON = json.dumps({'result': False, 'error': 'You appear not to be logged in.'}) self.response.headers["Content-Type"] = 'application/json; charset=utf-8' self.response.out.write(resultJSON)
def checkDBPoint(self, pointURL): point, pointRoot = Point.getCurrentByUrl(pointURL) if point: isError1, messages1 = self.checkPointNew(point) if pointRoot: isError2, messages2 = self.checkRoot(pointRoot) if not isError1 and not isError2: message = 'No errors were found.' else: messages = [] if messages1: messages += messages1 if messages2: messages += messages2 if messages == []: messages = ['Errors generated, but no messages generated.'] template_values = { 'messages': messages, 'user': self.current_user, 'currentArea':self.session.get('currentArea') } self.response.out.write(self.template_render('message.html', template_values))
def cell_is_free(self, x, y): try: if self.grid[y][x] == "*": raise WrongMove("This cell is a part of the board grid.") return Point(x, y) except KeyError: raise WrongMove("This cell is outside of the board grid.")
def post(self): resultJSON = json.dumps({'result': False}) searchResultsFuture = Point.search( searchTerms=self.request.get('searchTerms'), user=self.current_user, excludeURL=self.request.get('exclude'), linkType=self.request.get('linkType')) searchResults = None if searchResultsFuture: searchResults = searchResultsFuture.get_result() template_values = { 'points': searchResults, 'linkType': self.request.get('linkType'), } resultsHTML = self.template_render('pointBoxList.html', template_values) if searchResults: resultJSON = json.dumps({ 'result': True, 'resultsHTML': resultsHTML, 'searchString': self.request.get('searchTerms') }) self.response.headers[ "Content-Type"] = 'application/json; charset=utf-8' self.response.out.write(resultJSON)
def post(self): jsonOutput = {'result': False} user = self.current_user titles = json.loads(self.request.get('titles')) levels = json.loads(self.request.get('levels')) dataRefs = json.loads(self.request.get('dataRefs')) furtherInfos = json.loads(self.request.get('furtherInfos')) sources = json.loads(self.request.get('sources')) pointsData = processTreeArrays(titles, levels, dataRefs, furtherInfos, sources) if user: try: newMainPoint, newMainPointRoot = Point.createTree(pointsData, user) except WhysaurusException as e: jsonOutput = { 'result': False, 'err': str(e) } else: jsonOutput = { 'result': True, 'url': newMainPoint.url, 'rootKey': newMainPointRoot.key.urlsafe() } resultJSON = json.dumps(jsonOutput) logging.info('Tree %s' % resultJSON) else: resultJSON = json.dumps({'result': False, 'error': 'You appear not to be logged in.'}) self.response.headers.add_header('content-type', 'application/json', charset='utf-8') self.response.out.write(resultJSON)
def mutate(self, info, parentURL, url, linkType): user = info.context.current_user point, point_root = PointModel.getCurrentByUrl(parentURL) new_version = point.unlink(url, linkType, user) if new_version: return Unlink(parentURL=parentURL, url=url) else: raise Exception(str('unlink failed:'))
def mutate(self, info, url): user = info.context.current_user point, point_root = PointModel.getCurrentByUrl(url) result, msg = point_root.delete(user) if result: return Delete(url=url) else: raise Exception(str('delete failed: ' + msg))
def post(self): resultJSON = json.dumps({'result': False}) point, pointRoot = Point.getCurrentByUrl(self.request.get('pointURL')) user = self.current_user if point and user: if user.addVote(point, int(self.request.get('vote'))): resultJSON = json.dumps({'result': True, 'newVote': self.request.get('vote')}) self.response.headers.add_header('content-type', 'application/json', charset='utf-8') self.response.out.write(resultJSON)
def indClearLowQualityFlags(cursor=None, num_updated=0, batch_size=250, cntUpdatedNet=0, namespace=None, namespaces=None): logging.info('ClearLowQuality Update: Start: %d Batch: %d Namespace: %s' % (num_updated, batch_size, namespace)) if namespace: previous_namespace = namespace_manager.get_namespace() namespace_manager.set_namespace(namespace) else: previous_namespace = None try: query = Point.query() points, next_cursor, more = query.fetch_page(batch_size, start_cursor=cursor) cnt = 0 cntSkip = 0 cntUpdate = 0 # for p in query.iter(): for p in points: cnt += 1 # if p.isLowQualityAdmin == False: # cntSkip += 1 # continue if p.isLowQualityAdmin: cntUpdate += 1 p.isLowQualityAdmin = False p.put() logging.info('ClearLowQuality Incremental: Count: %d Updated: %d Skipped: %d' % (cnt, cntUpdate, cntSkip)) finally: if previous_namespace: namespace_manager.set_namespace(previous_namespace) # If there are more entities, re-queue this task for the next page. if more: deferred.defer(indClearLowQualityFlags, cursor=next_cursor, num_updated=(num_updated + cnt), batch_size=batch_size, cntUpdatedNet=(cntUpdatedNet + cntUpdate), namespace=namespace, namespaces=namespaces) else: logging.warning('ClearLowQuality Complete! - Net Updated: %d Namespace: %s' % (cntUpdatedNet + cntUpdate, namespace)) if namespaces and len(namespaces) > 0: nextNamespace = namespaces[0] del namespaces[0] logging.warning('ClearLowQuality: Next Namespace: %s Count: %d' % (nextNamespace, len(namespaces))) deferred.defer(indClearLowQualityFlags, cursor=None, num_updated=0, batch_size=batch_size, cntUpdatedNet=0, namespace=nextNamespace, namespaces=namespaces)
def post(self): resultJSON = json.dumps({'result': False}) point, pointRoot = Point.getCurrentByUrl(self.request.get('pointURL')) user = self.current_user newRibbonValue = self.request.get('ribbon') == 'true' if point and user: if user.setRibbon(point, newRibbonValue): resultJSON = json.dumps({'result': True, 'ribbonTotal': point.ribbonTotal}) self.response.headers.add_header('content-type', 'application/json', charset='utf-8') self.response.out.write(resultJSON)
def post(self): user = self.current_user if user: resultJSON = json.dumps({"result": False}) oldPoint, oldPointRoot = Point.getCurrentByUrl(self.request.get("urlToEdit")) sourcesURLs = json.loads(self.request.get("sourcesURLs")) if self.request.get("sourcesURLs") else None sourcesNames = json.loads(self.request.get("sourcesNames")) if self.request.get("sourcesNames") else None sourcesToRemove = ( json.loads(self.request.get("sourcesToRemove")) if self.request.get("sourcesToRemove") else None ) if oldPoint == None: resultJSON = json.dumps( {"result": False, "error": "Unable to edit point. Please refresh the page and try again."} ) elif user.isLimited: resultJSON = json.dumps({"result": False, "error": "This account cannot edit points."}) else: sources = Source.constructFromArrays(sourcesURLs, sourcesNames, oldPoint.key) newVersion = oldPoint.update( newTitle=self.request.get("title"), newContent=self.request.get("content"), newSummaryText=self.request.get("plainText"), user=self.current_user, imageURL=self.request.get("imageURL"), imageAuthor=self.request.get("imageAuthor"), imageDescription=self.request.get("imageDescription"), sourcesToAdd=sources, sourceKeysToRemove=sourcesToRemove, ) if newVersion: sources = newVersion.getSources() sourcesHTML = self.template_render("sources.html", {"sources": sources}) resultJSON = json.dumps( { "result": True, "version": newVersion.version, "author": newVersion.authorName, "authorURL": self.current_user.url, "dateEdited": newVersion.PSTdateEdited.strftime("%b. %d, %Y, %I:%M %p"), "pointURL": newVersion.url, "imageURL": newVersion.imageURL, "imageAuthor": newVersion.imageAuthor, "imageDescription": newVersion.imageDescription, "sourcesHTML": sourcesHTML, } ) ReportEvent.queueEventRecord(user.key.urlsafe(), newVersion.key.urlsafe(), None, "Edit Point") else: # This is the only way newVersion will fail resultJSON = json.dumps({"result": False, "error": "You appear not to be logged in."}) self.response.headers["Content-Type"] = "application/json; charset=utf-8" self.response.out.write(resultJSON)
def post(self): resultJSON = json.dumps({'result': False}) point, pointRoot = Point.getCurrentByUrl(self.request.get('pointURL')) parentPointURL = self.request.get('parentPointURL') parentPoint = None if parentPointURL: parentPoint, parentPointRoot = Point.getCurrentByUrl(parentPointURL) user = self.current_user if point and user: if user.addVote(point, int(self.request.get('vote'))): point.updateBacklinkedSorts(pointRoot) parentNewScore = None if parentPoint: parentNewScore = parentPoint.pointValue() resultJSON = json.dumps({'result': True, 'newVote': self.request.get('vote'), 'newScore': point.pointValue(), 'parentNewScore': parentNewScore}) self.response.headers["Content-Type"] = 'application/json; charset=utf-8' self.response.out.write(resultJSON)
def post(self): user = self.current_user if user: resultJSON = json.dumps({'result': False}) oldPoint, oldPointRoot = Point.getCurrentByUrl(self.request.get('urlToEdit')) sourcesURLs=json.loads(self.request.get('sourcesURLs')) \ if self.request.get('sourcesURLs') else None sourcesNames=json.loads(self.request.get('sourcesNames')) \ if self.request.get('sourcesNames') else None sourcesToRemove=json.loads(self.request.get('sourcesToRemove')) \ if self.request.get('sourcesToRemove') else None if oldPoint == None: resultJSON = json.dumps({'result': False, 'error': 'Unable to edit point. Please refresh the page and try again.'}) elif user.isLimited: resultJSON = json.dumps({'result': False, 'error': 'This account cannot edit points.'}) else: sources = Source.constructFromArrays(sourcesURLs, sourcesNames, oldPoint.key) newVersion = oldPoint.update( newTitle=self.request.get('title'), newContent=self.request.get('content'), newSummaryText=self.request.get('plainText'), user=self.current_user, imageURL=self.request.get('imageURL'), imageAuthor=self.request.get('imageAuthor'), imageDescription=self.request.get('imageDescription'), sourcesToAdd=sources, sourceKeysToRemove= sourcesToRemove ) if newVersion: sources = newVersion.getSources() sourcesHTML = self.template_render('sources.html', {'sources':sources}) resultJSON = json.dumps({ 'result': True, 'version': newVersion.version, 'author': newVersion.authorName, 'authorURL': self.current_user.url, 'dateEdited': newVersion.PSTdateEdited.strftime('%b. %d, %Y, %I:%M %p'), 'pointURL':newVersion.url, 'imageURL': newVersion.imageURL, 'imageAuthor': newVersion.imageAuthor, 'imageDescription': newVersion.imageDescription, 'sourcesHTML': sourcesHTML }) ReportEvent.queueEventRecord(user.key.urlsafe(), newVersion.key.urlsafe(), None, "Edit Point") else: # This is the only way newVersion will fail resultJSON = json.dumps({'result': False, 'error': 'You appear not to be logged in.'}) self.response.headers["Content-Type"] = 'application/json; charset=utf-8' self.response.out.write(resultJSON)
def addMissingBacklinks(self, pointURL): point, pointRoot = Point.getCurrentByUrl(pointURL) if point: rootsAdded = point.addMissingBacklinks() message = 'Added %d missing roots to links of %s' % (rootsAdded, point.title) else: message = 'Could not find point' template_values = { 'message': message, 'user': self.current_user, 'currentArea':self.session.get('currentArea') } self.response.out.write(self.template_render('message.html', template_values))
def post(self): resultJSON = json.dumps({'result': False}) if self.request.get('mainPointURL'): mainPoint, pointRoot = Point.getCurrentByUrl(self.request.get('mainPointURL')) if self.request.get('supportingPointURL'): supportingPointURL = self.request.get('supportingPointURL') newVersion = mainPoint.unlink(self.request.get('supportingPointURL'), self.request.get('linkType'), self.current_user) if newVersion: resultJSON = json.dumps({'result': True, 'pointURL': supportingPointURL}) self.response.headers.add_header('content-type', 'application/json', charset='utf-8') self.response.out.write(resultJSON)
def cleanDeadBacklinks(self, pointURL): point, pointRoot = Point.getCurrentByUrl(pointURL) if pointRoot: rootsRemoved = pointRoot.removeDeadBacklinks() message = 'Removed %d dead roots from %s' % (rootsRemoved, point.title) else: message = 'Could not find point' template_values = { 'message': message, 'user': self.current_user, 'currentArea':self.session.get('currentArea') } self.response.out.write(self.template_render('message.html', template_values))
def addMissingBacklinks(self, pointURL): point, pointRoot = Point.getCurrentByUrl(pointURL) if point: rootsAdded = point.addMissingBacklinks() message = 'Added %d missing roots to links of %s' % (rootsAdded, point.title) else: message = 'Could not find point' template_values = { 'message': message, 'user': self.current_user, 'currentArea':self.session.get('currentArea') } path = os.path.join(os.path.dirname(__file__), '../templates/message.html') self.response.out.write(template.render(path, template_values))
def reconcileVersionArrays(self, pointURL): point, pointRoot = Point.getCurrentByUrl(pointURL) if pointRoot: pointsRemoved = pointRoot.reconcileVersionArrays() message = 'Removed %d points from version root arrays in %s' % (pointsRemoved, point.title) else: message = 'Could not find point' template_values = { 'message': message, 'user': self.current_user, 'currentArea':self.session.get('currentArea') } path = os.path.join(os.path.dirname(__file__), '../templates/message.html') self.response.out.write(template.render(path, template_values))
def get(self): pointData = Point.getFullHistory(self.request.get('pointUrl')) template_values = { 'latestPoint': pointData[0]["point"] if pointData else None, 'numPoints': len(pointData) if pointData else 0, 'pointData': pointData, 'user': self.current_user, 'currentArea':self.session.get('currentArea') } path = os.path.join(constants.ROOT, 'templates/pointHistory.html') self.response.headers.add_header('content-type', 'application/json', charset='utf-8') self.response.out.write(json.dumps(template.render(path, template_values)))
def cleanEmptyLinks(self, pointURL): point, pointRoot = Point.getCurrentByUrl(pointURL) if pointRoot: linksRemoved, versionCount = pointRoot.cleanEmptyLinks() message = 'Removed %d dead links from structured link arrays in %d versions of %s' % \ (linksRemoved, versionCount, point.title) else: message = 'Could not find point' template_values = { 'message': message, 'user': self.current_user, 'currentArea':self.session.get('currentArea') } self.response.out.write(self.template_render('message.html', template_values))
def cleanDeadBacklinks(self, pointURL): point, pointRoot = Point.getCurrentByUrl(pointURL) if pointRoot: rootsRemoved = pointRoot.removeDeadBacklinks() message = 'Removed %d dead roots from %s' % (rootsRemoved, point.title) else: message = 'Could not find point' template_values = { 'message': message, 'user': self.current_user, 'currentArea':self.session.get('currentArea') } path = os.path.join(os.path.dirname(__file__), '../templates/message.html') self.response.out.write(template.render(path, template_values))
def getPointComments(self): resultJSON = json.dumps({'result': False}) newURL = None url = self.request.get('url') point, pointRoot = Point.getCurrentByUrl(url) if point is None: # Try to find a redirector newURL = RedirectURL.getByFromURL(url) if newURL: point, pointRoot = Point.getCurrentByUrl(url) if pointRoot: template_values = { 'user': self.current_user, 'pointRoot': pointRoot, 'comments':pointRoot.getComments() } html = self.template_render('pointComments.html', template_values) resultJSON = json.dumps({ 'result': True, 'html': html }) self.response.headers["Content-Type"] = 'application/json; charset=utf-8' self.response.out.write(resultJSON)