def test_cascading_seat(db_session):
    season = createBasicSeason(db_session)
    user = User(username="******",
                sub="sub",
                email="email",
                fullname="Man Man McMan")
    application = Application(needs="needs",
                              user=user,
                              partnerUsername="******",
                              comments="comments",
                              preferredRoom="pref",
                              seatRollover=True,
                              rank=Rank.WRITING_MASTER,
                              status=ApplicationStatus.SUBMITTED,
                              applicationSeason=season)
    room = Room(name="room", info="info")
    seat = Seat(name="d1", room=room, info="info")
    db_session.add(user)
    db_session.add(application)
    db_session.add(room)
    db_session.add(seat)
    db_session.commit()
    application.room_id = seat.room_id
    application.seat_id = seat.id
    assert application.seat is seat

    db_session.delete(application)
    db_session.commit()
    db_session.expire_all()

    dbseat = db_session.query(Seat).first()
    print(user.application)
    assert dbseat == seat
    assert dbseat.application is None
    assert user.application is None
def test_multiple_applications_on_applicationSeason_should_fail(db_session):
    season = createBasicSeason(db_session)
    user = createUser(db_session)
    application1 = Application(needs="needs",
                               user=user,
                               partnerUsername="******",
                               comments="comments",
                               preferredRoom="pref",
                               seatRollover=True,
                               rank=Rank.WRITING_MASTER,
                               status=ApplicationStatus.SUBMITTED,
                               applicationSeason=season)
    db_session.add(application1)
    db_session.commit()
    with raises(IntegrityError):
        application2 = Application(needs="needs",
                                   user=user,
                                   partnerUsername="******",
                                   comments="comments",
                                   preferredRoom="pref",
                                   seatRollover=True,
                                   rank=Rank.WRITING_MASTER,
                                   status=ApplicationStatus.SUBMITTED,
                                   applicationSeason=season)
        db_session.add(application2)
        db_session.commit()
def test_application_connect_to_seat(db_session):
    season = createBasicSeason(db_session)
    room = Room("D1", "kek")
    db_session.add(room)
    seat = Seat(name="D1", room=room, info="")
    db_session.add(seat)
    user = User(username="******",
                sub="sub",
                email="email",
                fullname="schnep scmep")
    db_session.add(user)
    application = Application(needs="",
                              comments="",
                              user=user,
                              partnerUsername="",
                              preferredRoom="d1",
                              seatRollover=True,
                              rank=Rank.WRITING_MASTER,
                              status=ApplicationStatus.SUBMITTED,
                              applicationSeason=season)
    db_session.add(application)
    db_session.commit()
    application.room_id = seat.room_id
    application.seat_id = seat.id
    assert application.seat is seat
    assert seat.application is application
 def generate_name(self, application: Application) -> str:
     """
     Genarate unique name for Application
     """
     application.generate_name()
     while self._repository.name_exists(application.name):
         application.generate_name(
             f"{application.real_name}_{randint(1, 100)}")
    def get_application_by_name(self,pkgname):
        #print "get_application_by_name:", pkgname
        if pkgname == "brasero":
            return None
        if not pkgname:
            return None
        if self.cat_list is None:
            return None
        #
        # print("self.cat_list111",self.cat_list)
        for (catname, cat) in list(self.cat_list.items()): #get app in cat which init in uksc startup
            app = cat.get_application_byname(pkgname)
            if app is not None and app.package is not None:
                return app

        if(Globals.ADVANCED_SEARCH):
            pkg = self.get_package_by_name(pkgname)
            if pkg is not None and pkg.candidate is not None: #get app from cache and add it to cat  when app not in cat
                displayname_cn = pkgname
                app = Application(pkgname, displayname_cn, cat, self.apt_cache)
                app.orig_name = app.name
                app.orig_summary = app.summary
                app.orig_description = app.description
                app.displayname = app.name
                app.summary = app.summary
                app.description = app.description
                app.from_ukscdb = False
                # if("Accessories" in self.cat_list.keys()):
                #     cat = self.cat_list["Accessories"]
                #     cat.apps[pkgname] = app
                return app

        return None
 def test_update_application(self):
     season = createBasicSeason(db.session)
     testuser = createUser(db.session)
     testApplication = Application(ApplicationStatus.SUBMITTED,
                                   "Fanta is better than solo",
                                   user=testuser,
                                   partnerUsername="******",
                                   preferredRoom="d1",
                                   seatRollover=True,
                                   applicationSeason=season,
                                   comments="Not Pepsi, but Pepsi Max")
     db.session.add(testApplication)
     db.session.commit()
     mimetype = 'application/json'
     headers = {
         'Content-Type': mimetype,
         'Accept': mimetype,
         'Authorization': self.token,
         'AccessToken': self.accessToken
     }
     response = self.app.test_client().put(
         'http://localhost:5000/application/1',
         headers=headers,
         data=json.dumps(
             dict(
                 username=testuser.username,
                 needs="Pepsi is better than coke",
                 comments="Not Pepsi, but Pepsi Max",
                 partnerUsername="",
                 preferredRoom="d1",
                 seatRollover=True,
                 aRandomfield=True,
             )))
     expectedResponse = make_response(
         jsonify(
             needs="Pepsi is better than coke",
             comments="Not Pepsi, but Pepsi Max",
             id=1,
             status="SUBMITTED",
             user={
                 "id": 1,
                 "username": testuser.username,
                 "email": testuser.email,
                 "fullname": testuser.fullname
             },
             partnerApplication={},
             rank="OTHER",
             seat=None,
             preferredRoom="d1",
             seatRollover=True,
         ), 200)
     assert expectedResponse.status == response.status
     assert json.loads(expectedResponse.data) == json.loads(response.data)
     assert testApplication.to_json() == json.loads(response.data)
