Beispiel #1
0
def lost_info():
    """JSON info about losts"""

    #messages = Message.query.filter_by(to_id=user_id).options(db.joinedload('from_user')).order_by(Message.send_time).all()

    losts = Lost.query.options(db.joinedload('location'),
                               db.joinedload('user')).order_by(
                                   Lost.time).limit(50)

    for lost in losts:
        if not lost.location.lat or not lost.location.lng:
            update_location(lost.location)

    #list comprehension
    losts_json = [{
        "id": lost.lost_id,
        "title": lost.title,
        "description": lost.description,
        "user_fname": lost.user.fname,
        "user_lname": lost.user.lname,
        "reward": lost.reward,
        "time": lost.time,
        "lat": lost.location.lat,
        "lng": lost.location.lng
    } for lost in losts]

    return jsonify(losts_json)
Beispiel #2
0
def found_info():
    """JSON info about founds"""

    founds = Found.query.options(db.joinedload('location'),
                                 db.joinedload('user')).order_by(
                                     Found.time).limit(50)

    for found in founds:
        if not found.location.lat or not found.location.lng:
            update_location(found.location)

    #list comprehension
    founds_json = [{
        "id": found.found_id,
        "title": found.title,
        "description": found.description,
        "user_fname": found.user.fname,
        "user_lname": found.user.lname,
        'user_id': found.user.user_id,
        "time": found.time,
        "lat": found.location.lat,
        "lng": found.location.lng,
    } for found in founds]

    return jsonify(founds_json)
Beispiel #3
0
def return_search_result():
    """Return user's search results."""

    # Search string user enters gathered from the form on the homepage.
    search_str = request.args.get("search_str")

    # Return the producer(s), performer(s), song(s), and album(s)
    # that match the search string (not case-sensitive), alphabetized.
    if len(search_str) > 0:
        sql_search_str = f"%{search_str}%"

        producers = Producer.query.order_by("producer_name").filter(
            Producer.producer_name.ilike(sql_search_str)).all()

        performers = Performer.query.order_by("performer_name").filter(
            Performer.performer_name.ilike(sql_search_str)).all()

        songs = Song.query.order_by("song_title").filter(
            Song.song_title.ilike(sql_search_str)).options(
                db.joinedload("performers")).all()

        albums = Album.query.order_by("album_title").filter(
            Album.album_title.ilike(sql_search_str)).options(
                db.joinedload("performers")).all()
    else:
        producers = None
        performers = None
        songs = None
        albums = None

    return render_template("search_result.html",
                           producers=producers,
                           performers=performers,
                           songs=songs,
                           albums=albums)
Beispiel #4
0
def message_info(msg_id):
    """returns a json object of information in message for client side"""
    msg = Message.query.filter_by(msg_id=msg_id).options(
        db.joinedload('from_user'), db.joinedload('to_user')).one()

    msg_info_dict = {
        'msg': msg.to_dict(),
        'to_user': msg.to_user.to_dict(),
        'from_user': msg.from_user.to_dict()
    }

    return jsonify(msg_info_dict)
Beispiel #5
0
def get_responses_by_assignment_id(assignment_id):
    pras = PromptAssignment.query.get(assignment_id)
    prompt_content = pras.prompt.content
    prompt_id = pras.prompt_id
    due_date = pras.due_date
    if pras.revisit_pras_id is not None:
        revisit = True
        orig_date = get_pras_date(pras.revisit_pras_id)
    else:
        revisit = False
        orig_date = None
    # get existing responses
    responses = (Response.query.options(
        db.joinedload('prompt_assignment'),
        db.joinedload('user')).filter(Response.pras_id == assignment_id).all())

    # if no responses yet, return
    if responses == []:
        return [prompt_content, prompt_id, due_date, revisit, orig_date, []]

    # get students
    condition1 = (SectionAssignment.section_id == pras.section_id)
    condition2 = (SectionAssignment.role == 'student')
    seaction_assignments = (SectionAssignment.query.options(
        db.joinedload('user')).filter(condition1, condition2).all())
    students = []
    for seas in seaction_assignments:
        students.append(seas.user)

    # re-format responses
    res_info = []
    for res in responses:
        name = f'{res.user.first_name} {res.user.last_name}'
        res_info.append({
            'student': name,
            'last_name': res.user.last_name,
            'content': res.content,
            'sentiment': res.sentiment,
            'confidence': res.confidence,
            'date': res.submission_date
        })
        if res.user in students:
            students.remove(res.user)

    # add in students who have not responded yet
    for student in students:
        name = f'{student.first_name} {student.last_name}'
        res_info.append({
            'student': name,
            'last_name': student.last_name,
            'content': 'No response yet.'
        })
    return [prompt_content, prompt_id, due_date, revisit, orig_date, res_info]
