Example #1
0
File: views.py Project: nsu/caveman
def checkInClimber(user):
    print "checking in", user
    lastCheckIn = CheckIn.objects.filter(climber=user, checkOut=None)
    if lastCheckIn:
        raise ValueError

    checkIn = CheckIn(climber=user)
    checkIn.save()
Example #2
0
def add_checkin(nhi, data):
    c = CheckIn(**data)
    c.patient_nhi = nhi

    db.add(c)
    db.commit()

    if c.patient.latest_checkin_time is None or c.checkin_time > c.patient.latest_checkin_time:
        c.patient.latest_checkin_time = c.checkin_time

    db.commit()
    return c
Example #3
0
def checkin_new():
    checkin = CheckIn()
    if request.method == 'POST':
        form = CheckInForm(request.form, obj=checkin)
        if form.validate():
            try:
                form.populate_obj(checkin)
                validate_check_in_creation(checkin)
                checkin.save()
                flash('Yes, check in feito com sucesso.', 'success')
                return redirect(url_for('checkins.checkin_index'))
            except AttributeError as e:
                flash(str(e), 'warning')
    else:
        form = CheckInForm(obj=checkin)
    return render_template('checkins/new.html', form=form)
Example #4
0
def add_checkin_to_chart(request, chart_id=None, chart=None):
    if request.method == 'POST':
        check_in = CheckIn(chart=chart)
        form = AddCheckInForm(request.POST, instance=check_in)
        if form.is_valid():
            check_in.save()
            return {'checkIn': check_in, 
                    'chartData': _chart_data(request, chart=chart)}
        else:
            if form.errors.has_key('number'):
                error_message = form.errors['number']
            else:
                error_message = 'invalid check in'
            raise ValidationError(error_message)
    else:
        return {}
Example #5
0
def populate_database(num_patients, min_checkins, max_checkins):
    """
    Generates a number of Patients and a number of CheckIns per patient and
    stores them in the database.

    Arguments
    num_patients    -- the number of patients to generate
    min_checkins -- the minimum number of CheckIns to generate per Patient
    max_checkins -- the maximum number of CheckIns to generate per Patient

    """
    departments = [
        Department(department_name="Cardiology"),
        Department(department_name="Emergency"),
        Department(department_name="Gynecology"),
        Department(department_name="Pediatrics"),
        Department(department_name="Obstetrics"),
        Department(department_name="Oncology"),
        Department(department_name="Orthopedics"),
        Department(department_name="Neurology")
    ]

    for i in xrange(num_patients):
        patient = Patient(**generate_patient())
        patient.departments.append(choice(departments))
        db.add(patient)

        for j in xrange(randrange(min_checkins, max_checkins)):
            checkin = CheckIn(**generate_checkin())
            checkin.patient_nhi = patient.nhi

            lci = patient.latest_checkin_time
            vid = checkin.checkin_time

            lci = vid if lci is None or vid > lci else lci
            patient.latest_checkin_time = lci

            db.add(checkin)

        for k in xrange(randrange(0, 3)):
            appointment = Appointment(**generate_appointment())
            appointment.patient_nhi = patient.nhi

            db.add(appointment)

    db.commit()
Example #6
0
def dataInsertCheckIn(tweetId,fingerprint):
    tweetId = str(tweetId)
    dt_stamp = timezone.now()
    #stamp = dt_stamp.strftime('%Y-%m-%d %H:%M:%S')
    try:
        print "%s--%s--%s" % (fingerprint,dt_stamp.strftime("%Y%m%d%H%M%S"),tweetId)
        checkin = CheckIn(fingerprint=fingerprint, stamp=dt_stamp, tweetId=tweetId)
        checkin.save()
        print "pido con el id: %s" % tweetId
        call = tweetGeo.objects.get(tweetId=tweetId)
        call.relevanceFirst += 1
        call.save()
        print "OK"
        return {"code":"OK","count":call.relevanceFirst}
    except Exception as e:
        print e
        return {"code":"KO"}