Beispiel #7
0
def app(request, browser_type, base_url):
    if browser_type == "firefox":
        driver = webdriver.Firefox(GECKODRIVER)
    elif browser_type == "chrome":
        chrome_options = webdriver.ChromeOptions()
        chrome_options.add_argument('--window-size=1920,1080')
        chrome_options.add_argument('--enable-logging')
        chrome_options.add_argument('--v=1')
        chrome_options.add_argument('--ignore-certificate-errors')
        chrome_options.add_argument('--disable-extensions')
        chrome_options.add_argument('--no-sandbox')
        chrome_options.add_argument('--enable-popup-blocking')
        chrome_options.add_argument('--disable-notifications')
        chrome_options.add_argument('--headless')
        chrome_options.add_argument('--use-gl=osmesa')
        chrome_options.add_argument('--disable-dev-shm-usage')
        chrome_options.add_argument('--disable-infobars')
        driver = webdriver.Chrome(CHROMEDRIVER, options=chrome_options)

    def fin():

        screenshot("END TEST", driver)
        driver.get(base_url)
        driver.quit()

    request.addfinalizer(fin)
    return Application(driver, base_url)
Beispiel #8
0
    def test_run(self):
        jobs, students, apps = self.get_test_case()

        # Add the test objects to DB
        for obj in jobs + students + apps:
            obj.save()

        # Run the script
        MatchScript(app = self.app).run()

        # Check job objects
        job_ids = map(lambda job: job.id, jobs)
        db_jobs = Job.by_ids_dict(job_ids)
        assert(db_jobs[jobs[0].id].state == Job.State.FILLED)
        assert(db_jobs[jobs[1].id].state == Job.State.PARTIALLY_FILLED)
        assert(db_jobs[jobs[2].id].state == Job.State.UNFILLED)

        # Check app objects
        expected_matches = {
            students[0].id : jobs[0].id,
            students[1].id : jobs[1].id,
            students[2].id : jobs[1].id,
            students[3].id : None
        }
        app_ids = map(lambda app: app.id, apps)
        db_apps = Application.by_ids(app_ids)
        for app in db_apps:
            if expected_matches[app.student_id] == app.job_id:
                assert(app.state == Application.State.MATCHED)
            else:
                assert(app.state == Application.State.NOT_MATCHED)
Beispiel #9
0
def apply(job_id, student_id):
    data = request.json
    application = Application(
        job_id=job_id,
        student_id=student_id,
    )
    return save_model(application)
Beispiel #10
0
def registerApplicationMock(comments, user, needs, partnerUsername, preferredRoom, seatRollover, rank):
    return Application(
        status=ApplicationStatus.SUBMITTED,
        comments=comments,
        needs=needs,
        user=User(username="******", sub="sub", email="email", fullname="Schnep Schmep"),
        partnerUsername=partnerUsername,
        preferredRoom="d1",
        seatRollover=True,
        rank=rank,
        applicationSeason=createBasicSeason()
    ).to_json(), 201
Beispiel #11
0
 def get(self):
     if self.user:
         if self.user.has_transfers() or self.request.get("dashboard") == "true":
             self.render("transfer_dashboard",
                 user_transfer=self.user.transfers(),
                 show_graph=True,
                 total_transfers=Application.app().total_transfers or 0,
             )
         else:
             self.render("transfer_step1", email=self.user.email, location=self.user.location())
     else:
         self.render("authorize", redirect_uri="%s/auth" % settings.APP_ENGINE_PATH, app_id=settings.FACEBOOK_APP_ID)
Beispiel #12
0
def get_jobs():
    query = {}
    request_data = request.args.to_dict()

    # Search by id
    if 'employer_id' in request_data:
        query['employer_id'] = ObjectId(request.args.get('employer_id'))

    # Search by location
    if 'company_name' in request_data:
        company_name = request_data.get('company_name')
        employer = Employer.find_one({'company_name': company_name})
        if employer:
            query['employer_id'] = employer.id
        else:
            query['company_name'] = '-1'

    # Search by location
    if 'location' in request_data:
        query['location'] = request_data.get('location')

    # Execute query
    jobs = Job.find(query)

    job_ids = map(lambda job: job.id, jobs)

    # Get student applications for those jobs
    app_query = {'job_id': {'$in': job_ids}}

    # If I'm a student, only return my apps
    if g.student:
        app_query['student_id'] = g.user.id

    # Query for applications to those jobs
    apps = Application.find(app_query)

    # Convert to dictionary based on either student or employer context
    if g.student:
        apps = map(lambda app: app.to_dict_student(), apps)
    else:
        apps = map(lambda app: app.to_dict_employer(), apps)

    apps_by_job_id = dict(zip(map(lambda app: app['job_id'], apps), apps))

    # Assemble results as dicts
    result = []
    for job in jobs:
        _dict = job.to_dict()
        _dict['application'] = apps_by_job_id.get(str(job.id))
        result.append(_dict)

    return ujson.dumps(result)