Beispiel #6
0
def get_project_json(project_id=None):
    """Return JSON project."""

    if not project_id:
        project_id = request.args.get('projectId')

    project = Project.query.options(
        db.joinedload('categories'),
        db.joinedload('media'),
        db.joinedload('tags')
    ).get(project_id)

    return jsonify_list(project.get_attributes())
Beispiel #7
0
def user_profile(user_id):
    """ Show users home page """

    print '\n\nuser_id: {}, session_id: {}, types: {}, {}\n\n'.format(
        user_id, session.get("current_user"), type(user_id),
        type(session.get("current_user")))

    if int(user_id) != session.get("current_user"):
        abort(404)

    # get user with joined loads rides_taking and rides_offered
    user = User.query.options(db.joinedload('rides_taking'),
                              db.joinedload('rides_offered')).get(user_id)

    rides_offered = user.rides_offered

    for ride in rides_offered:
        ride.start_timestamp = to_local(ride.start_state, ride.start_timestamp)
        ride.start_timestamp = to_time_string(ride.start_state,
                                              ride.start_timestamp)

    rides_offered_requests = []

    # If there are requests for rides you are offering, append
    for ride in rides_offered:
        if ride.requests:
            rides_offered_requests.append(ride)

    rides_taking = user.rides_taking

    for ride in rides_taking:
        ride.start_timestamp = to_local(ride.start_state, ride.start_timestamp)
        ride.start_timestamp = to_time_string(ride.start_state,
                                              ride.start_timestamp)

    rides_taking_requests = Request.query.filter(
        Request.requester == user_id).all()

    for request in rides_taking_requests:
        request.ride.start_timestamp = to_local(request.ride.start_state,
                                                request.ride.start_timestamp)
        request.ride.start_timestamp = to_time_string(
            request.ride.start_state, request.ride.start_timestamp)

    return render_template('profile.html',
                           user=user,
                           rides_offered=rides_offered,
                           rides_offered_requests=rides_offered_requests,
                           rides_taking=rides_taking,
                           rides_taking_requests=rides_taking_requests)
Beispiel #8
0
def get_book_by_isbn(isbn):
    """Returns a book with given ISBN if it exists in the database, otherwise, 
    returns None"""

    book = Book.query.filter(Book.isbn == isbn).options(db.joinedload("categories")).first()

    return book
Beispiel #9
0
def _save_interest_growth_ranking_to_db(industry_id):
    """Get the interest movement ranking in the same industry and store it to db."""

    growth_list = []
    company_list = []

    industry = Industry.query.options(
        db.joinedload("companies")).filter_by(industry_id=industry_id).first()

    for company in industry.companies:

        if company.interest:
            company_interest_growth = get_interest_growth(company)
            growth_list.append(company_interest_growth)
            company_list.append(company)
        else:
            print(f"{company.company_id} has no interest.")

    sorted_growth_list = sorted(growth_list, reverse=True)
    print(sorted_growth_list)

    for company in company_list:
        ranking = sorted_growth_list.index(get_interest_growth(company))
        print((ranking + 1), company.name, company.company_id,
              get_interest_growth(company))
        company.ranking = ranking + 1
        #print(company.ranking)
        db.session.commit()
