示例#1
0
    def calc_rating(self, sims, test):
        pred = User("prediction")
        pred_nw = User('non weight prediction')
        sim_sum = 0

        for user, sim in sims:
            sim_sum += abs(sim)

            for book, rating in user.books.items():

                # filter out books rated by user count less than threshold
                if self.u_book_list[book].user_count < self.threshold:
                    rating = test.avg

                # sum ratings
                if book not in pred.books.keys():
                    pred_nw.append_book(book, rating)
                    pred.append_book(book, (rating * abs(sim)))
                else:
                    pred_nw.books[book] += rating
                    pred.books[book] += (rating * abs(sim))

        # mean
        for book in pred.books.keys():
            pred_nw.books[book] /= self.K
            pred.books[book] /= (sim_sum if sim_sum != 0 else self.K)

        return pred, pred_nw
示例#2
0
def get_user_info():
    """
    gets the user info from the database from a uni
    returns a new User object

    """
    user = users.get_current_user()
    uni = email_to_uni(user.email())

    db = connect_to_cloudsql()
    cursor = db.cursor()
    cursor.execute('use cuLunch')

    
    query = "SELECT u.uni, u.name, u.schoolYear, u.interests, u.schoolName FROM users u WHERE u.uni='{}'".format(uni)
    
    try:
        cursor.execute(query)
        
    except:
        print("SELECT for getting user info failed!")

    if not cursor.rowcount:
        raise ValueError("User {} not found in database!".format(uni))

    r = cursor.fetchone()
    db.close()
    
    return User(r[0], r[1], r[2], r[3], r[4])
示例#3
0
def output():
    user = users.get_current_user()

    # can't see listings if you don't have an account :^)
    if not user or not check_registered_user(email_to_uni(user.email())):
        return redirect("/")

    # then fetch the listings
    # TODO: make this a self-contained function to get listings of not a current UNI?
    uni = email_to_uni(user.email())

    
    db = connect_to_cloudsql()
    cursor = db.cursor()
    cursor.execute('use cuLunch')

    # grab the relevant information and make sure the user doesn't see their own listings there
    query = "SELECT u.uni, u.name, u.schoolYear, u.interests, u.schoolName, l.expiryTime, l.needsSwipes, l.Place from " \
            "users u JOIN listings l ON u.uni=l.uni WHERE NOT u.uni = '{}' ORDER BY l.expiryTime".format(uni)

    me = find_user(uni)
    try:
        cursor.execute(query)
        
    except:
        print("SELECT for listings failed!")
        
    swipes = 0
    num_listings = 0
    posts = []
    for r in cursor.fetchall():
        u = User(r[0], r[1], r[2], r[3], r[4])
        # we need to convert datetime into a separate date and time for the listing object
        l = Listing(r[5], r[0], r[7], r[6])
        if l.expiryDateTime > (datetime.datetime.now() - timedelta(hours=4)):
            num_listings += 1
            if l.needSwipe:
                swipes += 1
            posts.append(ListingPost(l, u))
        print(str(l.expiryDateTime) + " ")

    db.close()
    d = get_popular_place()
    best_hall = d["place"]
    best_count = d["count"]

    # serve index template
    return render_template('/listings/index.html', numlistings = num_listings, swipes=swipes, current_user=me,
                           listingposts=posts, name=user.nickname(), logout_link=users.create_logout_url("/"),
                           best_hall=best_hall, best_count=best_count)
示例#4
0
def find_user(uni):
    db = connect_to_cloudsql()
    cursor = db.cursor()
    cursor.execute("use cuLunch")

    query = "SELECT u.uni, u.name, u.schoolYear, u.interests, u.schoolName from users u WHERE u.uni = '{}'".format(uni)
    u = None

    try:
        cursor.execute(query)
        
    except:
        print("SELECT for find_user failed!")

    for r in cursor.fetchall():
        u = User(r[0], r[1], r[2], r[3], schools[r[4]])

    db.close()
    return u
    def to_dict(self, columns):
        """ Transforms the dataframe into user and book object dictionary """
        # get distinct keys
        book_index = self.indexify('ISBN')
        user_index = self.indexify('User-ID')

        # get data array
        m_arr = self.get_columns(columns)

        # base dicts
        users = {uid: User(uid) for uid in user_index.keys()}
        books = {isbn: Book(isbn) for isbn in book_index.keys()}

        # fill dict above with objects
        for user in m_arr:
            users[user[1]].append_book(user[0], user[2])
            users[user[1]].update()

            books[user[0]].append_user(user[1], user[2])
            books[user[0]].update()

        return users, books