Beispiel #13
0
def registerApplication(comments, needs, user, partnerUsername, seatRollover,
                        preferredRoom, rank):
    try:
        season = getCurrentOrNext()
        application = Application(
            status=ApplicationStatus.SUBMITTED,
            needs=needs,
            user=user,
            partnerUsername=partnerUsername,
            comments=comments,
            seatRollover=seatRollover,
            preferredRoom=preferredRoom,
            rank=rank,
            applicationSeason=season,
        )
        db.session.add(application)
        db.session.commit()
        connectApplication(application)
        return application.to_json(), 201
    except SQLAlchemyError as err:
        print(err)
        return "", 400
Beispiel #14
0
 def process_transfer_form(self, user):
     current_month_transfer = float(self.request.get("current_month"))
     
     if self.request.get("last_month"):
         last_month_transfer = float(self.request.get("last_month"))
     else:
         last_month_transfer = None
     
     if self.request.get("start_date"):
         from datetime import datetime
         start_date = datetime.strptime(self.request.get("start_date"), "%Y-%m-%d").date()
     else:
         start_date = None
             
     user_id = user.user_id
     parent = user.key()
     
     try:
         if start_date:
             # if we're here, it means that this is the first time the user has submitted the form
             # at this point, user has no transfers yet
             transfer = Transfer(
                 user_id=user_id, key_name=user_id, parent=parent, start_date=start_date, monthly_transfers=[current_month_transfer]
             )
         else:
             # user is updating or entering new transfer
             transfer = user.transfers()
         
             if last_month_transfer:
                 # update last month's transfer
                 transfer.monthly_transfers[-1] = last_month_transfer
             
             transfer.monthly_transfers.append(current_month_transfer)
                 
         transfer.put()
         self.render(
             'transfer_dashboard',
             message="Your transfer has been saved.",
             success=True,
             total_transfers=Application.app().total_transfers or 0,
             show_graph=True
         )
     except:
         self.render(
             "transfer_dashboard",
             message="Data not saved. Please ensure that you've entered the correct information.", 
             success=False
         )
 def download_category_apps(self,cat,catdir=""):
     #load the apps from category file
     count = 0
     sumapp = 0
     apps = {}
     file = open(catdir + cat, 'r')
     for line in file:
         pkgname = line.strip('\n')
         if pkgname == "brasero":
             continue
         app = Application(pkgname,cat, self.apt_cache)
         if app.package:
             apps[pkgname] = app
             sumapp = sumapp + 1
         else:
             count = count + 1
     return apps
Beispiel #16
0
def createApplication(db_session=None):
    season = createBasicSeason(db_session)
    user = createUser(db_session)
    application = Application(
        needs="needs",
        comments="comments",
        user=user,
        partnerUsername="******",
        preferredRoom="d1",
        seatRollover=True,
        status=ApplicationStatus.SUBMITTED,
        rank=Rank.WRITING_MASTER,
        applicationSeason=season,
    )
    if (db_session):
        db_session.add(application)
        db_session.commit()
    return application
Beispiel #17
0
def add_application():
    attributes = request.json
    application = Application(**attributes)
    try:
        session.add(application)
        session.commit()
        response = jsonify({
            "code": 1,
            "message": "Successfully added application"
        })
        return make_response(response, 201)
    except:
        session.rollback()
        response = jsonify({
            "code": -1,
            "message": "Application already exists"
        })
        return make_response(response, 401)
Beispiel #18
0
    def test_remove_all_students_from_seat(self):
        room, seat = createSeatAndRoom()
        room2, seat2 = createSeatAndRoom()
        application1 = createApplication(db.session)
        user = User(username="******",
                    sub="sub",
                    email="email2",
                    fullname="fullname2")
        application2 = Application(
            ApplicationStatus.APPROVED,
            "Fanta is better than solo",
            user=user,
            partnerUsername="******",
            preferredRoom="d1",
            seatRollover=True,
            applicationSeason=application1.applicationSeason,
            comments="Not Pepsi, but Pepsi Max")
        db.session.add(user)
        db.session.add(application2)
        seat.application = application1
        seat2.application = application2
        db.session.add(seat)
        db.session.add(seat2)
        db.session.commit()

        mimetype = 'application/json'
        headers = {
            'Content-Type': mimetype,
            'Accept': mimetype,
            'AccessToken': self.accessToken
        }
        seatId = 1
        response = self.app.test_client().post(
            "http://localhost:5000/seat/removeAllStudents",
            headers=headers,
            data=json.dumps(seatId))

        assert "200 OK" == response.status
        assert seat.application is None
        assert seat2.application is None
        assert application1.seat is None
        assert application2.seat is None
        assert application1.status is ApplicationStatus.SUBMITTED
        assert application2.status is ApplicationStatus.SUBMITTED