Beispiel #10
0
def producer_detail(producer_id):
    """Show producer's details."""

    # URL from which to make API calls.
    URL = f"https://genius.com/api/artists/{producer_id}"

    # Method "joinedload" employed to reduce # of queries run for output.
    producer = Producer.query.options(
        db.joinedload("albums").joinedload("songs").joinedload(
            "producers")).get(producer_id)

    all_producers = Producer.query.all()

    albums = producer.albums  # list

    # Return the album release years in descending chronological order.
    album_years = sorted(set(
        [album.album_release_date.strftime("%Y") for album in albums]),
                         reverse=True)

    j = requests.get(URL).json()

    # If call is successful, access JSON object.
    if j["meta"]["status"] == 200:
        bio = j["response"]["artist"].get("description_preview", "")

    # Store producer_id in session.
    session["producer_id"] = producer_id

    if producer_id == 2139214:
        related_producers = []
        return render_template("producer.html",
                               producer=producer,
                               all_producers=all_producers,
                               album_years=album_years,
                               bio=bio,
                               related_producers=related_producers)

    # Return related performers with knn ML algorithm.
    data = pd.read_csv('seed_data/scores.csv')
    d = data.pivot(index='producer_id', columns='performer_id', values='score')
    # knn
    model = joblib.load('static/model/trained-model_producers.pkl')

    # Shape model to the dimensions of the dataset.
    dist, ind = model.kneighbors(d.loc[producer_id, :].values.reshape(1, -1))
    related_producers = [list(d.index)[i] for i in ind[0]]
    # The producer being searched is included in the neighbors list.  Remove it
    # before passing list to Jinja with pop left equivalent method.
    related_producers.pop(0)

    # Calculate page_runtime.
    # print(f"total_time = {end_time - start_time}")

    return render_template("producer.html",
                           producer=producer,
                           all_producers=all_producers,
                           album_years=album_years,
                           bio=bio,
                           related_producers=related_producers)
Beispiel #11
0
def calendar_get_data():
    """Render data stored by user for each meal"""

    # get user_id from session
    user_id = session.get('user_id')
    # get meals for user_id
    meals_for_user = Meal.query.filter(Meal.user_id==user_id).order_by(
                    Meal.meal_time).options(db.joinedload("meal_foodgroups")).all()

        
    events = []
    #loop through the meals to obtain each meal
    for meal in meals_for_user:
        #initialize an empty event object to store each meal data
        event = {}
        event['title']=meal.meal_name
        event['meal_id']=meal.meal_id
        event['start_utc']=meal.meal_time
        #initialize an empty meal foodgroup list for each meal food info
        event['meal_foodgroups']=[]

        #loop through each of the mral_foodgroups in each meal
        for m in meal.meal_foodgroups:
            #add to the empty meal_foodgroups list each component in a particular format as defined in model.py
            event['meal_foodgroups'].append(m.serialize())

        event['allDay']=False
        #add to the events list each event
        events.append(event)
    return jsonify(events)
Beispiel #12
0
def submit_new_attraction(user_id):
    """Show main user landing page with submission form and map."""

    user = User.query.options(
        db.joinedload('attractions').joinedload('location')).get(user_id)

    return render_template('map.html', user=user, GOOGLE_KEY=GOOGLE_KEY)
Beispiel #13
0
def get_sections_by_user_id(user_id):
    assignments = (SectionAssignment.query.options(
        db.joinedload('section')).filter(
            SectionAssignment.user_id == user_id).all())
    sections = [(assignment.section, assignment.role)
                for assignment in assignments]
    return sections
Beispiel #14
0
def show_user_details(user_id):
    """Shows details for individual user"""

    # Creates user object joined to both ratings and movies
    user = User.query.options(db.joinedload('ratings', 'movies')).get(user_id)

    return render_template('user_details.html', user=user)
Beispiel #15
0
def index():
    """Homepage."""

    term = request.args.get('term')
    if not term:
        return render_template('homepage.html',
                               poems=[],
                               headlines=[],
                               subjects=[],
                               term='')

    isalpha = term.isalpha()
    if isalpha == False:
        flash('Word must be all alpha characters.')
        return redirect('/')

    poems = Poem.query.options(db.joinedload('subjects')).filter(
        Poem.tsv.match(term)).all()
    if not poems:
        flash('Word not found. Try another!')
        return redirect('/')

    headlines = queries.get_headlines(term)

    subjects = queries.get_subject_counts(poems)

    return render_template("homepage.html",
                           headlines=headlines,
                           poems=poems,
                           subjects=subjects,
                           term=term)