示例#6
0
def show_profile():
    """ find current user """
    user = users.get_current_user()

    if not user or not check_registered_user(email_to_uni(user.email())):
        return redirect("/")

    uni = email_to_uni(user.email())

    db = connect_to_cloudsql()
    cursor = db.cursor()
    cursor.execute('use cuLunch')
    # grab only the current user's listings
    query = "SELECT l.expiryTime, l.needsSwipes, l.Place, u.uni, u.name, u.schoolYear, u.interests, u.schoolName" \
            " from users u JOIN listings l ON u.uni=l.uni WHERE l.uni = '{}'".format(uni)

    u = find_user(uni)
    print(u.name, u.school)
    
    try:
        cursor.execute(query)
        
    except:
        print("SELECT for show_profile failed!")

    listingposts = []
    for r in cursor.fetchall():
        u = User(r[3], r[4], r[5], r[6], schools[r[7]])
        l = Listing(r[0], uni, r[2], r[1])
        if l.expiryDateTime > (datetime.datetime.now()- timedelta(hours=4)):
            listingposts.append(ListingPost(l, u))
    db.close()

    return render_template('/profile/index.html',
                           current_user=u,
                           listingposts=listingposts if listingposts else False,
                           logout_link=users.create_logout_url("/"),
                           user_email=user.email())
示例#7
0
def update_profile():
    """ find current user """
    error = None
    user = users.get_current_user()
    uni = email_to_uni(user.email())

    new_name = request.form['new_name']
    new_school = request.form['new_school']
    new_year = int(request.form['new_year'])
    new_interests = request.form['new_interests']

    if new_name == '' or new_interests == '':
        error = "No field should be empty!"

    db = connect_to_cloudsql()
    cursor = db.cursor()
    cursor.execute('use cuLunch')

    if error is None:

        update_query = "UPDATE users SET name = '%s', schoolYear = %d, interests = '%s', schoolName = '%s'" \
            " WHERE uni='%s'" % (new_name, new_year, new_interests, new_school, uni)
        print(update_query)

        try:
            cursor.execute(update_query)
            # commit the changes in the DB
            db.commit()
        except:
            # rollback when an error occurs
            db.rollback()
            print("UPDATE failed!")

    # grab only the current user's listings
    get_query = "SELECT l.expiryTime, l.needsSwipes, l.Place, u.uni, u.name, u.schoolYear, u.interests, u.schoolName" \
            " from users u JOIN listings l ON u.uni=l.uni WHERE l.uni = '{}'".format(uni)

    u = find_user(uni)
    print(u.name, u.school)

    try:
        cursor.execute(get_query)
        
    except:
        print("SELECT for update_profile failed!")

    listingposts = []
    for r in cursor.fetchall():
        u = User(r[3], r[4], r[5], r[6], schools[r[7]])
        l = Listing(r[0], uni, r[2], r[1])
        listingposts.append(ListingPost(l, u))
        print(l.place)

    db.close()

    return render_template('/profile/index.html',
                           current_user=u,
                           listingposts=listingposts if listingposts else False,
                           logout_link=users.create_logout_url("/"),
                           user_email = user.email(),
                           error = error)