Example #7
0
def predicate4(user, lecture, checkin):
	# finds all check ins for the same lecture, by other students
	checkinQuery = CheckIn.query().filter(CheckIn.lecture.day == lecture.day, CheckIn.lecture.time == lecture.time, CheckIn.lecture.week == getCurrentWeek(), CheckIn.lecture.module == lecture.module, CheckIn.student.userid != user.userid)
	for otherCheckin in checkinQuery:
		# checks if any were made earlier than this check in
		if otherCheckin.time < checkin.time:
			return False

	return True
Example #8
0
    def post(self, id):
        args = self.reqparse.parse_args()
        text = args["text"]
        
        # getting sentiment analysis from google nlp api
        annotations = get_sentiment(text)
        sentiment = annotations.document_sentiment.score

        # getting emotion from deepaffects text api
        emotion = list(json.loads(get_emotion(text).text)["response"].keys())[0]
        ketchup = CheckIn(id, text, sentiment, emotion)
        self.add_checkin_to_db(ketchup)
        most_common, average, slope, r2 = self.get_data(id)
        return jsonify({"emotion": emotion, "sentiment": sentiment, "most_freq_emotion": most_common, "average_sentiment": average, "slope": slope, "r2": r2})
Example #9
0
def checkin(nhi, checkin_id):
    checkin = CheckIn.query.filter_by(
        patient_nhi=nhi, checkin_id=checkin_id).first()

    if not checkin:
        return make_response("No checkin for patient {} with id {}".format(nhi, checkin_id))

    elif request.method == "GET":
        return jsonify(checkin.serialize())

    elif request.method == "POST":
        checkin_data = json.loads(request.data)
        checkin = CheckIn(**checkin_data)
        checkin.checkin_id = checkin_id
        checkin = db.merge(checkin)
        db.commit()

        return jsonify(checkin.serialize())

    elif request.method == "DELETE":
        db.delete(checkin)
        db.commit()

        return make_response("Deleted checkin: {} from patient: {}".format(checkin_id, nhi), 200)
Example #10
0
def check_in(MealId):

    try:
        meal = session.query(Meal).filter(Meal.MealId == MealId).first()
        canCheckInBool = session.query(CheckIn).filter(
            CheckIn.MealId == MealId,
            CheckIn.Email == current_user.Email).first() is not None

        # Check if Member is in the time frame to check-in for a meal
        if can_check_in(meal, canCheckInBool) and has_swipes():
            checkIn = CheckIn(MealId=MealId,
                              Email=current_user.Email,
                              Timestamp=datetime.datetime.now(),
                              IsLatePlate=False)

            # Check if user already is checked in
            if session.query(CheckIn).filter(CheckIn.MealId == checkIn.MealId,
                                             CheckIn.Email
                                             == checkIn.Email).first() is None:
                session.add(checkIn)
                session.commit()

                meal = session.query(Meal).filter(
                    Meal.MealId == MealId).first()

                flash("Check In Was a Success!")
                return render_template('pages/view_checkin.html', meal=meal)
            else:
                flash("You were already checked in for that meal."
                      )  # should never get here
        else:
            flash(
                "Cannot check-in for a meal more than 30 minutes before or after. Also, make sure you have swipes left this week."
            )
        return redirect(url_for("get_meal", mealId=MealId))
    except Exception as e:
        flash(
            "CheckIn for Meal with ID of {} was unsuccessful. Please try again. {}"
            .format(MealId, e))
        return redirect(url_for("get_meal", mealId=MealId))
Example #11
0
def late_plate(MealId):
    try:
        meal = session.query(Meal).filter(Meal.MealId == MealId).first()

        # Check if Member has swipes for late plate and MUST request before 5 PM the day before
        if can_rsvp(meal) and has_swipes():
            checkIn = CheckIn(MealId=MealId,
                              Email=current_user.Email,
                              Timestamp=datetime.datetime.now(),
                              IsLatePlate=True)

            # Check if user already is checked in
            if session.query(CheckIn).filter(CheckIn.MealId == checkIn.MealId,
                                             CheckIn.Email
                                             == checkIn.Email).first() is None:
                session.add(checkIn)
                session.commit()

                meal = session.query(Meal).filter(
                    Meal.MealId == MealId).first()

                flash("Late Plate Was a Success!")
                return redirect(url_for("get_meal", mealId=MealId))
            else:
                flash("You were already checked in for that meal."
                      )  # should never get here
        else:
            flash(
                "Cannot request a Late Plate after 5PM the day before. Also, make sure you have swipes left this week."
            )
        return redirect(url_for("get_meal", mealId=MealId))
    except Exception as e:
        flash(
            "Late Plate for Meal with ID of {} was unsuccessful. Please try again. {}"
            .format(MealId, e))
        return redirect(url_for("get_meal", mealId=MealId))