Beispiel #16
0
def return_saved_jobs():
    """Returns all the jobs that a user saved."""

    user_id = session.get('user_id')

    if not user_id:
        flash("Please sign in first to save this job")
        return redirect("/login")

    else:

        user = User.query.options(db.joinedload('saved_jobs')).get(user_id)

        job_id = request.args.get('job_id')
        job = Job.query.get(job_id)

        if job in user.saved_jobs:
            flash("You've already saved this job")
            return redirect(f"/job_profile?job_id={job.job_id}")

        else:
            save_job = Savings(user_id=user_id, job_id=job_id)

            db.session.add(save_job)
            db.session.commit()

            flash("This job has been saved to your profile!")

    return redirect(f"/job_profile?job_id={job.job_id}")
Beispiel #17
0
def album_list():
    """Show list of albums."""

    # Return album objects using performers' and albums' relationship, ordering
    # results by album title.
    albums = Album.query.options(
        db.joinedload("performers").joinedload("albums")).order_by(
            'album_title').all()

    page, per_page, offset = get_page_args(page_parameter="page",
                                           per_page_parameter="per_page")

    per_page = 100

    offset = (page - 1) * per_page
    total = len(albums)

    pagination_albums = albums[offset:offset + per_page]
    pagination = Pagination(page=page,
                            per_page=per_page,
                            total=total,
                            css_framework="bootstrap4")

    return render_template("album_list.html",
                           albums=pagination_albums,
                           page=page,
                           per_page=per_page,
                           pagination=pagination)
Beispiel #18
0
def user_following(user_id):
    """Users followed by user specified.

    Return json of all the users followed by the user specified in the
    URI. Note that route is `...following` but model has the attribute
    `followed`. This is to maintain an English-like relationship in
    the URI and model respectively.
    """

    mode = request.args.get('mode', 'full')
    user = User.query.filter(User.id == user_id).options(
        db.joinedload('followed')).one()

    if mode == 'full':
        dict_of_users = {
            followed.id: followed.to_dictionary()
            for followed in user.followed
        }
    elif mode == 'short':
        dict_of_users = {
            followed.id: followed.uname
            for followed in user.followed
        }
    else:
        abort(400)  # Bad request

    return jsonify(dict_of_users)
Beispiel #19
0
def show_active_jobs():
    """Shows list jobs the user is interested in, applied to, or interviewing for."""

    # redirect if user is not logged in
    if not session:
        return redirect('/')
    else:
        # get user_id from session and pass in companies
        user_id = session['user_id']
        user = User.query.filter(User.user_id == user_id).one()
        companies = user.companies

        # query for user job events, return list
        user_job_events = JobEvent.query.options(db.joinedload('jobs')).filter(JobEvent.user_id == user_id).order_by(desc('date_created')).all()
        job_event_ids = [event.job_event_id for event in user_job_events]

        # make a set of all job_ids and remove any that are inactive
        user_job_ids = set(job.job_id for job in user_job_events if job.jobs.active_status == True)

        # grab only the most recent events and todos for each job_id
        all_active_status = []
        all_todos = []
        for user_job_id in user_job_ids:
            # get all events for one job id
            events = [event for event in user_job_events if event.job_id == user_job_id]
            # find that latest event and add to list
            status = events[0]
            all_active_status.append(status)
            user_todo = ToDo.query.filter(ToDo.job_event_id == status.job_event_id, ToDo.active_status == True).first()
            if user_todo:
                all_todos.append(user_todo)

        return render_template('jobs-active.html', all_active_status=all_active_status, all_todos=all_todos, companies=companies)
Beispiel #20
0
def delete_user(user_id):
    """Remove user."""

    session_id = session_check(session['id'], request.remote_addr,
                               request.user_agent, int(user_id))

    if session_id == '':
        session['id'] = ''
        abort(401)  # Unauthorized

    user = User.query.filter(User.id == user_id).options(
        db.joinedload('posts')).one()

    if user.deleted:
        abort(403, 'Cannot delete a deleted user.')
    else:
        # Append the user's id to the end of their (deleted) username.
        user.uname = f'{user.uname} (deleted) {user.id}'
        user.deleted = True

        for post in user.posts:
            post.title, post.content = '', ''
            post.erased = True

        Follower.query.filter(Follower.follower_id == user.id).delete()
        Bookmark.query.filter(Bookmark.user_id == user_id).delete()
        Session.query.filter(Session.session_id == session_id).delete()

        db.session.commit()
        session['id'] = ''

        return ('', 204)  # status 204: success, no content