def test_proper_user_serialization(db_session):
    season = createBasicSeason(db_session)
    testuser1 = User(username="******",
                     sub="sub",
                     email="email",
                     fullname="Asbjørn ELEVG baby")
    db_session.add(testuser1)
    application = Application(needs="",
                              comments="",
                              user=testuser1,
                              partnerUsername=None,
                              preferredRoom="d1",
                              seatRollover=True,
                              rank=Rank.WRITING_MASTER,
                              status=ApplicationStatus.SUBMITTED,
                              applicationSeason=season)
    db_session.add(application)
    db_session.commit()
    dbapplication = db_session.query(Application).first()
    assert testuser1.to_json() == dbapplication.to_json()['user']
 def test_update_application_with_partner(self):
     season = createBasicSeason(db.session)
     headers = {
         'Authorization': self.token,
         'AccessToken': self.accessToken,
         'Content-type': 'application/json'
     }
     testuser1 = User(username="******",
                      sub="sub",
                      email="email",
                      fullname="Franky Frank")
     testuser2 = User(username="******",
                      sub="uuid",
                      email="email",
                      fullname="Schmemail")
     db.session.add(testuser1)
     db.session.add(testuser2)
     db.session.commit()
     createUser(db.session)
     testApplication1 = Application(ApplicationStatus.SUBMITTED,
                                    "Fanta is better than solo",
                                    user=testuser1,
                                    partnerUsername=testuser2.username,
                                    preferredRoom="d1",
                                    seatRollover=True,
                                    applicationSeason=season,
                                    comments="Not Pepsi, but Pepsi Max")
     testApplication2 = Application(ApplicationStatus.SUBMITTED,
                                    "Fanta is better than solo",
                                    user=testuser2,
                                    partnerUsername=testuser1.username,
                                    preferredRoom="d1",
                                    seatRollover=True,
                                    applicationSeason=season,
                                    comments="Not Pepsi, but Pepsi Max")
     testApplication1.partnerApplication = testApplication2
     testApplication2.partnerApplication = testApplication1
     db.session.add(testApplication1)
     db.session.add(testApplication2)
     db.session.commit()
     assert testApplication1.partnerApplication is testApplication2
     assert testApplication2.partnerApplication is testApplication1
     self.app.test_client().put('http://localhost:5000/application/1',
                                headers=headers,
                                data=json.dumps(dict(partnerUsername="", )))
     assert testApplication1.partnerApplication is None
     assert testApplication2.partnerApplication is None
def test_cascading_user(db_session):
    season = createBasicSeason(db_session)
    user = User(username="******", sub="sub", email="email", fullname="Dudeman")
    application = Application(needs="needs",
                              user=user,
                              partnerUsername="******",
                              comments="comments",
                              preferredRoom="pref",
                              seatRollover=True,
                              rank=Rank.WRITING_MASTER,
                              status=ApplicationStatus.SUBMITTED,
                              applicationSeason=season)

    db_session.add(user)
    db_session.add(application)
    db_session.commit()
    db_session.expire_all()
    db_session.delete(application)
    db_session.commit()
    dbuser = db_session.query(User).first()
    assert dbuser == user
    assert user.application is None
def test_application_connect_to_season(db_session):
    season = createBasicSeason(db_session)
    user = User(username="******",
                sub="sub",
                email="email",
                fullname="schnep scmep")
    db_session.add(user)
    application = Application(needs="",
                              comments="",
                              user=user,
                              partnerUsername="",
                              preferredRoom="d1",
                              seatRollover=True,
                              rank=Rank.WRITING_MASTER,
                              status=ApplicationStatus.SUBMITTED,
                              applicationSeason=season)
    db_session.add(season)
    db_session.add(application)
    db_session.commit()
    dbseason = db_session.query(ApplicationSeason).first()
    assert application.applicationSeason == season
    assert dbseason.applications == [application]
Beispiel #23
0
def submit_rankings(data, ranking_type):
    if 'rankings' not in data:
        return "Bad Request", 400

    rankings = data['rankings']
    rankings_vals = sorted(map(lambda v: int(v), rankings.values()))

    # Validate rankings - monotonically increasing integers from 1 to n
    if len(rankings) > 1:
        increasing = all(x < y
                         for x, y in zip(rankings_vals, rankings_vals[1:]))
        if not increasing or rankings_vals[0] != 1:
            return "Invalid rankings", 409

    for app_id in rankings:
        rank = rankings.get(app_id)
        app = Application.by_id(ObjectId(app_id))
        if app is None:
            return "Invalid application ID", 400

        app.set(**{ranking_type: rank})

    return 200
 def test_get_all_applications(self):
     season = createBasicSeason(db.session)
     headers = {
         'Authorization': self.token,
         'AccessToken': self.accessToken
     }
     testuser1 = User(username="******",
                      sub="sub",
                      email="email",
                      fullname="Franky Frank")
     testuser2 = User(username="******",
                      sub="uuid",
                      email="email",
                      fullname="Schmemail")
     db.session.add(testuser1)
     db.session.add(testuser2)
     db.session.commit()
     createUser(db.session)
     testApplication1 = Application(ApplicationStatus.SUBMITTED,
                                    "Fanta is better than solo",
                                    user=testuser1,
                                    partnerUsername="******",
                                    preferredRoom="d1",
                                    seatRollover=True,
                                    applicationSeason=season,
                                    comments="Not Pepsi, but Pepsi Max")
     testApplication2 = Application(ApplicationStatus.SUBMITTED,
                                    "Fanta is better than solo",
                                    user=testuser2,
                                    partnerUsername="******",
                                    preferredRoom="d1",
                                    seatRollover=True,
                                    applicationSeason=season,
                                    comments="Not Pepsi, but Pepsi Max")
     db.session.add(testApplication1)
     db.session.add(testApplication2)
     db.session.commit()
     allApplications = self.app.test_client().get(
         'http://localhost:5000/application/all', headers=headers)
     assert allApplications.status == "200 OK"
     assert allApplications.data == jsonify(
         [testApplication1.to_json(),
          testApplication2.to_json()]).data