示例#8
0
def search_listings():

    cafeteria = request.form['Cafeteria']
    show_swipe_needers = request.form.get ('swipe_needers') != None
    show_swipe_offerers = request.form.get ('swipe_offerers') != None

    if show_swipe_needers:
        print("Showing swipe needers")
    if show_swipe_offerers:
        print("Showing swipe offerers")

    user = users.get_current_user()

    # can't see listings if you don't have an account :^)
    if not user or not check_registered_user (email_to_uni (user.email ())):
        return redirect("/")

    # then fetch the listings
    # TODO: make this a self-contained function to get listings of not a current UNI?

    if not show_swipe_needers and not show_swipe_offerers and (cafeteria == '' or cafeteria == 'All Cafeterias'):
        return redirect("/listings")
    elif show_swipe_needers and show_swipe_offerers and (cafeteria == '' or cafeteria == 'All Cafeterias'):
        return redirect("/listings")
    else:
        uni = email_to_uni(user.email())

        db = connect_to_cloudsql()
        cursor = db.cursor()
        cursor.execute('use cuLunch')
        # grab the relevant information and make sure the user doesn't see their own listings there
        # TODO: determine whether the user should actually see their own listings (would let us consolidate code)

        if (cafeteria == '' or cafeteria == 'All Cafeterias') and show_swipe_offerers:
            query = "SELECT u.uni, u.name, u.schoolYear, u.interests, u.schoolName, l.expiryTime, l.needsSwipes, l.Place from " \
                    "users u JOIN listings l ON u.uni=l.uni WHERE l.needsSwipes=0 AND NOT u.uni = '{}'".format(uni)

        elif (cafeteria == '' or cafeteria == 'All Cafeterias') and show_swipe_needers:
            query = "SELECT u.uni, u.name, u.schoolYear, u.interests, u.schoolName, l.expiryTime, l.needsSwipes, l.Place from " \
                    "users u JOIN listings l ON u.uni=l.uni WHERE l.needsSwipes=1 AND NOT u.uni = '{}'".format(uni)

        if cafeteria != '' and cafeteria != 'All Cafeterias' and show_swipe_needers:
            query = "SELECT u.uni, u.name, u.schoolYear, u.interests, u.schoolName, l.expiryTime, l.needsSwipes, l.Place from " \
                "users u JOIN listings l ON u.uni=l.uni WHERE l.Place = '{}' AND l.needsSwipes=1 AND NOT u.uni = '{}'".format(cafeteria, uni)

        elif cafeteria != '' and cafeteria != 'All Cafeterias' and show_swipe_offerers:
            query = "SELECT u.uni, u.name, u.schoolYear, u.interests, u.schoolName, l.expiryTime, l.needsSwipes, l.Place from " \
                    "users u JOIN listings l ON u.uni=l.uni WHERE l.Place = '{}' AND l.needsSwipes=0 AND NOT u.uni = '{}'".format(
                    cafeteria, uni)

        elif cafeteria != '' and cafeteria != 'All Cafeterias':
            query = "SELECT u.uni, u.name, u.schoolYear, u.interests, u.schoolName, l.expiryTime, l.needsSwipes, l.Place from " \
                "users u JOIN listings l ON u.uni=l.uni WHERE l.Place = '{}' AND NOT u.uni = '{}'".format(cafeteria, uni)

        me = find_user(uni)
        try:
            cursor.execute(query)
        
        except:
            print("SELECT for listings failed!")

        loc_swipes = 0
        loc_num_listings = 0
        posts = []
        for r in cursor.fetchall():
            u = User(r[0], r[1], r[2], r[3], r[4])
            # we need to convert datetime into a separate date and time for the listing object
            l = Listing(r[5], r[0], r[7], r[6])
            if l.expiryDateTime > datetime.datetime.now():
                posts.append(ListingPost(l, u))
                print(str(l.expiryDateTime) + " ")
                loc_num_listings += 1
                if l.needSwipe:
                    loc_swipes += 1

        db.close()

        # serve index template
        return render_template('/listings/index.html', locnumlistings=loc_num_listings,
                               locswipes=loc_swipes, place=cafeteria, current_user=me,
                               listingposts=posts, name=user.nickname(),logout_link=users.create_logout_url("/"), needs=show_swipe_needers,
                               offers=show_swipe_offerers)
示例#9
0
from werkzeug.security import safe_str_cmp
from code.user import User

users = [
    User(1, "bob", "asdf")
]

# username_mapping = {"bob": {
#     "id": 1,
#     "username": "******",
#     "password": "******"
# }
# }

username_mapping = {u.username: u for u in users}

# userid_mapping = {1: {
#     "id": 1,
#     "username": "******",
#     "password": "******"
# }
# }

userid_mapping = {u.id: u for u in users}


def authenticate(username, password):
    user = username_mapping.get(username, None)
    # if user is not None: # same as "if user"
    if user and safe_str_cmp(user.password, password):
        return user