Beispiel #21
0
def get_company_application(search_company_name):
    """Return the application id for the company which is input as a parameter.
    working code

    Example (from 'solar_viz_test' database): 
    >>> print(get_company_application('Pacific Gas and Electric'))
    [<Program application_id=SD-CSI-00001
                       utility=1
                       city=San Diego
                       county=San Diego
                       zipcode=92121
                       contractor=4
                       pv_manuf=11
                       invert_manuf=18
                       status=Installed>, <Program application_id=SCE-CSI-06676
                       utility=2
                       city=Manhattan Beach
                       county=Los Angeles
                       zipcode=90266
                       contractor=5
                       pv_manuf=12
                       invert_manuf=19
                       status=Installed>, 
                       ... AND MORE RETURNED BUT TRUNCATED

        """

    applications = Program.query.filter(Company.name == search_company_name)\
                                .options(db.joinedload('utility_company'))\
                                .all()

    return applications
Beispiel #22
0
def show_all_contacts():
    """Show all contacts a user is connected to."""

    # redirect if user is not logged in
    if not session:
        return redirect('/')
    else:
        # get user
        user_id = session['user_id']
        user = User.query.filter(User.user_id == user_id).one()
        companies = user.companies

        # get all user events with all contacts
        contact_events = ContactEvent.query.filter(ContactEvent.user_id == user_id).order_by(desc('date_created')).all()

        # make a set of all contact_ids
        contact_ids = set(contact_event.contact_id for contact_event in contact_events)

        # grab all contact objects by contact_id
        contacts = []
        all_todos = []
        for contact_id in contact_ids:
            contact = Contact.query.filter(Contact.contact_id == contact_id).options(db.joinedload('companies')).first()
            contacts.append(contact)
            # get all contact events for the contact
            events = [event for event in contact_events if event.contact_id == contact.contact_id]
            latest_event = events[0]
            user_todo = ToDo.query.filter(ToDo.contact_event_id == latest_event.contact_event_id, ToDo.active_status ==True).first()
            if user_todo:
                all_todos.append(user_todo)

        return render_template('contacts.html', contacts=contacts, all_todos=all_todos, companies=companies)
Beispiel #23
0
def show_a_contact(contact_id):
    """Show one contact and all interactions."""

    # redirect if user is not logged in
    if not session:
        return redirect('/')
    else:
        # get user_id from session
        user_id = session['user_id']
        user = User.query.filter(User.user_id == user_id).one()
        companies = user.companies

        # get edit status
        edit = request.args.get('edit')

        # get contact (join companies) and all events
        contact = Contact.query.filter(Contact.contact_id == contact_id).options(db.joinedload('companies')).first()
        contact_events = ContactEvent.query.filter(ContactEvent.contact_id == contact_id).order_by(desc('date_created')).all()

        # query for associated tasks, return list
        all_todos = []
        for event in contact_events:
            todo = ToDo.query.filter(ToDo.contact_event_id == event.contact_event_id).options(db.joinedload('todo_codes')).first()
            all_todos.append(todo)

        return render_template('contact-info.html',
                               edit=edit,
                               contact=contact,
                               contact_events=contact_events,
                               all_todos=all_todos,
                               companies=companies)
Beispiel #24
0
def return_average_rating():
    """Returns the average rating for a specific job posting"""

    job_id = request.args.get('job_id')
    rating = Job.query.options(db.joinedload('ratings')).get(job_id)
    job = Job.query.get(job_id)  #get the job_id of the specific job posting
    #returns list of rating objects of the job (all ratings of the job)

    ratings_list = []

    if job.ratings:
        for each_rating in job.ratings:
            ratings_list.append(each_rating.rating)
        average = round(mean(ratings_list), 1)

        if 0 <= average < 1:
            response = "On average, applicants who applied to this job didn't hear back"
        elif 1 <= average < 2:
            response = "On average, applicants who applied to this job heard back from a recruiter"
        elif 2 <= average < 3:
            response = "On average, applicants who applied to this job received a phone screen interview"
        elif 3 <= average < 4:
            response = "On average, applicants who applied to this job got through to the onsite interview"
        else:
            response = "On average, applicants who applied to this job received a job offer!"
        return response
    else:
        return "No ratings on this job posting yet!"