def test_cascading_partnerApplication(db_session):
    season = createBasicSeason(db_session)
    user1 = User(username="******",
                 sub="sub",
                 email="email",
                 fullname="Solvæng")
    application1 = Application(needs="needs",
                               user=user1,
                               partnerUsername="******",
                               comments="comments",
                               preferredRoom="pref",
                               seatRollover=True,
                               rank=Rank.WRITING_MASTER,
                               status=ApplicationStatus.SUBMITTED,
                               applicationSeason=season)
    user2 = User(username="******",
                 sub="sub2",
                 email="email2",
                 fullname="Sålvong")
    application2 = Application(needs="needs",
                               user=user2,
                               partnerUsername="******",
                               comments="comments",
                               preferredRoom="pref",
                               seatRollover=True,
                               rank=Rank.WRITING_MASTER,
                               status=ApplicationStatus.SUBMITTED,
                               applicationSeason=season)
    db_session.add(user1)
    db_session.add(user2)
    db_session.add(application1)
    db_session.add(application2)
    application1.partnerApplication = application2
    application2.partnerApplication = application1
    db_session.commit()
    db_session.expire_all()
    db_session.delete(application1)
    db_session.commit()
    dbapplication = db_session.query(Application).first()
    assert dbapplication == application2
    assert dbapplication.partnerApplication is None
def test_users_connect_each_other(db_session):
    season = createBasicSeason(db_session)
    testuser1 = User(username="******",
                     sub="sub",
                     email="email",
                     fullname="Asbjørn ELEVG baby")
    testuser2 = User(username="******",
                     sub="subs",
                     email="emails",
                     fullname="Asbjørns ELEVGs babys")
    db_session.add(testuser1)
    db_session.add(testuser2)
    application2 = Application(needs="",
                               comments="",
                               user=testuser2,
                               partnerUsername=testuser1.username,
                               preferredRoom="d1",
                               seatRollover=True,
                               rank=Rank.WRITING_MASTER,
                               status=ApplicationStatus.SUBMITTED,
                               applicationSeason=season)
    application1 = Application(needs="",
                               comments="",
                               user=testuser1,
                               partnerUsername=testuser2.username,
                               preferredRoom="d1",
                               seatRollover=True,
                               rank=Rank.WRITING_MASTER,
                               status=ApplicationStatus.SUBMITTED,
                               applicationSeason=season)
    application1.partnerApplication = application2
    application2.partnerApplication = application1
    db_session.add(application1)
    db_session.add(application2)
    db_session.commit()
    dbapp1 = db_session.query(Application).filter_by(user=testuser1).one()
    dbapp2 = db_session.query(Application).filter_by(user=testuser2).one()
    assert dbapp1.partnerApplication == application2
    assert dbapp2.partnerApplication == application1
    def get_category_apps_from_db(self,cat,catdir=""):
        list = self.db.query_category_apps(cat)
        apps = {}
        for item in list:
            pkgname = UnicodeToAscii(item[0])
            displayname = item[1]
            #            print "get_category_apps_from_db:",pkgname
            app = Application(pkgname,displayname, cat, self.apt_cache)
            if app.package:
                apps[pkgname] = app

                #if there has special information in db, get them
                #get_category_apps_from_db: 0 0
                #display_name, summary, description, rating_average,rating_total,review_total,download_total
                appinfo = self.db.query_application(pkgname)
                summary = appinfo[1]
                description = appinfo[2]
                rating_average = appinfo[3]
                rating_total = appinfo[4]
                review_total = appinfo[5]
                # rank = appinfo[6]

                #                if CheckChineseWords(app.summary) is False and CheckChineseWordsForUnicode(summary) is True:
                if summary is not None and summary != 'None':
                    app.summary = summary
                #                if CheckChineseWords(app.description) is False and CheckChineseWordsForUnicode(description) is True:
                if description is not None and summary != 'None':
                    app.description = description
                if rating_average is not None:
                    app.ratings_average = float(rating_average)
                if rating_total is not None:
                    app.ratings_total = int(rating_total)
                if review_total is not None:
                    app.review_total = int(review_total)
                    # if rank is not None:
                    #     app.rank = int(rank)
        return apps
Beispiel #28
0
import datetime

from models.transfer import Transfer
from models.application import Application

active_transfers = 0.0
total_transfers = 0.0
today = datetime.date.today()

for transfer in Transfer.all():
    if transfer.start_date <= today:
        total_transfers += sum(transfer.monthly_transfers)
        
app = Application.app()
app.total_transfers = total_transfers
app.put()
Beispiel #29
0
from database import db
from models.application import Application
from models.tag import Tag
from preprocessors.tag_preprocessor import add_tag
from main import app
from gp_parser import gp_parse

app.app_context().push()