Example #12
0
 def test_invalid_check_in(self):
     checkin = CheckIn(check_out_time=date(2020, 9, 5))
     with self.assertRaises(AttributeError):
         validate_check_in_creation(checkin)
Example #13
0
	def post(self):
		user = users.get_current_user()
		if user:
			missedLectureCheck(user)
			#logging.info(self.request.body)
			data = json.loads(self.request.body)
			latitude = data["lat"]
			longitude = data["lon"]

			day = datetime.date.today().weekday()
			hour = datetime.datetime.now().hour
			minute = datetime.datetime.now().minute
			if minute > 45:
				hour = hour + 1

			thisLecture = None
			thisUser = None
			poly = []			

			userQuery = User.query(User.userid == user.user_id())
			for userEntity in userQuery:
				thisUser = userEntity
				for lecture in userEntity.lectures:
					#checks for a lecture that matches the current day and time
					if(lecture.day == day and (lecture.time <= hour and lecture.time + lecture.duration > hour)):
						thisLecture = lecture
						locations = lecture.location.split(";");
						for location in locations:
							#need to make multiple polys for each lecture, for each possible location
							buildingQuery = Building.query(Building.number == location)
							for building in buildingQuery:
								buildingCoords = []
								for coordinate in building.coordinates:
									c = (coordinate.lon, coordinate.lat)
									buildingCoords.append(c)
								poly.append(buildingCoords)

			noLecture = False
			checkedIn = False

			#checks if there is no current lecture
			if thisLecture is None:
				noLecture = True
				self.response.out.write(json.dumps({"valid":3}))
			else:
				#checks if the user has already checked in to this lecture
				for pastLecture in thisUser.history:
					if pastLecture.week == getCurrentWeek() and pastLecture.time == thisLecture.time and pastLecture.day == thisLecture.day:
						checkedIn = True
				if checkedIn:
					self.response.out.write(json.dumps({"valid":4}))	
			if not checkedIn and not noLecture:
				inBuilding = False
				for coords in poly:
					#checks user is at the correct location(s) for the lecture
					if not inBuilding and point_in_poly(longitude, latitude, coords):
						inBuilding = True

						attendedLecture = Lecture(module=thisLecture.module, title=thisLecture.title, location=thisLecture.location, day=thisLecture.day, time=thisLecture.time, duration=thisLecture.duration)

						attendedLecture.attended = True
						attendedLecture.week = getCurrentWeek()

						checkin = CheckIn(student=thisUser, lecture=attendedLecture)
						checkin.put()

						thisUser.history.append(attendedLecture)

						completedChalls = challengecheck(thisUser, attendedLecture, checkin)

						pointsEarned = 0
						
						challIcons = []
						challTitles = []
						challDescs = []
						challPoints = []

						for challenge in completedChalls:
							pointsEarned += challenge.points
							challTitles.append(challenge.title)
							challIcons.append(challenge.badge.iconName)
							challDescs.append(challenge.description)
							challPoints.append(challenge.points)

						thisUser.score = thisUser.score + 10 + thisUser.streak + pointsEarned
						thisUser.streak = thisUser.streak + 1
						thisUser.count = thisUser.count + 1

						thisUser.put()
						
						self.response.out.write(json.dumps({"valid":1, "score":thisUser.score, "count":thisUser.count, "streak":thisUser.streak, "icons":challIcons, "titles":challTitles, "points":challPoints, "descriptions":challDescs}))
				if not inBuilding: 
					self.response.out.write(json.dumps({"valid":2}))	
		else:
			self.redirect(users.create_login_url(self.request.uri))