Beispiel #25
0
def show_user_profile():
    """Show user's profile and allow update to information."""

    # redirect if user is not logged in
    if not session:
        return redirect('/')
    else:
        # find user in db
        user_id = session['user_id']
        user = User.query.filter(User.user_id == user_id).one()
        companies = user.companies

        # get user data to pass into charts
        user_job_events = JobEvent.query.options(db.joinedload('jobs')).filter(JobEvent.user_id == user_id).all()
        total_interested = len([event for event in user_job_events if event.job_code == 1])
        total_applied = len([event for event in user_job_events if event.job_code == 2])
        total_phone = len([event for event in user_job_events if event.job_code == 3])
        total_in_person = len([event for event in user_job_events if event.job_code == 4])
        total_job_offer = len([event for event in user_job_events if event.job_code == 5])

        user_analytics = {
            'interested': total_interested,
            'applied': total_applied,
            'phone': total_phone,
            'onsite': total_in_person,
            'offers': total_job_offer
        }

        return render_template('profile-tasks.html', companies=companies,
                               user=user, user_analytics=user_analytics)
Beispiel #26
0
def get_crop_favorites(gardener_id):
    """Get favorite crops for a gardener user."""

    favorite_crop_list = []

    favorite_crops = FavoriteCrop.query.filter(
        FavoriteCrop.gardener_id == gardener_id).options(
            db.joinedload('crop')).all()

    for favorite_crop in favorite_crops:
        favorite_crop_dictionary = {}
        favorite_crop_dictionary['name'] = favorite_crop.crop.crop_name
        favorite_crop_dictionary[
            'planting_consideration'] = favorite_crop.crop.crop_planting_considerations
        favorite_crop_dictionary[
            'growing_from_seed'] = favorite_crop.crop.crop_growing_from_seed
        favorite_crop_dictionary[
            'transplanting'] = favorite_crop.crop.crop_transplanting
        favorite_crop_dictionary['spacing'] = favorite_crop.crop.crop_spacing
        favorite_crop_dictionary['watering'] = favorite_crop.crop.crop_watering
        favorite_crop_dictionary['feeding'] = favorite_crop.crop.crop_feeding
        favorite_crop_dictionary['crop_id'] = favorite_crop.crop_id
        favorite_crop_dictionary[
            'image_url'] = favorite_crop.crop.crop_image_url

        favorite_crop_list.append(favorite_crop_dictionary)

    return favorite_crop_list
Beispiel #27
0
def show_a_company(company_id):
    """Show a company a user has interest in."""

    # redirect if user is not logged in
    if not session:
        return redirect('/')
    else:
        edit = request.args.get('edit')

        # get user_id from session
        user_id = session['user_id']
        user = User.query.filter(User.user_id == user_id).one()
        companies = user.companies

        #get company info and pre-load jobs
        company = Company.query.filter(Company.company_id == company_id).options(db.joinedload('jobs')).options(db.joinedload('contacts')).first()
        # get list of active jobs and of arcived jobs
        active_jobs = [job for job in company.jobs if job.active_status]
        archived_jobs = [job for job in company.jobs if not job.active_status]

        states = ["", "AL", "AK", "AZ", "AR", "CA", "CO", "CT", "DC", "DE", "FL", "GA",
                  "HI", "ID", "IL", "IN", "IA", "KS", "KY", "LA", "ME", "MD",
                  "MA", "MI", "MN", "MS", "MO", "MT", "NE", "NV", "NH", "NJ",
                  "NM", "NY", "NC", "ND", "OH", "OK", "OR", "PA", "RI", "SC",
                  "SD", "TN", "TX", "UT", "VT", "VA", "WA", "WV", "WI", "WY"]

        return render_template('company-info.html',
                               company=company,
                               edit=edit,
                               states=states,
                               companies=companies,
                               active_jobs=active_jobs,
                               archived_jobs=archived_jobs)
Beispiel #28
0
def update_recipes_folder(recipe_id, folder_id):
    """Update folder for given recipe"""

    recipe = Recipe.query.options(db.joinedload(
        Recipe.folder)).filter(Recipe.recipe_id == recipe_id).first()
    recipe.folder_id = folder_id

    db.session.commit()
Beispiel #29
0
def get_teacher_assignments():
    teacherAssignments = (SectionAssignment.query.options(
        db.joinedload('user')).filter(
            SectionAssignment.role == 'teacher').all())
    teachers = []
    for teas in teacherAssignments:
        teachers.append(teas.user)
    return teachers