app_seed1 = Application(
    name="Adobe Photoshop Express: редактор фото и коллажей",
    image_url=
    'https://play-lh.googleusercontent.com/kSYT6j4SVHdvA6FcP_erR5wBfPpAh_AVbxC5aihMe7OztbFV_iDAQOLdPN3fVyXmsqU=s180-rw',
    description=
    '<p>УЛУЧШЕНИЕ И СТИЛИЗАЦИЯ ФОТОГРАФИЙ.</p><p>Реализуйте свой потенциал с Photoshop Express, быстрым и простым редактором фотографий, которым пользуются миллионы творческих людей. Редактируйте фотографии, как профессионал, с помощью этой удобной многофункциональной цифровой студии на мобильном устройстве.</p><p></p><p>Photoshop Express предоставляет полный спектр разнообразных инструментов и эффектов. Используйте рамки и текст, улучшайте цвета и образы, создавайте коллажи, быстро исправляйте и улучшайте ваши достойные внимания моменты. И все это бесплатно!</p><p></p><p></p><p>КОРРЕКЦИЯ ПЕРСПЕКТИВЫ</p><p>• Исправляйте искривленные изображения автоматически.</p><p>• Исправьте искаженный угол съемки с помощью инструмента Трансформирование.</p><p></p><p>УДАЛЕНИЕ ШУМА</p><p>• Устраните зернистость или уменьшите цветовой шум для получения кристально чистого изображения.</p><p>• Повысьте резкость деталей для создания лучших изображений.</p><p></p><p>РАЗМЫТИЕ</p><p>• Привлеките внимание к определенным элементам и смешайте фон с помощью радиального размытия.</p><p>• Улучшайте изображения и создавайте эффект движения с помощью функций полного размытия.</p><p></p><p>РАМКИ И ТЕКСТ</p><p>• Добавьте индивидуальности стикерам, мемам и подписям.</p><p>• Измените стиль сообщений, используя множество шрифтов, цветов и настроек непрозрачности.</p><p>• Подберите рамку под цвет фото или свой вкус.</p><p>• Настройте размещение текста с помощью панорамирования, масштабирования и поворота.</p><p>• Добавьте водяные знаки, пользовательский текст или логотипы.</p><p></p><p>ФИЛЬТРЫ И ЭФФЕКТЫ</p><p>• Придайте эмоциям выразительности с помощью различных фильтров: «Монохромный», «Портрет», «Природа» и «Двухцветный».</p><p>• Поменяйте цветовую температуру, красочность и другие цветовые эффекты с помощью удобного ползунка.</p><p>• Удалите туман или дымку, чтобы создать насыщенный деталями пейзаж.</p><p></p><p>ПОТРЯСАЮЩИЕ КОЛЛАЖИ</p><p>• Создавайте профессиональные коллажи, добавляя готовые макеты сетки.</p><p></p><p>• Изменяйте толщину и цвет границ.</p><p>• Печатайте фотографии непосредственно из приложения.</p><p></p><p>ТОЧЕЧНОЕ ВОССТАНОВЛЕНИЕ</p><p>• Уберите дефекты и пятна с фотографий</p><p></p><p>БЫСТРЫЕ ИСПРАВЛЕНИЯ</p><p>• Кадрирование, выпрямление, вращение и зеркальное отражение фотографий.</p><p>• Автоматическое исправление контраста, экспозиции и баланса белого одним касанием.</p><p>• Устранение эффекта красных и засвеченных глаз.</p><p></p><p>ИМПОРТ И ЭКСПОРТ ФОТОГРАФИЙ</p><p>• Загружайте изображения со своего мобильного устройства, из Adobe Creative Cloud, Dropbox, Facebook и Google Фото.</p><p>• Поддержка, импорт и редактирование форматов RAW и TIFF.</p><p>• Изменение размера и настройка качества изображений JPEG перед сохранением.</p><p>• Делитесь своими фотографиями в Instagram, Facebook, Twitter, Flickr, WhatsApp и т. д. одним касанием.</p><p></p><p>Программа Photoshop Express создана компанией Adobe — разработчиком семейства Photoshop.</p><p></p><p>Условия использования Adobe:</p><p>Предназначено для лиц в возрасте 13 лет и старше. Требует принятия условий и положений политики конфиденциальности Adobe.</p><p>http://www.adobe.com/go/terms_linkfree_ru</p><p>http://www.adobe.com/go/privacy_policy_linkfree_ru</p><p></p>',
    appstore_link=
    'https://apps.apple.com/ru/app/photoshop-express-photo-editor/id331975235',
    gp_link='https://play.google.com/store/apps/details?id=com.adobe.psmobile',
    msstore_link=
    'https://www.microsoft.com/ru-ru/p/adobe-photoshop-express-%D1%80%D0%B5%D0%B4%D0%B0%D0%BA%D1%82%D0%BE%D1%80-%D0%B8%D0%B7%D0%BE%D0%B1%D1%80%D0%B0%D0%B6%D0%B5%D0%BD%D0%B8%D0%B9-%D1%81-%D0%BA%D0%BE%D1%80%D1%80%D0%B5%D0%BA%D1%82%D0%B8%D1%80%D0%BE%D0%B2%D0%BA%D0%B0%D0%BC%D0%B8-%D1%84%D0%B8%D0%BB%D1%8C%D1%82%D1%80%D0%B0%D0%BC%D0%B8-%D1%8D%D1%84%D1%84%D0%B5%D0%BA%D1%82%D0%B0%D0%BC%D0%B8-%D0%B8-%D1%80%D0%B0%D0%BC%D0%BA%D0%B0%D0%BC%D0%B8/9wzdncrfj27n'
)

tag_seed1 = add_tag('с размытием')
tag_seed2 = add_tag('с удалением шума')
tag_seed3 = add_tag('графический редактор', show_in_list=False)
tag_seed4 = add_tag('с фильтрами')
tag_seed5 = add_tag('для цветокоррекции')
if tag_seed1 != None:
    app_seed1.tags.append(tag_seed1)
if tag_seed2 != None:
    app_seed1.tags.append(tag_seed2)