Beispiel #30
0
def get_all_media_json():
    """Return JSON of all media, ordered by date updated."""

    all_media = Media.query.options(
        db.joinedload('projects')
    ).order_by(Media.date_updated.desc()).limit(6).all()

    return jsonify_list(Media.get_json_from_list(all_media, True, False))
Beispiel #31
0
def get_all_events_books(event_id):
    """Returns a list of event_book objects for a given event"""
    
    # event = Event.query.options(db.joinedload("events_books")).get(event_id)
    events_books = EventBook.query.filter(EventBook.event_id == event_id).options(db.joinedload("book")).all()

    # return event.events_books
    return events_books
Beispiel #32
0
def get_category_by_label(user_id, label):
    """Returns a category with a given label"""

    category = Category.query.filter(Category.label == label, Category.\
                                    user_id == user_id).\
                                    options(db.joinedload("books")).first()

    return category
Beispiel #33
0
def song_detail(song_id):
    """Show song detail."""

    # Return song objects using producers' and songs' relationship.
    song = Song.query.options(
        db.joinedload("producers").joinedload("songs")).get(song_id)

    return render_template("song.html", song=song)
Beispiel #34
0
def user_details(userid):
    """show the details for a given user id."""

    user = User.query.options(db.joinedload('ratings',
                                            'venue')).get(int(userid))

    print user
    return render_template("user_details.html", user=user)
Beispiel #35
0
def performer_detail(performer_id):
    """Show performer's detail."""

    URL = "https://genius.com/api/artists/" + str(performer_id)

    performer = Performer.query.options(
        db.joinedload("albums").joinedload("songs").joinedload(
            "producers")).get(performer_id)

    all_performers = Performer.query.all()

    albums = performer.albums

    # Return a set of performer's album release years in descending order.
    album_years = sorted(set(
        [album.album_release_date.strftime("%Y") for album in albums]),
                         reverse=True)

    # Store performer_id in session.
    session["performer_id"] = performer_id

    # API call for producer bio.
    r = requests.get(URL)
    j = r.json()

    # If url request is successful and the bio JSON key exists, return that key
    # value (description_preview); otherwise, return an empty string.
    if j["meta"]["status"] == 200:
        bio = j["response"]["artist"].get("description_preview", "")

    if performer_id == 2119381:
        related_performers = [1456758]
        return render_template("performer.html",
                               performer=performer,
                               all_performers=all_performers,
                               album_years=album_years,
                               bio=bio,
                               related_performers=related_performers)

    # Return related performers with knn ML algorithm.
    data = pd.read_csv('seed_data/scores.csv')
    d = data.pivot(index='performer_id', columns='producer_id', values='score')
    # knn
    model = joblib.load('static/model/trained-model.pkl')

    # The performer being searched is included in the neighbors list.  Remove it
    # before passing list to Jinja with pop left equivalent method.
    # For future development: cache values to prevent doing operations in server.
    dist, ind = model.kneighbors(d.loc[performer_id, :].values.reshape(1, -1))
    related_performers = [list(d.index)[i] for i in ind[0]]
    related_performers.pop(0)

    return render_template("performer.html",
                           performer=performer,
                           all_performers=all_performers,
                           album_years=album_years,
                           bio=bio,
                           related_performers=related_performers)
Beispiel #36
0
def show_a_job(job_id):
    """Shows detailed info about a job"""

    # redirect if user is not logged in
    if not session:
        return redirect('/')
    else:
        user_id = session['user_id']
        user = User.query.filter(User.user_id == user_id).one()
        companies = user.companies

        # get job from database and pre-load company data
        job = Job.query.filter(Job.job_id == job_id).options(db.joinedload('companies')).first()

        # query for user job events, return list
        # Look at created a db.relationship from users to jobs
        job_status = JobEvent.query.options(db.joinedload('todos')).filter(JobEvent.user_id == user_id, JobEvent.job_id == job_id).order_by(desc('date_created')).order_by(desc('job_code')).all()

        # query for associated tasks, return list
        all_todos = []
        for status in job_status:
            todo = ToDo.query.filter(ToDo.job_event_id == status.job_event_id).options(db.joinedload('todo_codes')).first()
            all_todos.append(todo)

        if not job.avg_salary:
            metros = db.session.query(Salary.metro).group_by(Salary.metro).order_by(Salary.metro).all()
            job_titles = db.session.query(Salary.job_title).group_by(Salary.job_title).order_by(Salary.job_title).all()
        else:
            metros = ""
            job_titles = ""

        return render_template('job-info.html',
                               job=job,
                               metros=metros,
                               job_titles=job_titles,
                               job_status=job_status,
                               all_todos=all_todos,
                               companies=companies)
Beispiel #37
0
def flickr_search():
    """Makes request to FLICKR API, given bldg tags. Saves file for each bldg, each page 500 results max."""

    bldgs = db.session.query(Building).options(db.joinedload('city')).all()

    flickr_per_page_limit = 500

    for bldg in bldgs:
        bldg_name = bldg.building_name
        city_name = bldg.city.city
        # Assumes all buildings are in the same city, if joined for API call.

        page = 1
        page_count = 80  # Arbitrary limit.

        extras = 'url_s, url_m, geo, tags, owner_name, date_taken, description'

        # extras: description, license, date_upload, date_taken, owner_name, icon_server,
        # original_format, last_update, geo, tags, machine_tags, o_dims, views, media, path_alias,
        # url_sq, url_t, url_s, url_q, url_m, url_n, url_z, url_c, url_l, url_o

        while (page < page_count):

            payload = {'tags': bldg_name+', '+city_name, 'tag_mode': 'all',
                       'extras': extras,
                       'ispublic': 1, 'format': 'json', 'nojsoncallback': 1,
                       'api_key': FLICKR_KEY,
                       'page': page, 'per_page': flickr_per_page_limit}

            # Response object.
            r = requests.get('https://api.flickr.com/services/rest/?method=flickr.photos.search', params=payload)

            # Content of Response object as string.
            content = r.content

            # JSON dictionary.
            data = json.loads(content)

            insert_photos(data)

            page_count = int(data['photos']['pages'])

            print '''Getting page {} in {} total pages.
                     Queried for {} building at rank {}'''.format(page,
                                                                  page_count,
                                                                  bldg_name,
                                                                  bldg.rank)

            page += 1
Beispiel #38
0
def edit_a_contact():
    """Allows user to edit info about a contact"""

    # redirect if user is not logged in
    if not session:
        return redirect('/')
    else:
        # get contact object to update
        contact_id = request.form['contact_id']
        contact = Contact.query.filter(Contact.contact_id == contact_id).options(db.joinedload('companies')).first()

        contact.notes = request.form['notes']
        contact.email = request.form['email']
        phone = "".join((request.form['phone']).split('-'))
        contact.phone = phone

        # look for company_id and find existing company OR
        # get new company_name and create company object, add, commit
        if request.form['company_id']:
            company_id = int(request.form['company_id'])
            company = Company.query.filter(Company.company_id == company_id).first()
        elif request.form['company_name']:
            company_name = request.form['company_name']
            company = Company(name=company_name)
            db.session.add(company)
            db.session.commit()

        contact.company_id = company.company_id
        db.session.commit()

        # send results back to webpage
        results = {
            'email': contact.email,
            'phone': contact.phone,
            'company': contact.companies.name,
            'notes': contact.notes,
        }

        return jsonify(results)
Beispiel #39
0
def show_archived_jobs():
    """ Shows a list of archived jobs the user is no longer tracking."""

    # redirect if user is not logged in
    if not session:
        return redirect('/')
    else:
        # get user_id from session
        user_id = session['user_id']
        user = User.query.filter(User.user_id == user_id).one()
        companies = user.companies

        # query for user job events, return list
        user_job_events = JobEvent.query.options(db.joinedload('jobs')).filter(JobEvent.user_id == user_id).order_by(desc('date_created')).all()

        # make a set of all job_ids and remove any that are inactive
        user_job_ids = set(job.job_id for job in user_job_events
                           if job.jobs.active_status == False)

        # grab only the most recent events for each job_id
        all_archived = {}
        for user_job_id in user_job_ids:

            # get all events for one job id
            events = [event for event in user_job_events
                      if event.job_id == user_job_id]

            # find that latest event and add to list
            status = events[0]
            company = Company.query.filter(
                Company.company_id == status.jobs.company_id).first()
            all_archived[status] = company

        return render_template('jobs-archive.html',
                               all_archived=all_archived,
                               companies=companies)