Beispiel #30
0
    async def gameapplication(self, ctx, key: str, member: discord.Member):
        # check if game with key exist
        db_game = GameModel.getByKey(key)
        if db_game:
            foundGame = False
            for activity in member.activities:
                if activity.type == discord.ActivityType.playing:

                    # set found game true
                    foundGame = True

                    db_application = Application.getByID(
                        activity.application_id)
                    if not db_application:
                        db_application.id = activity.id
                        db_application.name = activity.name
                        db_session.add(db_application)
                        db_session.commit()

                    db_application_game = ApplicationGame.getByID(
                        db_application.id,
                        db_game.id
                    )
                    if not db_application_game:
                        db_application_game.applicationID = db_application.id
                        db_application_game.gameID = db_game.id
                        db_session.add(db_application_game)
                        db_session.commit()

                        # create output embed
                        embed = discord.Embed(
                            colour=discord.Colour.green(),
                            title="Application hinzugefügt",
                        )

                    else:
                        # create output embed
                        embed = discord.Embed(
                            colour=discord.Colour.red(),
                            title="Application wurde schon hinzugefügt",
                        )

                    embed.add_field(
                        name='Name',
                        value=f'{activity.name}',
                        inline=False
                    )

                    embed.add_field(
                        name='ApplicationID',
                        value=f'{activity.application_id}',
                        inline=False
                    )

                    embed.add_field(
                        name='Spiel',
                        value=f'{db_game.name}',
                        inline=False
                    )

                    embed.add_field(
                        name='SpielID',
                        value=f'{db_game.id}',
                        inline=False
                    )

                    Session.close_all()

                    # send message
                    await ctx.send(ctx.author.mention, embed=embed)
                    break

            if not foundGame:

                # create output embed
                embed = discord.Embed(
                    colour=discord.Colour.red(),
                    title=f'Kein Spiel gefunden'
                )
                embed.add_field(
                    name="Fehler", value=f'Es konnte kein Spiel bei {member.mention} entdeckt werden.', inline=False)

                # send embed
                await ctx.send(ctx.author.mention, embed=embed)

        else:

            # create output embed
            embed = discord.Embed(
                colour=discord.Colour.red(),
                title=f'Spiel nicht gefunden'
            )
            embed.add_field(
                name="Fehler", value=f'Es wurde kein Spiel mit dem Key "{key}" gefunden.', inline=False)

            # send embed
            await ctx.send(ctx.author.mention, embed=embed)
    def get_category_apps_from_db(self,cat,catdir=""):
        lists = self.appmgr.db.query_category_apps(cat)
        apps = {}
        for item in lists:
            #pkgname = UnicodeToAscii(item[0])
            pkgname = item[0]
            displayname_cn = item[1]
            if pkgname == "brasero":
                continue
            if pkgname in list(Globals.ALL_APPS.keys()):
                apps[pkgname] = Globals.ALL_APPS[pkgname]
            else:
                app = Application(pkgname,displayname_cn, cat, self.apt_cache)
                if app.package and app.package.candidate:
                    #if there has special information in db, get them
                    #get_category_apps_from_db: 0 0
                    #display_name, summary, description, rating_average,rating_total,review_total,download_total
                    app.from_ukscdb = True
                    app.orig_name = app.name#zx2015.01.26
                    app.orig_summary = app.summary
                    app.orig_description = app.description

                    appinfo = self.appmgr.db.query_application(pkgname)

                    app.displayname = appinfo[0]
                    app.summary = appinfo[1]
                    app.description = appinfo[2]
                    rating_average = appinfo[3]
                    rating_total = appinfo[4]
                    review_total = appinfo[5]
                    app.downloadcount = appinfo[7]
                    # rank = appinfo[6]

                    # #                if CheckChineseWords(app.summary) is False and CheckChineseWordsForUnicode(summary) is True:
                    # if summary is not None and summary != 'None':
                    #     app.summary = summary
                    # #                if CheckChineseWords(app.description) is False and CheckChineseWordsForUnicode(description) is True:
                    # if description is not None and summary != 'None':
                    #     app.description = description
                    if rating_average is not None:
                        app.ratings_average = float(rating_average)
                    if rating_total is not None:
                        app.ratings_total = int(rating_total)
                    if review_total is not None:
                        app.review_total = int(review_total)
                        # if rank is not None:
                        #     app.rank = int(rank)
                    apps[pkgname] = app

                    Globals.ALL_APPS[pkgname] = app #make sure there is only one app with the same pkgname even it may belongs to other category
        return apps
 def test_waiting_list(self):
     season = createBasicSeason(db.session)
     headers = {
         'Authorization': self.token,
         'AccessToken': self.accessToken,
         'Content-type': 'application/json'
     }
     testuser1 = User(username="******",
                      sub="sub",
                      email="email",
                      fullname="Franky Frank")
     testuser2 = User(username="******",
                      sub="uuid",
                      email="email",
                      fullname="Schmemail")
     testuser3 = User(username="******",
                      sub="ubuid",
                      email="email",
                      fullname="bruh")
     db.session.add(testuser1)
     db.session.add(testuser2)
     db.session.add(testuser3)
     db.session.commit()
     createUser(db.session)
     testApplication1 = Application(ApplicationStatus.SUBMITTED,
                                    "Fanta is better than solo",
                                    user=testuser1,
                                    partnerUsername="******",
                                    preferredRoom="d1",
                                    seatRollover=True,
                                    applicationSeason=season,
                                    comments="Not Pepsi, but Pepsi Max")
     testApplication2 = Application(ApplicationStatus.SUBMITTED,
                                    "Fanta is better than solo",
                                    user=testuser2,
                                    partnerUsername="******",
                                    preferredRoom="d1",
                                    seatRollover=True,
                                    applicationSeason=season,
                                    comments="Not Pepsi, but Pepsi Max")
     testApplication3 = Application(ApplicationStatus.SUBMITTED,
                                    "Fanta is better than Cola",
                                    user=testuser3,
                                    partnerUsername="",
                                    preferredRoom="d2",
                                    seatRollover=False,
                                    applicationSeason=season,
                                    comments="Not Cola, but Fanta Free")
     db.session.add(testApplication1)
     db.session.add(testApplication2)
     db.session.add(testApplication3)
     db.session.commit()
     # Dump to create new objects which are not changed by the post
     app1 = json.dumps(testApplication1.to_json())
     app2 = json.dumps(testApplication2.to_json())
     jsondata = json.dumps(dict(ids=[1, 2]))
     approvedApplications = self.app.test_client().post(
         'http://localhost:5000/application/waitingList',
         headers=headers,
         data=jsondata,
     )
     app1 = json.loads(app1)
     app2 = json.loads(app2)
     app1["status"] = "WAITING_LIST"
     app2["status"] = "WAITING_LIST"
     assert approvedApplications.status == "200 OK"
     assert json.loads(approvedApplications.data) == json.loads(
         jsonify([app1, app2]).data)
    def test_new_application_with_existing_partner(self):
        season = createBasicSeason(db.session)
        testuser1 = User(username="******",
                         sub=decodedToken.get("sub"),
                         email="email",
                         fullname="Franky Frank")
        testuser2 = User(username="******",
                         sub="sub",
                         email="emails",
                         fullname="Schmemails")
        testApplication = Application(ApplicationStatus.SUBMITTED,
                                      "Pepsi is better than coke",
                                      user=testuser2,
                                      partnerUsername="******",
                                      preferredRoom="d1",
                                      seatRollover=True,
                                      applicationSeason=season,
                                      comments="Not Pepsi, but Pepsi Max")
        db.session.add(testuser1)
        db.session.commit()
        db.session.add(testuser2)
        db.session.add(testApplication)
        db.session.commit()
        mimetype = 'application/json'
        headers = {
            'Content-Type': mimetype,
            'Accept': mimetype,
            'Authorization': self.token,
            'AccessToken': self.accessToken
        }
        user1Response = self.app.test_client().post(
            'http://localhost:5000/application/',
            headers=headers,
            data=json.dumps(
                dict(
                    username=testuser1.username,
                    needs="Fanta is better than solo",
                    comments="Bruh wtf",
                    partnerUsername=testuser2.username,
                    preferredRoom="d1",
                    seatRollover=True,
                )))
        user1expectedResponse = make_response(
            jsonify(
                needs="Fanta is better than solo",
                comments="Bruh wtf",
                id=2,
                status="SUBMITTED",
                user={
                    "id": testuser1.id,
                    "username": testuser1.username,
                    "email": testuser1.email,
                    "fullname": testuser1.fullname
                },
                preferredRoom="d1",
                rank="WRITING_MASTER",
                seatRollover=True,
                partnerApplication={
                    "needs": "Pepsi is better than coke",
                    "comments": "Not Pepsi, but Pepsi Max",
                    "id": 1,
                    "status": "SUBMITTED",
                    "rank": "OTHER",
                    "user": {
                        "id": testuser2.id,
                        "username": testuser2.username,
                        "email": testuser2.email,
                        "fullname": testuser2.fullname
                    },
                    "preferredRoom": "d1",
                    "seatRollover": True,
                },
            ), 201)

        expectedConnectedApplication = jsonify(
            needs="Pepsi is better than coke",
            comments="Not Pepsi, but Pepsi Max",
            id=1,
            status="SUBMITTED",
            user={
                "id": testuser2.id,
                "username": testuser2.username,
                "email": testuser2.email,
                "fullname": testuser2.fullname
            },
            preferredRoom="d1",
            seatRollover=True,
            seat=None,
            rank="OTHER",
            partnerApplication={
                "needs": "Fanta is better than solo",
                "comments": "Bruh wtf",
                "id": 2,
                "status": "SUBMITTED",
                "preferredRoom": "d1",
                "seatRollover": True,
                "rank": "WRITING_MASTER",
                "seat": None,
                "user": {
                    "id": testuser1.id,
                    "username": testuser1.username,
                    "email": testuser1.email,
                    "fullname": testuser1.fullname
                },
            },
        )
        getApplication = self.app.test_client().get(
            'http://localhost:5000/application/byUser/1', headers=headers)
        assert user1expectedResponse.status == user1Response.status
        assert json.loads(user1expectedResponse.data) == json.loads(
            user1Response.data)
        assert getApplication.status == "200 OK"
        assert json.loads(expectedConnectedApplication.data) == json.loads(
            getApplication.data)
    def create(self, data: dict, user: User) -> Application:
        try:
            application = Application()
            application.real_name = data["real_name"]
            application.model = data["model"]
            application.description = data["description"]
            application.details = data["details"] if "details" in data.keys(
            ) else None
            self.generate_name(application)
            application.created_at = datetime.now()
            application.created_by = user.id
            application.updated_at = datetime.now()
            application.updated_by = user.id
            application.activate = True
            application.add_user(user.id)
            self._repository.create(application)
            self._dbcontext.commit()
            self._logger.info(
                f"{user.email} created new application {application.name}")

            return application
        except Exception as e:
            self._logger.error(
                f"Error ocurred on create new application {str(e)}")
            self._dbcontext.rollback()

            raise e