Example #1
0
    def __create(self, args):
        result = {"status": "success",
                  "msg": "操作成功"}
        #print(args)

        product = AutoProduct.query.filter_by(name=args["name"]).first()
        if product is None:
            try:
                product = AutoProduct(name=args["name"],
                                      desc=args["desc"],
                                      tags=args["tags"],
                                      enable=args["enable"],
                                      create_author_id=current_user.get_id(),
                                      update_author_id=current_user.get_id())

                db.session.add(product)
                db.session.commit()
            except Exception as e:
                result["status"] = "fail"
                result["msg"] = "异常:%s" % str(e)
        else:
            result["status"] = "fail"
            result["msg"] = "产品名称[%s]重复" % args["name"]

        return result
Example #2
0
def all_drafts():
    # Returns the current beer list with the user ratings

    my_rating = db.session.query(UserBeerList.Beer_ID,
                                 db.func.avg(UserBeerList.Rating).label('Avg_Rating'),
                                 db.func.count(UserBeerList.Rating).label('Avg_Rating_cnt')) \
        .group_by(UserBeerList.Beer_ID). \
        filter(UserBeerList.User_ID == current_user.get_id()).subquery()

    others_rating = db.session.query(UserBeerList.Beer_ID,
                                     db.func.avg(UserBeerList.Rating).label('Avg_Rating'),
                                     db.func.count(UserBeerList.Rating).label('Avg_Rating_cnt')). \
        group_by(UserBeerList.Beer_ID). \
        filter(UserBeerList.User_ID != current_user.get_id()).subquery()

    rated_draft_list = db.session.query(DraftList.Beer_ID, DraftList.Beer, DraftList.Brewery,
                                        DraftList.BeerRating, DraftList.RatingSite,
                                        DraftList.OnDraft,
                                        my_rating.c.Avg_Rating.label('MyRating'),
                                        my_rating.c.Avg_Rating_cnt.label('MyRatingCnt'),
                                        others_rating.c.Avg_Rating.label('OtherRating'),
                                        others_rating.c.Avg_Rating_cnt.label('OtherRatingCnt')). \
        outerjoin(my_rating, DraftList.Beer_ID == my_rating.c.Beer_ID). \
        outerjoin(others_rating, DraftList.Beer_ID == others_rating.c.Beer_ID). \
        order_by(DraftList.Brewery).all()

    draft_list = [dict(Beer_ID=beer[0], Beer=beer[1], Brewery=beer[2],
                       BeerRating=beer[3], RatingSite=beer[4], OnDraft=beer[5],
                       MyRating=beer[6], MyRateCnt=beer[7], OthersRating=beer[8],
                       OthersRateCnt=beer[9]) for beer in rated_draft_list]

    return render_template('all_drafts.html', draft_list=draft_list, current_user=current_user)
Example #3
0
def login():
    error = None
    form = LoginFrom(request.form)

    if request.method == 'POST':
        #print request.form['username']
        #print request.form['password']

        if form.validate_on_submit():

            user = User.query.filter_by(name=form.username.data).first()
            if user is not None  and bcrypt.check_password_hash(user.password, form.password.data): 
            #print "sss"
            # if (request.form['username'] != 'admin') \
            #         or request.form['password'] != 'admin':
            #     error = 'Invalid Credentials. Please try again.'
            # else:
                #session['logged_in'] = True
                login_user(user)
                print current_user.id
                print current_user.name
                print current_user.get_id()
                #print current_user
                flash('You were logged in.')
                return redirect(url_for('homes.home'))
            else:
                error = 'Invalid Credentials. Please try again.'
    return render_template('login.html', form=form, error=error)
Example #4
0
    def __create(self, args):
        result = {"status": "success",
                  "msg": "操作成功"}

        case = AutoCase.query.filter_by(id=args["case_id"]).first()
        if case is not None:
            try:
                step = AutoStep(desc=args["desc"],
                                keyword=args["keyword"],
                                case_id=args["case_id"],
                                param_1=args["param_1"],
                                param_2=args["param_2"],
                                param_3=args["param_3"],
                                param_4=args["param_4"],
                                enable=args["enable"],
                                step=args["step"],
                                prev=args["prev"],
                                create_author_id=current_user.get_id(),
                                update_author_id=current_user.get_id())

                db.session.add(step)
                db.session.commit()
            except Exception as e:
                result["status"] = "fail"
                result["msg"] = "异常:%s" % str(e)
        else:
            result["status"] = "fail"
            result["msg"] = "步骤id[%s]不存在" % args["name"]

        return result
Example #5
0
def handle_twitter_callback():
    twitter = Twython(app.config['TWITTER_API_KEY'],app.config['TWITTER_API_SECRET'],
                      session['oauth_token'], session['oauth_token_secret'])
    success = True

    try:
        final_step = twitter.get_authorized_tokens(request.json['oauth_verifier'])
        user_oauth_token = final_step['oauth_token']
        user_oauth_token_secret = final_step['oauth_token_secret']

        user_twitter = Twython(app.config['TWITTER_API_KEY'],app.config['TWITTER_API_SECRET'],
                               user_oauth_token, user_oauth_token_secret)
        twitter_user_show = user_twitter.show_user(user_id=final_step['user_id'])
        current_user.set_twitter_data(final_step['user_id'], final_step['screen_name'], twitter_user_show)

        new_twitter_auth = TwitterAuth(current_user.get_id(), user_oauth_token, user_oauth_token_secret)
        db.session.add(new_twitter_auth)
        db.session.commit()

        tasks.get_tweets_per_user.delay(current_user.get_id())
        # db.session.close()
    except:
        # print 'error in twitter auth'
        success = False
    return jsonify({'success': success})
Example #6
0
def meals():
    form = MealForm()
    if form.validate_on_submit():
        ingredients = []
        print(request.values)
        for value in request.values:
            print(request.values[value])
            if 'amount' in value:
                number = value.split('_')[1]
                print("number: {}".format(number))
                amount = request.values[value]
                ingredient = request.values['ingredient_' + number]
                ingredients.append({"amount": amount, "ingredient_name": ingredient})
        print(ingredients)
        meal = {}
        meal['name'] = form.meal_name.data
        meal['directions'] = form.directions.data
        meal['ingredients'] = ingredients
        meal['user'] = current_user.get_id()
        app.config['MEALS_COLLECTION'].insert(meal)
        flash("Created meal!", category='success')
        return redirect('/meals')
    meals = app.config['MEALS_COLLECTION'].find({"user": current_user.get_id()})
    # ingredients = []
    # for i in range(0, 10):
    #    ingredients.append({'1', '1'})
    return render_template('meals.html', title='Meals', username=current_user.get_id(), meals=meals, form=form)
Example #7
0
    def __create(self, args):
        result = {"status": "success",
                  "msg": "操作成功"}

        project = AutoProduct.query.filter_by(name=args["name"]).first()
        if project is None:
            try:
                project = AutoProject(name=args["name"],
                                      desc=args["desc"],
                                      category=args["category"],
                                      product_id=args["product_id"],
                                      tags=args["tags"],
                                      enable=args["enable"],
                                      version=args["version"],
                                      cron=args["cron"],
                                      setup=args["setup"],
                                      teardown=args["teardown"],
                                      create_author_id=current_user.get_id(),
                                      update_author_id=current_user.get_id())

                db.session.add(project)
                db.session.commit()
                # app = current_app._get_current_object()
                # app.config["TRIGGER"].load_job_list()
            except Exception as e:
                result["status"] = "fail"
                result["msg"] = "异常:%s" % str(e)
        else:
            result["status"] = "fail"
            result["msg"] = "项目名称[%s]重复" % args["name"]

        return result
Example #8
0
def check_session_id():
    """
    Generate a UUID and store it in the session
    as well as in the WebSession table.
    """
    # TODO: Create UserAgentEntity and populate
    user_agent = get_user_agent()

    if 'uuid' not in session:
        session['uuid'] = str(uuid.uuid4())
        WebSessionEntity.create(session_id=session['uuid'],
                                user_id=current_user.get_id(),
                                ip=request.remote_addr,
                                date_time=datetime.datetime.now(),
                                user_agent=user_agent)
        return
    if current_user.is_authenticated():
        # update the user_id on the first request after login is completed
        session_id = session['uuid']
        web_session = WebSessionEntity.get_by_session_id(session_id)
        if web_session is not None:
            web_session = WebSessionEntity.update(
                web_session,
                user_id=current_user.get_id())
        else:
            app.logger.error("No row found for sess_id: {}".format(session_id))
Example #9
0
File: main.py Project: koffie/lmfdb
def edit(ID):
    from psycopg2 import DatabaseError
    if not allowed_knowl_id.match(ID):
        flask.flash("""Oops, knowl id '%s' is not allowed.
                  It must consist of lowercase characters,
                  no spaces, numbers or '.', '_' and '-'.""" % ID, "error")
        return flask.redirect(url_for(".index"))
    knowl = Knowl(ID)

    lock = None
    if request.args.get("lock", "") != 'ignore':
        try:
            lock = knowldb.is_locked(knowl.id)
        except DatabaseError as e:
            logger.info("Oops, failed to get the lock. Error: %s" %e)
    author_edits = lock and lock['who'] == current_user.get_id()
    logger.debug(author_edits)
    if author_edits:
        lock = None
    if not lock:
        try:
            knowldb.set_locked(knowl, current_user.get_id())
        except DatabaseError as e:
            logger.info("Oops, failed to set the lock. Error: %s" %e)

    b = get_bread([("Edit '%s'" % ID, url_for('.edit', ID=ID))])
    return render_template("knowl-edit.html",
                           title="Edit Knowl '%s'" % ID,
                           k=knowl,
                           bread=b,
                           lock=lock)
Example #10
0
    def __create(self, args):
        result = {"status": "success", "project_id": args["project_id"],
                  "msg": "操作成功"}

        suite = AutoObject.query.filter(and_(AutoObject.name == args["name"],
                                             AutoObject.project_id == args["project_id"])).first()
        if suite is None:
            try:
                suite = AutoObject(name=args["name"],
                                   desc=args["desc"],
                                   project_id=args["project_id"],
                                   tags=args["tags"],
                                   category=args["category"],
                                   enable=args["enable"],
                                   setup=args["setup"],
                                   teardown=args["teardown"],
                                   create_author_id=current_user.get_id(),
                                   update_author_id=current_user.get_id())

                db.session.add(suite)
                db.session.commit()
            except Exception as e:
                result["status"] = "fail"
                result["msg"] = "异常:%s" % str(e)
        else:
            result["status"] = "fail"
            result["msg"] = "对象集名称[%s]重复" % args["name"]

        return result
Example #11
0
    def __create(self, args):
        result = {"status": "success",
                  "msg": "操作成功"}

        case = AutoCase.query.filter(and_(AutoCase.name == args["name"],
                                          AutoCase.suite_id == args["suite_id"])).first()
        if case is None:
            try:
                case = AutoCase(name=args["name"],
                                desc=args["desc"],
                                suite_id=args["suite_id"],
                                tags=args["tags"],
                                enable=args["enable"],
                                setup=args["setup"],
                                teardown=args["teardown"],
                                create_author_id=current_user.get_id(),
                                update_author_id=current_user.get_id())

                db.session.add(case)
                db.session.commit()
                result["suite_id"] = case.suite_id
            except Exception as e:
                result["status"] = "fail"
                result["msg"] = "异常:%s" % str(e)
        else:
            result["status"] = "fail"
            result["msg"] = "用例名称[%s]重复" % args["name"]

        return result
Example #12
0
    def leave(self, user):
        """Remove user from group.

        :param user: User to remove from the group.
        """
        # if I want to remove another user from the group
        if(user.id != current_user.get_id() and
           # I need to be an admin of the group
           not self.is_admin(current_user.get_id())):
            raise AccountSecurityError(
                'Not enough right to '
                'remove user "{0}" from group "{1}"'
                .format(user.nickname, self.name))

        # check that I'm not the last admin before leaving the group.
        if self.is_admin(user.id) and self.admins.count() == 1:
            raise IntegrityUsergroupError(
                'User can leave the group '
                'without admins, please delete the '
                'group if you want to leave.')

        # leave the group
        UserUsergroup.query.filter_by(
            id_usergroup=self.id,
            id_user=user.id,
        ).delete()
        try:
            db.session.commit()
        except Exception:
            db.session.rollback()
            raise
Example #13
0
def activity_stats():
    pos_purchases_query = db.session.query(
            db.func.sum(Product.price).label('amount'), 
            db.func.count(Product.price).label('units')
        )\
        .join(Purchase, Purchase.product_id == Product.id)\
        .filter(Purchase.activity_id == current_user.get_id())\
        .filter(Purchase.undone == False)
    auction_purchases_query = db.session.query(
            db.func.sum(AuctionPurchase.price).label('amount'), 
            db.func.count(AuctionPurchase.price).label('units')
        )\
        .filter(AuctionPurchase.activity_id == current_user.get_id())\
        .filter(AuctionPurchase.undone == False)

    stats = {
        'pos_purchases_total': pos_purchases_query.first(),
        'pos_purchases_products': pos_purchases_query.add_column(Product.name)\
            .group_by(Product.name).order_by(db.desc('amount')).all(),
        'pos_purchases_participants': pos_purchases_query.add_column(Participant.name)\
            .join(Participant, Purchase.participant_id == Participant.id)\
            .group_by(Participant.name).order_by(db.desc('amount')).limit(10),
        'auction_purchases_total': auction_purchases_query.first(),
        'auction_purchases_participants': auction_purchases_query.add_column(Participant.name)\
            .join(Participant, AuctionPurchase.participant_id == Participant.id)\
            .group_by(Participant.name).order_by(db.desc('amount')).limit(10)
    }
    return render_template('pos/activity_stats.html', **stats)
Example #14
0
def groceries():
    days_since_epoch = (datetime.datetime.now() - datetime.datetime(1970, 1, 1)).days
    day_of_week = datetime.datetime.now().weekday()
    low_range = days_since_epoch - (day_of_week + 1)
    high_range = days_since_epoch + (6 - day_of_week)
    user_calendar = app.config['CALENDAR_COLLECTION'].find({"days": {"$gte": low_range, "$lt": high_range},
                                                            "user": current_user.get_id(),
                                                            "bought": {"$ne": 'true'}}).sort("days",
                                                                                             pymongo.ASCENDING)
    groceries = []
    for day in user_calendar:
        meal = app.config['MEALS_COLLECTION'].find_one({"_id": day['meal_id']})
        for ingredient in meal['ingredients']:
            if ingredient['ingredient_name'] == '' or ingredient['amount'] == '':
                continue
            # TODO: Need to make units work
            # for grocery in groceries:
            #    if grocery['name'] == ingredient['ingredient_name']:
            #        grocery['amount'] += ingredient['amount']
            #        continue
            grocery = {"name": ingredient['ingredient_name'], "amount": ingredient['amount'],
                       "id": str(day['_id']) + ingredient['ingredient_name']}
            groceries.append(grocery)
    print(groceries)
    return render_template('groceries.html', title='Groceries', username=current_user.get_id(), groceries=groceries)
Example #15
0
    def __init__(self):
        super(SearchRequestsForm, self).__init__()
        self.agency_ein.choices = get_agency_choices()
        self.agency_ein.choices.insert(0, ('', 'All'))
        if current_user.is_agency:
            self.agency_ein.default = current_user.default_agency_ein
            user_agencies = sorted([(agencies.ein, agencies.name) for agencies in current_user.agencies
                                    if agencies.ein != current_user.default_agency_ein],
                                   key=lambda x: x[1])
            default_agency = current_user.default_agency

            # set default value of agency select field to agency user's primary agency
            self.agency_ein.default = default_agency.ein
            self.agency_ein.choices.insert(1, self.agency_ein.choices.pop(self.agency_ein.choices.index(
                (default_agency.ein, default_agency.name))
            ))

            # set secondary agencies to be below the primary
            for agency in user_agencies:
                self.agency_ein.choices.insert(2, self.agency_ein.choices.pop(self.agency_ein.choices.index(agency)))

            # get choices for agency user select field
            if current_user.is_agency_admin():
                self.agency_user.choices = get_active_users_as_choices(current_user.default_agency.ein)

            if current_user.is_agency_active() and not current_user.is_agency_admin():
                self.agency_user.choices = [
                    ('', 'All'),
                    (current_user.get_id(), 'My Requests')
                ]
                self.agency_user.default = current_user.get_id()

            # process form for default values
            self.process()
Example #16
0
def index():
    """List user tokens."""
    clients = Client.query.filter_by(
        user_id=current_user.get_id(),
        is_internal=False,
    ).all()

    tokens = Token.query.options(db.joinedload('client')).filter(
        Token.user_id == current_user.get_id(),
        Token.is_personal == True,  # noqa
        Token.is_internal == False,
        Client.is_internal == True,
    ).all()

    authorized_apps = Token.query.options(db.joinedload('client')).filter(
        Token.user_id == current_user.get_id(),
        Token.is_personal == False,  # noqa
        Token.is_internal == False,
        Client.is_internal == False,
    ).all()

    return render_template(
        'invenio_oauth2server/settings/index.html',
        clients=clients,
        tokens=tokens,
        authorized_apps=authorized_apps,
    )
Example #17
0
def milestone(owner, repo, number):
    """
    Load a single milestone from Github into WebhookDB.

    :query inline: process the request inline instead of creating a task
      on the task queue. Defaults to ``false``.
    :statuscode 200: milestone successfully loaded inline
    :statuscode 202: task successfully queued
    :statuscode 404: specified milestone was not found on Github
    """
    inline = bool(request.args.get("inline", False))
    children = bool(request.args.get("children", False))
    bugsnag_ctx = {"owner": owner, "repo": repo, "number": number, "inline": inline}
    bugsnag.configure_request(meta_data=bugsnag_ctx)

    if inline and not children:
        try:
            sync_milestone(
                owner, repo, number, children=children,
                requestor_id=current_user.get_id(),
            )
        except NotFound as exc:
            return jsonify({"message": exc.message}), 404
        else:
            return jsonify({"message": "success"})
    else:
        result = sync_milestone.delay(
            owner, repo, number, children=children,
            requestor_id=current_user.get_id(),
        )
        resp = jsonify({"message": "queued"})
        resp.status_code = 202
        resp.headers["Location"] = url_for("tasks.status", task_id=result.id)
        return resp
Example #18
0
def can_edit_dashboard(dashboard_uuid):
    dashboard = db.session.query(Dashboard).get(dashboard_uuid)
    if not dashboard:
        return False

    # superadmin can edit
    if current_user.is_superadmin:
        return True

    if dashboard.user_id:
        # test user permission, owner can edit
        return dashboard.user_id == current_user.get_id()

    elif dashboard.group_id:
        # test group permission, group admin can edit
        gm = db.session.query(GroupMember).\
            filter(GroupMember.user_id == current_user.get_id()).\
            filter(GroupMember.group_id == dashboard.group_id).\
            filter(GroupMember.is_admin).\
            first()
        return bool(gm)

    else:
        raise OwnerNotSetError(
            "dashboard %s don't have a owner" % dashboard.id)
Example #19
0
    def join(self, user, status=None):
        """Join user to group.

        :param user: User to add into the group.
        :param status: status of user
        """
        # if I want to join another user from the group
        if(user.id != current_user.get_id() and
           # I need to be an admin of the group
           not self.is_admin(current_user.get_id())):
            raise AccountSecurityError(
                'Not enough right to '
                'add user "{0}" from group "{1}"'
                .format(user.nickname, self.name))

        # join group
        self.users.append(
            UserUsergroup(
                id_user=user.id,
                user_status=status or self.new_user_status,
            )
        )
        try:
            db.session.commit()
        except Exception:
            db.session.rollback()
            raise
def home(var):
  global final_html
  global df,df_train,df_test,test_train_created,lin_model,log_model,log_reg_key,res_log,log_predict1,res_lin,lin_predict1,lin_reg_key
  # Upload the data file
  if (var == 'upl'):
	f = request.files['myfile']
	print "Current user1",current_user.get_id()
	filename1 = ""
	filename1 = filename + str(current_user.get_id()) + ".csv"
	f.save(filename1)
	filename1 = filename + str(current_user.get_id()) + ".csv"
	df = pd.read_csv(filename1)
	#Original Data frame
	origin_df = df
	#Take a subset of records to display as sample
	df1 = df[1:10]
	s = "<br><br>" + df1.to_html()
	# String in HTML form to be returned
	final_html = template.s2 +"""<div style="width:600px; height:700px; position: absolute; top: 20px; left:500px;"><b>File Uploaded Successfully !!</b></div>"""+  s
	return final_html
  # This will restore the original data uploaded from CSV. All changes made in the functions will be lost
  elif (var == 'restore'):
	#df = pd.read_csv("E:/test2.csv")
	s = "<br><br>" + df[1:10].to_html()
	final_html = template.s1 + "</div>" + s
	print "Current user2",current_user
	return final_html
  #Function called to Export dataset prepared
  elif (var ==	'view'):
	try:
		df_train.to_csv(template.save_train_data_path)
		temp_df = df[1:10]	
		s = "<br><br>" + temp_df.to_html()
		return template.s1 + "</div><br> <b> Sample Data (10 rows) </b> drive <br>" + s
	except:
		return template.s1 + """</div><br><font color="lightcoral"> Something went wrong. Please try again </font><br><br>""" + df[1:15].to_html()
  # Create random Test and train data samples
  elif (var == 'testrain'):
	#df = pd.read_csv("E:/test2.csv")
	#s = "<br><br>" + df[1:15].to_html()
	s = df[1:10].to_html()
	final_html = template.s1 + template.train_per + "</div>" + s
	return final_html
  elif (var == 'lin_test'):
	#df = pd.read_csv("E:/test2.csv")
	try:
		df_test['PREDICTED_LIN'] = res_lin.predict(df_test[lin_reg_key])
		df_test.to_csv(template.save_lin_predict_path)
		s = """<div style="width:600px; height:700px; position: absolute; top: 20px; left:500px;"><br><br> ***** Predicted Values (sample) **** <br>""" + (DataFrame(df_test['PREDICTED_LIN'])[1:10]).to_html() + "</div>" + df[1:15].to_html()
		final_html = template.s1 + "</div>" + s
		return final_html
	except KeyError,ValueError:
		s = """<div style="width:600px; height:700px; position: absolute; top: 20px; left:500px;"><font color="lightcoral">Error.  Please select the proper parameters and try again. </font><br><br> <br></div>""" + df[1:15].to_html()
		final_html = template.s1 + "</div>" + s
		return final_html
	except AttributeError:
		s = """<div style="width:600px; height:700px; position: absolute; top: 20px; left:500px;"><font color="lightcoral"> Error. Please select the proper parameters and try again. </font><br><br></div>""" + df[1:15].to_html()
		final_html = template.s1 + "</div>" + s
		return final_html	
Example #21
0
def manage_task(task_id):
    cursor = get_connection().cursor()
    if request.method == 'GET':
        cursor.execute('SELECT t.id, t.name, t.domain, t.author, u.name '
                       'FROM LTN_DEVELOP.TASKS t LEFT OUTER JOIN LTN_DEVELOP.USERS u ON u.id = t.author '
                       'WHERE t.id = ?', (task_id,))
        result = cursor.fetchone()
        cursor.execute('SELECT d.id, count(ud.id) '
                       'FROM LTN_DEVELOP.TASKS t '
                       'JOIN LTN_DEVELOP.DOCUMENTS d ON d.task = t.id '
                       'LEFT OUTER JOIN LTN_DEVELOP.USER_DOCUMENTS ud ON ud.document_id = d.id '
                       'AND (ud.visibility = 1 OR ud.user_id = ?) '
                       'WHERE t.id = ? '
                       'GROUP BY d.id ORDER BY d.id ASC', (current_user.get_id(), task_id))
        documents = list()
        for row in cursor.fetchall():
            documents.append({'document_id': row[0], 'user_document_count': row[1]})
        return respond_with({'task_id': result[0], 'task_name': result[1], 'task_domain': result[2],
                             'user_id': result[3], 'user_name': result[4], 'documents': documents})
    elif request.method == 'POST':
        req = request.get_json()
        if req.get('task_id') is not None:
            sql_to_prepare = 'CALL LTN_DEVELOP.update_task (?, ?, ?, ?, ?)'
        else:
            sql_to_prepare = 'CALL LTN_DEVELOP.add_task (?, ?, ?, ?, ?)'

        params = {
            'TASK_ID': req.get('task_id'),
            'TASK_NAME': req.get('task_name'),
            'TABLE_NAME': req.get('task_domain'),
            'ER_ANALYSIS_CONFIG': req.get('task_config'),
            'NEW_AUTHOR': req.get('user_id')
        }

        if params.get('TABLE_NAME', None) is None:
            generate_table_name(params)
        if params.get('NEW_AUTHOR', None) is None:
            params['NEW_AUTHOR'] = current_user.get_id()

        psid = cursor.prepare(sql_to_prepare)
        ps = cursor.get_prepared_statement(psid)
        try:
            cursor.execute_prepared(ps, [params])
            get_connection().commit()
        except:
            pass  # Rows affected warning
        return 'OK', 200
    elif request.method == 'DELETE':
        sql_to_prepare = 'CALL LTN_DEVELOP.delete_task (?)'
        params = {'TASK_ID': task_id}
        psid = cursor.prepare(sql_to_prepare)
        ps = cursor.get_prepared_statement(psid)
        try:
            cursor.execute_prepared(ps, [params])
            get_connection().commit()
        except:
            pass  # Rows affected warning
        return 'OK', 200
Example #22
0
 def update_selector_list(self, select=None):
     if select is None:
         socketio.emit('update-selector-list',
                       {"html": self.request_update_selector_list(), "res_type": self.res_type},
                       namespace='/user_manage', room=current_user.get_id())
     else:
         socketio.emit('update-selector-list',
                       {"html": self.request_update_selector_list(), "select": select, "res_type": self.res_type},
                       namespace='/user_manage', room=current_user.get_id())
Example #23
0
    def update(self, *args, **kwargs):
        try:
            if not self.created_by:
                self.created_by = current_user.get_id()
            self.modified_by = current_user.get_id()
        except:
            pass

        self.modified = datetime.now()
        return Document.update(self, *args, **kwargs)
Example #24
0
def logout():
    socketio.emit('close-user-windows', {}, namespace='/user_manage', room=current_user.get_id())
    socketio.emit('close-user-windows', {}, namespace='/main', room=current_user.get_id())
    if current_user.username in user_tiles:
        del user_tiles[current_user.username]
    if current_user.username in loaded_user_modules:
        del loaded_user_modules[current_user.username]
    logout_user()
    return render_template('auth/login.html', show_message="yes",
                           message="You have been logged out.", alert_type="alert-info")
Example #25
0
 def unload_all_tiles(self):
     try:
         loaded_user_modules[current_user.username] = set([])
         user_tiles[current_user.username] = {}
         socketio.emit('update-loaded-tile-list', {"html": self.render_loaded_tile_list()},
                       namespace='/user_manage', room=current_user.get_id())
         socketio.emit('update-menus', {}, namespace='/main', room=current_user.get_id())
         return jsonify({"message": "Tiles successfully unloaded", "alert_type": "alert-success"})
     except:
         error_string = "Error unloading tiles: " + str(sys.exc_info()[0]) + " " + str(sys.exc_info()[1])
         return jsonify({"success": False, "message": error_string, "alert_type": "alert-warning"})
Example #26
0
def load_page_root():
    search_form = LoadListRootSearchForm()
    if search_form.is_submitted():
        page = LoadPageRoot.query.filter_by(user_id = current_user.get_id())
        if search_form.start_period.data:
            page = page.filter(LoadPageRoot.start_period >= search_form.start_period.data)
        if search_form.end_period.data:
            page = page.filter(LoadPageRoot.end_period <= search_form.end_period.data)

        return render_template('professor/load_page/load_page_root.html', load_page=page.all(), form=search_form)
    else:
        page = LoadPageRoot.query.filter_by(user_id=current_user.get_id()).all()
    return render_template('professor/load_page/load_page_root.html', load_page=page, form=search_form)
Example #27
0
File: views.py Project: sntp/post
def send_post():
    form = SendMailForm()
    if form.validate_on_submit():
        sender_id = current_user.get_id()
        recipient_id = User.query \
            .filter(User.username == form.recipient.data.lower()) \
            .first() \
            .get_id()
        status = 'draft' if form.draft.data is True else 'sent'
        title = form.title.data or '...'
        text = form.text.data or '...'
        if form.draft_id.data:
            draft_id = form.draft_id.data
            draft_mail = Mail \
                .query \
                .filter(Mail.id == draft_id,
                        Mail.sender_id == current_user.get_id(),
                        Mail.status == MailStatus.DRAFT) \
                .first()
            if draft_mail:
                Mail.query \
                    .filter(Mail.id == draft_id) \
                    .update(dict(sender_id=sender_id,
                                 recipient_id=recipient_id,
                                 title=title,
                                 text=text,
                                 status=status,
                                 timestamp=datetime.now().isoformat()))
                db.session.commit()
        else:
            mail = Mail(sender_id, recipient_id, title, text, status)
            db.session.add(mail)
            db.session.commit()
        if status is 'sent':
            flash('Mail successfully sent.', 'success')
        else:
            flash('Mail saved to draft.', 'success')
        return redirect(url_for('send_get'))
    else:
        if not user_exists(form.recipient.data):
            flash('User with username \'%s\' doesn\'t exist.'
                  % form.recipient.data, 'danger')
        else:
            flash('Validation fail.', 'danger')
    return render_template('send-mail.html',
                           title='Send mail',
                           form=form,
                           new_mails=_new_mails_count(),
                           draft_mails=_draft_count())
Example #28
0
def calendar(view):
    if view == 'day':
        days_since_epoch = (datetime.datetime.now() - datetime.datetime(1970, 1, 1)).days
        print(days_since_epoch)
        user_calendar = app.config['CALENDAR_COLLECTION'].find(
            {"days": days_since_epoch, "user": current_user.get_id()})
    if view == 'week':
        days_since_epoch = (datetime.datetime.now() - datetime.datetime(1970, 1, 1)).days
        day_of_week = datetime.datetime.now().weekday()
        low_range = days_since_epoch - (day_of_week + 1)
        high_range = days_since_epoch + (6 - day_of_week)
        user_calendar = app.config['CALENDAR_COLLECTION'].find({"days": {"$gte": low_range, "$lt": high_range},
                                                                "user": current_user.get_id()}).sort("days",
                                                                                                     pymongo.ASCENDING)
    return render_template('calendar.html', title='Calendar', username=current_user.get_id(), calendar=user_calendar)
Example #29
0
def metadata(recid, of="hd", ot=None):
    """Display formated record metadata."""
    from invenio.legacy.bibrank.downloads_similarity import register_page_view_event
    from invenio.modules.formatter import get_output_format_content_type

    register_page_view_event(recid, current_user.get_id(), str(request.remote_addr))
    if get_output_format_content_type(of) != "text/html":
        from invenio.modules.search.views.search import response_formated_records

        return response_formated_records([recid], g.collection, of, qid=None)

    # Send the signal 'document viewed'
    record_viewed.send(current_app._get_current_object(), recid=recid, id_user=current_user.get_id(), request=request)

    return render_template("records/metadata.html", of=of, ot=ot)
Example #30
0
    def post(self, record_id):
        """Attach a list of tags to a record.

        If a tag in the list exists in database then it is attached
        to the record else the tag is created an then it is attached
        to the record
        :param record_id: the identifier of the record
        """
        json_data = request.get_json()
        attachTagsValidator = RESTValidator(add_tags_schema)
        if attachTagsValidator.validate(json_data) is False:
            raise TagValidationError(
                error_msg="Validation error in attaching tags on record",
                status_code=400,
                error_list=attachTagsValidator.get_errors())
        uid = current_user.get_id()
        tags_just_attached = tags_api.attach_tags_to_record(uid,
                                                            json_data['tags'],
                                                            record_id)
        if len(tags_just_attached) == 0:
            return []
        else:
            return map(
                lambda t: TagRepresenation(t).marshal(), tags_just_attached
            )
Example #31
0
def get_note(note_id):
    note = Note.find_by_id(note_id=note_id)
    if not note:
        raise ResourceNotFoundError('Note not found')
    note_read = NoteRead.when_user_read_note(current_user.get_id(), str(note.id))
    return tolerant_jsonify(_boa_note_to_compatible_json(note=note, note_read=note_read))
Example #32
0
def score_route_view():
    next_image = _select_image(int(current_user.get_id()))
    if not next_image:
        return redirect('/finished')
    return redirect('/score/%s' % next_image.id)
Example #33
0
def index(template, is_mobile=False):
    class MainForm(FlaskForm):
        camera_file = FileField()
        file = FileField()
        agree = BooleanField("Я согласен")
        disgree = BooleanField("Возражаю")
        lang = SelectField("Язык текста",
                           choices=[('RU', 'Русский'), ('EN', 'English'),
                                    ('DE', 'German'), ('GR', 'Ελληνικά'),
                                    ('LV', 'Latviešu'), ('PL', 'Polski'),
                                    ('UZ', 'Ўзбек'), ('UZL', "O'zbekcha")])
        find_orientation = BooleanField("Авто-ориентация")
        process_2_sides = BooleanField("Обе стороны")

    form = MainForm(
        agree=request.values.get('has_public_confirm', '') == 'True',
        disgree=request.values.get('has_public_confirm', '') == 'False',
        lang=request.values.get('lang', 'RU'),
        find_orientation=request.values.get('find_orientation',
                                            'True') == 'True',
        process_2_sides=request.values.get('process_2_sides',
                                           'False') == 'True')
    if form.validate_on_submit():
        file_data = form.camera_file.data or form.file.data
        if not file_data:
            flash('Необходимо загрузить файл')
            return render_template(template, form=form)
        if form.agree.data and form.disgree.data or not form.agree.data and not form.disgree.data:
            flash('Выберите один из двух вариантов (согласен/возражаю)')
            return render_template(template, form=form)
        filename = file_data.filename
        file_ext = Path(filename).suffix.lower()
        if file_ext not in VALID_EXTENTIONS:
            flash('Не подхожящий тип файла {}: {}'.format(file_ext, filename))
            return render_template(template, form=form)

        user_id = current_user.get_id()
        extra_info = {
            'user': user_id,
            'has_public_confirm': form.agree.data,
            'lang': form.lang.data,
            'find_orientation': form.find_orientation.data,
            'process_2_sides': form.process_2_sides.data,
        }
        task_id = core.process(user_id=user_id,
                               file_storage=file_data,
                               param_dict=extra_info)

        if not form.agree.data:
            return redirect(
                url_for('confirm',
                        task_id=task_id,
                        lang=form.lang.data,
                        find_orientation=form.find_orientation.data,
                        process_2_sides=form.process_2_sides.data))
        return redirect(
            url_for('results',
                    task_id=task_id,
                    has_public_confirm=form.agree.data,
                    lang=form.lang.data,
                    find_orientation=form.find_orientation.data,
                    process_2_sides=form.process_2_sides.data))

    return render_template(template, form=form)
Example #34
0
def pedido():
    if request.method == "POST":

        jsondata = request.get_json()
        importeTotal = 0
        mocked = randint(100, 9999)
        usuarioActual = Usuario.query.filter_by(
            id=current_user.get_id()).first()
        pedidoActual = Pedido(mocked, "pendiente", mocked * 37,
                              current_user.get_id())
        cabeceraDetalle = CabeceraDetalle(importeTotal, pedidoActual.id,
                                          pedidoActual)
        lineasDetalle = []

        for linea in jsondata:
            subtotal = 0
            idProducto = linea['id']
            cantidad = linea['cantidad']

            if idProducto and cantidad != '':
                producto = Producto.query.filter(
                    Producto.id.like(idProducto)).first()

                if producto:
                    """aca se deberia descubrir si hay stock haciendo la sumatoria del historial, 
                si la sumatoria del historial para ese id de producto es positiva entonces se 
                deberia comparar contra la cantidad solicitada, si es coherente, levantar el pedido"""
                subtotal = float(producto.importe_unitario) * int(cantidad)
                linea = LineaDetalle(cabeceraDetalle.id, producto.id, cantidad,
                                     subtotal)
                lineasDetalle.append(linea)
                importeTotal += subtotal
                print(linea.__dict__)
            else:
                flash(FLASH_MSG.get("PROD_NOT_FOUND"), "danger")
                return jsonify(
                    dict(redirect=url_for('main.buscar'),
                         result=session.get("request")))
        cabeceraDetalle.importe_total = float(importeTotal)
        try:
            db.session.add(pedidoActual)
            print(pedidoActual.__dict__)
            db.session.flush()
            db.session.add(cabeceraDetalle)
            print(cabeceraDetalle.__dict__)
            db.session.flush()
            for linea in lineasDetalle:
                linea.cabecera = cabeceraDetalle.id
                print(linea.__dict__)
            db.session.bulk_save_objects(lineasDetalle)
            db.session.flush()
            db.session.commit()
            flash(FLASH_MSG.get("PED_PROD_SUCC"), "success")
        except:
            flash(FLASH_MSG.get("PED_PROD_FAIL"), "danger")
            traceback.print_exc()
            db.session.rollback()

        pedidosUsuario = Pedido.query.filter_by(
            solicitante=current_user.get_id()).all()

        for p in pedidosUsuario:
            if (p.estado != "entregado"):
                if p.estado == "pendiente":
                    flash("Pedido %s" % p.nro_pedido, "info")
                else:
                    flash("Pedido %s" % p.nro_pedido, "warning")

        pedi_schema = PedidoSchema(many=True)
        session['pedidos'] = pedi_schema.dump(pedidosUsuario)
        '''
        #logica para un solo producto por pedido
        if idProducto:
            producto = Producto.query.filter(
                Producto.id.like(idProducto)).first()
            if producto:

                #cantidadSolicitada = json['cantidad']
                # if cantidadSolicitada <= producto.stock:
                # ....
                usuarioActual = Usuario.query.filter_by(
                    id=current_user.get_id()).first()
                mocked = randint(100, 9999)
                pedidoActual = Pedido(mocked, "pendiente",
                                      mocked*37, current_user.get_id())
                try:
                    db.session.add(pedidoActual)
                    db.session.commit()
                    flash(FLASH_MSG.get("PED_PROD_SUCC"), "success")
                except:
                    flash(FLASH_MSG.get("PED_PROD_FAIL"), "danger")                    
                    db.session.rollback()                    
            else:
                flash(FLASH_MSG.get("PROD_NOT_FOUND"), "danger")


        pedidosUsuario = Pedido.query.filter_by(
                    id=current_user.get_id()).all()        

        pedi_schema = PedidoSchema(many=True)        
        session['pedidos'] = pedi_schema.dump(pedidosUsuario)     '''

        return jsonify(
            dict(redirect=url_for('main.buscar'),
                 result=session.get("request")))
    else:
        return render_template('busqueda.html')
Example #35
0
    req.write(oai_header(argd, verb))
    for recid in list(complete_list)[cursor:cursor + CFG_OAI_LOAD]:
        req.write(
            print_record(recid,
                         argd['metadataPrefix'],
                         verb=verb,
                         set_spec=argd.get('set'),
                         set_last_updated=set_last_updated))

    if list(complete_list)[cursor + CFG_OAI_LOAD:]:
        resumption_token = oai_generate_resumption_token(argd.get('set', ''))
        cache = {
            'argd': argd,
            'last_recid': recid,
            # FIXME introduce IP check if you use fireroles for guests
            'id_user': current_user.get_id(),
            'complete_list': complete_list.fastdump(),
        }
        oai_cache_dump(resumption_token, cache)
        expdate = oai_get_response_date(CFG_OAI_EXPIRE)
        req.write(
            X.resumptionToken(
                expirationDate=expdate,
                cursor=cursor,
                completeListSize=len(complete_list))(resumption_token))
    elif resumption_token_was_specified:
        ## Since a resumptionToken was used we shall put a last empty resumptionToken
        req.write(
            X.resumptionToken(cursor=cursor,
                              completeListSize=len(complete_list))(""))
    req.write(oai_footer(verb))
Example #36
0
def curated_group_ids_per_sid(sid):
    return tolerant_jsonify(
        CuratedGroup.curated_group_ids_per_sid(user_id=current_user.get_id(),
                                               sid=sid))
Example #37
0
def itemdetail(form, itemid=0):

    sellerid = current_user.get_id()
    sellerinfo = mongo.db.user.find_one({'_id': ObjectId(sellerid)})
    target = os.path.join(APP_ROOT, '../static')
    print(target)
    print(request.files.getlist("images"))
    if not os.path.isdir(target):
        os.mkdir(target)
    imageslist = []
    if form.validate_on_submit():
        for upload in request.files.getlist("images"):
            print("Entered file section")
            print(upload)
            print("{} is the file name".format(upload.filename))
            filename = upload.filename
            # This is to verify files are supported
            ext = os.path.splitext(filename)[1]
            if (ext == ".jpg") or (ext == ".png"):
                print("File supported moving on...")
            else:
                render_template("Error.html",
                                message="Files uploaded are not supported...")
            destination = "/".join([target, form.category.data, filename])
            imageslist.append(filename)
            print("Accept incoming file:", filename)
            print("Save it to:", destination)
            upload.save(destination)
            print("printing imageslist")
            for x in imageslist:
                print(x)

        a = form.material_Care.data
        formdata = {
            'Category': form.category.data,
            'Seller': sellerinfo['username'],
            'Type': form.typeofitem.data,
            'Image': imageslist,
            'Brand': form.brand.data,
            'Short Description': form.short_Description.data,
            'Description': form.description.data,
            'Mrp': form.mrp.data,
            'Discount': form.discount.data,
            'Price':
            (form.mrp.data - ((form.mrp.data * form.discount.data) / 100)),
            'Size': form.sizenqty.data,
            'Product Details': form.productDetails.data,
            'Material & Care': [a, 0],
            'Tags': form.tags.data,
            'SellerId': sellerid
        }
        if (itemid == 0):
            mongo.db.items.insert(formdata)
            return 1
        else:
            mongo.db.items.update({"_id": itemid}, formdata)
            print("data updated")
            return 1

    else:
        return 0
Example #38
0
def account_createtable():
    tablename = request.form.get("tablenumber")
    tableid = DB.add_table(tablename, current_user.get_id())
    new_url = BH.shorten_url(config.base_url + "newrequest/" + tableid)
    DB.update_table(tableid, new_url)
    return redirect(url_for("account"))
Example #39
0
def account():
    tables = DB.get_tables(current_user.get_id())
    return render_template("account.html", tables=tables)
Example #40
0
 def decorated_view(*args, **kwargs):
     logger.info("reviewer access attempt by %s" % current_user.get_id())
     if not current_user.is_knowl_reviewer():
         return flask.abort(403)  # acess denied
     return fn(*args, **kwargs)
def fetchCandidateExperiences():
    try:
        database = psycopg2.connect(user = "******", password = "******", host= os.getenv('DATABASE_IP', "172.17.0.1") , port = "5432", database = "dauhmnvct04jp4")
        if database:
            cursor = database.cursor()
            response = dict()

            if current_user.is_authenticated():

                currentUserId = current_user.get_id()

                if currentUserId:
                    cursor.execute(f"""SELECT role_title, description, start_date, end_date, present, is_deleted FROM public."Candidate Experiences" WHERE user_id={currentUserId} AND is_deleted={False}""")
                    queryResult = cursor.fetchall()

                    if len(queryResult) != 0:
                        if len(queryResult) == 1:
                            experienceId1 = queryResult[0][0]
                            cursor.execute(f"""SELECT role_title, description, start_date, end_date, present, is_deleted FROM public."Candidate Experiences" WHERE experience_id={experienceId1}""")
                            queryResultFromExperienceId = cursor.fetchall()
                            constructExperienceResponse(response, queryResultFromExperienceId[0], '1')

                            cursor.execute(f"""SELECT role_title, description, start_date, end_date, present, is_deleted FROM public."Candidate Experiences" WHERE user_id={currentUserId} AND is_deleted={True}""")
                            queryResultForDeletedLinks = cursor.fetchall()
                            constructExperienceResponse(response, queryResultForDeletedLinks[0], '2')
                            constructExperienceResponse(response, queryResultForDeletedLinks[1], '3')
                            constructExperienceResponse(response, queryResultForDeletedLinks[2], '4')
                            constructExperienceResponse(response, queryResultForDeletedLinks[3], '5')
                        elif len(queryResult) == 2:
                            experienceId1 = queryResult[0][0]
                            experienceId2 = queryResult[1][0]
                            cursor.execute(f"""SELECT role_title, description, start_date, end_date, present, is_deleted FROM public."Candidate Experiences" WHERE experience_id={experienceId1} OR experience_id={experienceId2}""")
                            queryResultFromExperienceId = cursor.fetchall()
                            constructExperienceResponse(response, queryResultFromExperienceId[0], '1')
                            constructExperienceResponse(response, queryResultFromExperienceId[1], '2')

                            cursor.execute(f"""SELECT role_title, description, start_date, end_date, present, is_deleted FROM public."Candidate Experiences" WHERE user_id={currentUserId} AND is_deleted={True}""")
                            queryResultForDeletedLinks = cursor.fetchall()
                            constructExperienceResponse(response, queryResultForDeletedLinks[0], '3')
                            constructExperienceResponse(response, queryResultForDeletedLinks[1], '4')
                            constructExperienceResponse(response, queryResultForDeletedLinks[2], '5')
                        elif len(queryResult) == 3:
                            experienceId1 = queryResult[0][0]
                            experienceId2 = queryResult[1][0]
                            experienceId3 = queryResult[2][0]
                            cursor.execute(f"""SELECT role_title, description, start_date, end_date, present, is_deleted FROM public."Candidate Experiences" WHERE experience_id={experienceId1} OR experience_id={experienceId2} OR experience_id={experienceId3}""")
                            queryResultFromExperienceId = cursor.fetchall()
                            constructExperienceResponse(response, queryResultFromExperienceId[0], '1')
                            constructExperienceResponse(response, queryResultFromExperienceId[1], '2')
                            constructExperienceResponse(response, queryResultFromExperienceId[2], '3')

                            cursor.execute(f"""SELECT role_title, description, start_date, end_date, present, is_deleted FROM public."Candidate Experiences" WHERE user_id={currentUserId} AND is_deleted={True}""")
                            queryResultForDeletedLinks = cursor.fetchall()
                            constructExperienceResponse(response, queryResultForDeletedLinks[0], '4')
                            constructExperienceResponse(response, queryResultForDeletedLinks[1], '5')
                        elif len(queryResult) == 4:
                            
                            experienceId1 = queryResult[0][0]
                            experienceId2 = queryResult[1][0]
                            experienceId3 = queryResult[2][0]
                            experienceId4 = queryResult[3][0]
                            cursor.execute(f"""SELECT role_title, description, start_date, end_date, present, is_deleted FROM public."Candidate Experiences" WHERE experience_id={experienceId1} OR experience_id={experienceId2} OR experience_id={experienceId3} OR experience_id={experienceId4}""")
                            queryResultFromExperienceId = cursor.fetchall()
                            
                            constructExperienceResponse(response, queryResultFromExperienceId[0], '1')
                            constructExperienceResponse(response, queryResultFromExperienceId[1], '2')
                            constructExperienceResponse(response, queryResultFromExperienceId[2], '3')
                            constructExperienceResponse(response, queryResultFromExperienceId[3], '4')

                            cursor.execute(f"""SELECT role_title, description, start_date, end_date, present, is_deleted FROM public."Candidate Experiences" WHERE user_id={currentUserId} AND is_deleted={True}""")
                            queryResultForDeletedLinks = cursor.fetchall()
                            constructExperienceResponse(response, queryResultForDeletedLinks[0], '5')
                        else:
                            constructExperienceResponse(response, queryResult[0], '1')
                            constructExperienceResponse(response, queryResult[1], '2')
                            constructExperienceResponse(response, queryResult[2], '3')
                            constructExperienceResponse(response, queryResult[3], '4')
                            constructExperienceResponse(response, queryResult[4], '5')

                    else:
                        error = "Experiences No Longer Exist!"
                        response['error'] = error
                        raise Exception(response)
        else:
            error = "Connection To Database Failed!"
            response['error'] = error
            raise Exception(response)
    except Exception:
        return response, 400
    
    return response
Example #42
0
def home():
    message = f'Hello {current_user.get_id()}, from hawk-web!'
    print(message)
    return render_template('index.html', userid=current_user.get_id())
def updateCandidateProfileInfo():
    try:
        database = psycopg2.connect(
            user="******",
            password=
            "******",
            host=os.getenv('DATABASE_IP', "172.17.0.1"),
            port="5432",
            database="dauhmnvct04jp4")
        if database:
            cursor = database.cursor()
            response = dict()
            data = request.get_json()

            if current_user.is_authenticated():

                candidateSchool = data['candidate_school']
                candidateHighestLevelOfEducation = data[
                    'candidate_highest_level_of_education']
                candidateDescription = data['candidate_description']
                candidateCurrentPosition = data['candidate_current_position']

                nameOfInterest1 = data['name_of_interest_1']
                isDeleted1 = data['is_deleted_1']
                nameOfInterest2 = data['name_of_interest_2']
                isDeleted2 = data['is_deleted_2']
                nameOfInterest3 = data['name_of_interest_3']
                isDeleted3 = data['is_deleted_3']

                currentUserId = current_user.get_id()

                if currentUserId:
                    cursor.execute(
                        f"""SELECT interest_id FROM public."Candidate Interests" WHERE user_id = '{currentUserId}'"""
                    )
                    queryResult = cursor.fetchall()

                    cursor.execute(
                        f"""UPDATE public."Candidate Information" SET user_id={currentUserId}, candidate_school='{candidateSchool}', candidate_highest_level_of_education='{candidateHighestLevelOfEducation}', candidate_description='{candidateDescription}', candidate_current_position='{candidateCurrentPosition}', is_candidate_profile_deleted={False} WHERE user_id={currentUserId}"""
                    )
                    database.commit()
                    cursor.execute(
                        f"""UPDATE public."Candidate Interests" SET user_id={currentUserId}, name_of_interest='{nameOfInterest1}', is_deleted={isDeleted1} WHERE interest_id={queryResult[0][0]}"""
                    )
                    database.commit()
                    cursor.execute(
                        f"""UPDATE public."Candidate Interests" SET user_id={currentUserId}, name_of_interest='{nameOfInterest2}', is_deleted={isDeleted2} WHERE interest_id={queryResult[1][0]}"""
                    )
                    database.commit()
                    cursor.execute(
                        f"""UPDATE public."Candidate Interests" SET user_id={currentUserId}, name_of_interest='{nameOfInterest3}', is_deleted={isDeleted3} WHERE interest_id={queryResult[2][0]}"""
                    )
                    database.commit()
                    response['status'] = True
                    response[
                        'status_info'] = 'Candidate Profile Info Updated Successfully'
        else:
            error = "Connection To Database Failed!"
            response['error'] = error
            raise Exception(response)
    except Exception:
        return response, 400

    return response
Example #44
0
 def dispatch_request(self):
     if current_user.is_authenticated:
         return redirect(url_for('user', user_id=current_user.get_id()))
     return render_template('main.html')
Example #45
0
 def on_connect(self):
     self.emit_back('gomoku_status', get_game_status(current_user.get_id()))
     join_room(current_user.get_id())
Example #46
0
def before_request():
    if User.query.get_or_404(current_user.get_id()).role_id == 2:
        pass
    else:
        return 404
Example #47
0
def documents():
    files_meta = UserFiles.query.filter_by(user_id=current_user.get_id()).all()
    return render_template("documents.html",
                           files=files_meta,
                           title='Documents')
Example #48
0
 def find_by_tagName(cls, tagname):
     lowerTagname = tagname.lower(
     )  #checking database for lower case version of argument. Doing it here for same reason as above
     return cls.query.filter_by(tagname=lowerTagname,
                                user_id=current_user.get_id()).first()
Example #49
0
def index():
    if current_user.get_id():
        return current_user.get_id()
    return '首页'
Example #50
0
 def validate_oldPassword(self, oldPassword):
     if not verify_psw(email=current_user.get_id(), psw=oldPassword.data):
         raise ValidationError('The old password is wrong!')
def account():
    tables = DB.get_tables(current_user.get_id())
    return render_template("account.html", createtableform=CreateTableForm(), tables=tables)
Example #52
0
def map():
    if request.args:
        if 'group_id' in request.args:
            if request.args['group_id'] == 0:
                flash('bad choose')
            else:
                events = []
                for event in geodb.get_events_by_group_id(
                        request.args['group_id']):
                    n_ev = {}
                    for key, value in event.items():
                        if key != 'time' and key != 'grp':
                            n_ev[key] = value
                    events.append(n_ev)
                return render_template(
                    'map.html',
                    city='moscow',
                    loggedin=current_user,
                    groups=geodb.get_user_groups(user_id=current_user.get_id(
                    ) if current_user.is_authenticated() else None),
                    events=geodb.get_events_by_group_id(
                        request.args['group_id']))
        elif 'show_media' in request.args and 'event_id' in request.args:
            if request.args['show_media'] == 'Показать медиа':
                print('show')
                media = geodb.get_media_by_event_id(request.args['event_id'])
                event = geodb.get_event_by_id(request.args['event_id'])
                media_path = current_app.config['MEDIA_PATH']
                main, media_folder = os.path.split(media_path)
                photos = []
                videos = []
                for m in media:
                    print('here')
                    if m['type'] == 'photo':
                        photos.append(os.path.join(media_folder, m['path']))
                        print(m['path'])
                    elif m['type'] == 'video':
                        _, ext = os.path.splitext(m['path'])
                        videos.append({
                            'path':
                            os.path.join(media_folder, m['path']),
                            'ext':
                            ext[1:]
                        })
                    else:
                        pass
                return render_template(
                    'map.html',
                    city='moscow',
                    loggedin=current_user,
                    groups=geodb.get_user_groups(user_id=current_user.get_id(
                    ) if current_user.is_authenticated() else None),
                    events=geodb.get_events_by_group_id(event['grp']),
                    photos=photos,
                    videos=videos,
                    event_name=event['name'],
                    media_path=main,
                )

    return render_template(
        'map.html',
        city='moscow',
        loggedin=current_user,
        groups=geodb.get_user_groups(user_id=current_user.get_id(
        ) if current_user.is_authenticated() else None))
Example #53
0
def mark_note_read(note_id):
    if NoteRead.find_or_create(current_user.get_id(), note_id):
        return tolerant_jsonify({'status': 'created'}, status=201)
    else:
        raise BadRequestError(f'Failed to mark note {note_id} as read by user {current_user.get_uid()}')
Example #54
0
 def decorated_view(*args, **kwargs):
     logger.info("admin access attempt by %s" % current_user.get_id())
     if not current_user.is_admin:
         return flask.abort(403)  # access denied
     return fn(*args, **kwargs)
Example #55
0
def new_log():
    form = NewLogForm()

    if form.validate_on_submit():

        # Compute profit loss approximation
        buy_price = round(form.buy_price.data, 2) * 100
        sell_price = round(form.sell_price.data, 2) * 100
        quantity = form.quantity.data
        # MAY NEED TO IMPROVE THIS FORMULA
        profit_loss = int(quantity * 100 * (sell_price - buy_price))

        # Log the trade
        log = Trades(stock_name=form.stock_name.data.upper(),
                     buy_price=buy_price,
                     sell_price=sell_price,
                     quantity=quantity,
                     profit_loss=profit_loss,
                     sell_type=form.sell_type.data,
                     author=current_user)

        # Add the log, commit to database and update user
        db.session.add(log)
        db.session.commit()
        flash("Your log has been created!", 'success')

        return redirect(url_for('index'))

    # Total trades by user
    total_trades = Trades.query.filter_by(
        user_id=current_user.get_id()).count()

    trade_date_vals = []

    # Compute net profit of current users
    net_profit = 0
    pl_vals = []

    pl_query = Trades.query.filter_by(user_id=current_user.get_id())\
                           .with_entities(Trades.created_at, Trades.profit_loss)

    for query in pl_query:
        pl = query[1]
        net_profit += pl
        pl_vals.append(float(pl))
        trade_date_vals.append(query[0])

    # df = pd.DataFrame(dict(dates=trade_date_vals, profit_loss=pl_vals))

    net_profit = round(net_profit / 100., 2)

    # Next trade ML prediction
    trade_pred, monthly_pred = ml_prediction_sidebar_pipeline(
        trade_date_vals, pl_vals)

    # Some AI
    says = ai_says(pl_vals, total_trades)

    return render_template("create_log.html",
                           title="New Log",
                           form=form,
                           legend="New Log",
                           total_trades=total_trades,
                           net_profit=net_profit,
                           ai_says=says,
                           next_trade_pred=trade_pred,
                           next_monthly_pred=monthly_pred)
def mark_appointment_read(appointment_id):
    return tolerant_jsonify(AppointmentRead.find_or_create(current_user.get_id(), appointment_id).to_api_json())
def _set_appointment_to_waiting(appointment):
    has_privilege = current_user.is_admin or appointment.dept_code in _dept_codes_with_scheduler_privilege()
    if not has_privilege:
        raise ForbiddenRequestError(f'You are unauthorized to manage appointment {appointment.id}.')
    appointment.set_to_waiting(updated_by=current_user.get_id())
Example #58
0
def do_finalise(recid, publication_record=None, force_finalise=False,
                commit_message=None, send_tweet=False, update=False, convert=True,
                send_email=True):
    """
        Creates record SIP for each data record with a link to the associated
        publication.

        :param synchronous: if true then workflow execution and creation is
               waited on, then everything is indexed in one go.
               If False, object creation is asynchronous, however reindexing is not
               performed. This is only really useful for the full migration of
               content.
    """
    print('Finalising record {}'.format(recid))

    hep_submission = get_latest_hepsubmission(publication_recid=recid)

    generated_record_ids = []
    if hep_submission \
        and (force_finalise or hep_submission.coordinator == int(current_user.get_id())):

        submissions = DataSubmission.query.filter_by(
            publication_recid=recid,
            version=hep_submission.version).all()

        version = hep_submission.version

        existing_submissions = {}
        if hep_submission.version > 1 or update:
            # we need to determine which are the existing record ids.
            existing_data_records = get_records_matching_field(
                'related_publication', recid, doc_type=CFG_DATA_TYPE)

            for record in existing_data_records["hits"]["hits"]:

                if "recid" in record["_source"]:
                    existing_submissions[record["_source"]["title"]] = \
                        record["_source"]["recid"]
                    delete_item_from_index(record["_id"],
                                           doc_type=CFG_DATA_TYPE, parent=record["_source"]["related_publication"])

        current_time = "{:%Y-%m-%d %H:%M:%S}".format(datetime.utcnow())

        for submission in submissions:
            finalise_datasubmission(current_time, existing_submissions,
                                    generated_record_ids,
                                    publication_record, recid, submission,
                                    version)

        try:
            record = get_record_by_id(recid)
            # If we have a commit message, then we have a record update.
            # We will store the commit message and also update the
            # last_updated flag for the record.
            record['hepdata_doi'] = hep_submission.doi

            # The last updated date will be the current date (if record not migrated from the old site).
            if hep_submission.coordinator > 1:
                hep_submission.last_updated = datetime.utcnow()

            if commit_message:
                commit_record = RecordVersionCommitMessage(
                    recid=recid,
                    version=version,
                    message=str(commit_message))

                db.session.add(commit_record)

            record['last_updated'] = datetime.strftime(
                hep_submission.last_updated, '%Y-%m-%d %H:%M:%S')
            record['version'] = version

            record.commit()

            hep_submission.inspire_id = record['inspire_id']
            hep_submission.overall_status = "finished"
            db.session.add(hep_submission)

            db.session.commit()

            create_celery_app(current_app)

            # only mint DOIs if not testing.
            if not current_app.config.get('TESTING', False):
                generate_dois_for_submission.delay(inspire_id=hep_submission.inspire_id, version=version)
                log.info("Generated DOIs for ins{0}".format(hep_submission.inspire_id))

            # Reindex everything.
            index_record_ids([recid] + generated_record_ids)
            push_data_keywords(pub_ids=[recid])

            try:
                admin_indexer = AdminIndexer()
                admin_indexer.index_submission(hep_submission)
            except ConnectionTimeout as ct:
                log.error('Unable to add ins{0} to admin index.\n{1}'.format(hep_submission.inspire_id, ct))

            if send_email:
                send_finalised_email(hep_submission)

            if convert:
                for file_format in ['yaml', 'csv', 'yoda', 'root']:
                    convert_and_store.delay(hep_submission.inspire_id, file_format, force=True)

            if send_tweet:
                site_url = current_app.config.get('SITE_URL', 'https://www.hepdata.net')
                tweet(record.get('title'), record.get('collaborations'),
                      site_url + '/record/ins{0}'.format(record.get('inspire_id')), version)

            return json.dumps({"success": True, "recid": recid,
                               "data_count": len(submissions),
                               "generated_records": generated_record_ids})

        except NoResultFound:
            print('No record found to update. Which is super strange.')

    else:
        return json.dumps(
            {"success": False, "recid": recid,
             "errors": ["You do not have permission to finalise this "
                        "submission. Only coordinators can do that."]})
Example #59
0
def listUserData():
    r = {'userid': current_user.get_id()}
    return r
Example #60
0
def election():
    verify_vote_form = None
    id = request.args.get("id")
    election = Election.query.filter_by(id=id).first()
    if election == None:
        flash('Election not found', "danger")
        return redirect(url_for('home'))
    organizer = User.query.filter_by(id=election.organizer_id).first()
    candidates = db.session.query(Candidate, User).filter_by(
        election_id=election.id).join(User,
                                      User.id == Candidate.user_id).all()
    voters = db.session.query(Voter,
                              User).filter_by(election_id=election.id).join(
                                  User, User.id == Voter.user_id).all()
    vms = VotingMachine.query.filter_by(status=True).all()
    if (vms == []):
        flash("No voting machines online", "danger")
        return redirect(url_for('home'))
    vm = random.choice(vms)
    voting_link = "#"
    if vm != None:
        voting_link = "http://localhost:" + str(vm.port) + "/vote/"
    else:
        flash("No voting machines online", "danger")
        return redirect(url_for('home'))
    ciphertexts = defaultdict(lambda: 1)
    nonces = defaultdict(lambda: 1)
    tally = defaultdict(lambda: 1)
    candidate_dict = []
    winners = []
    num_votes = 0
    user_voted = None
    percent_verified = 0
    open_form = OpenElectionForm()
    close_form = CloseElectionForm()
    verified_vote_form = None
    form_type = request.form.get('type')
    if form_type == "open" and open_form.validate_on_submit():
        election = Election.query.filter_by(id=election.id).filter_by(
            organizer_id=current_user.get_id()).filter_by(
                started=False).filter_by(ended=False).first()
        if election != None:
            election.started = True
            db.session.add(election)
            db.session.commit()
            flash("Election is now open", "success")

    if (form_type == "close"
            and close_form.validate_on_submit()) or election.ended:
        closing = False
        lam = lcm(
            int(election.private_key_p) - 1,
            int(election.private_key_q) - 1)
        if form_type == "close" and close_form.validate_on_submit():
            closing = True
            election = Election.query.filter_by(id=election.id).filter_by(
                organizer_id=current_user.get_id()).first()
        if election != None:
            data_dict = {
                'nonce_product': defaultdict(lambda: 1),
                'votes': defaultdict(dict)
            }
            data_dict = get_all_votes(election)
            nonces = defaultdict(lambda: 1)
            ciphertexts = data_dict['votes']
            tally = defaultdict(lambda: 0)
            public_key = paillier.PaillierPublicKey(int(election.public_key))
            private_key = paillier.PaillierPrivateKey(
                public_key, int(election.private_key_p),
                int(election.private_key_q))

            for candidate in candidates:
                for fingerprint in data_dict['votes']:
                    tally[candidate.Candidate.id] += paillier.EncryptedNumber(
                        public_key,
                        int(data_dict['votes'][fingerprint][str(
                            candidate.Candidate.id)]))
                if closing:
                    candidate.Candidate.votes = private_key.decrypt(
                        tally[candidate.Candidate.id])
                    db.session.add(candidate.Candidate)
                nonces[candidate.Candidate.id] = compute_nonce(
                    candidate.Candidate.votes,
                    tally[candidate.Candidate.id].ciphertext(False),
                    int(election.public_key),
                    int(election.public_key) + 1, lam)
            if closing:
                election.ended = True
                db.session.add(election)
                flash("Election is now closed", "success")
            db.session.commit()
            verify_vote_form = VerifyVoteForm()
            if form_type == "verify" and verify_vote_form.validate_on_submit():
                temp_election_id = int(request.form.get("election"))
                temp_user_id = int(request.form.get("user"))
                temp_voter_id = int(request.form.get("voter"))
                temp_auth_token = request.form.get("authentication_token")
                temp_voter = Voter.query.filter_by(id=temp_voter_id).filter_by(
                    election_id=temp_election_id).filter_by(
                        user_id=temp_user_id).filter_by(
                            authentication_token=temp_auth_token).filter_by(
                                voted=True).filter_by(verified=False).first()
                if (temp_voter != None):
                    temp_voter.verified = True
                    if request.form.get("vote_exists"):
                        temp_voter.vote_exists = True
                    db.session.add(temp_voter)
                    db.session.commit()
            user_voted = Voter.query.filter_by(
                election_id=election.id).filter_by(voted=True).filter_by(
                    user_id=current_user.id).first()
            if (user_voted != None and user_voted.verified == False):
                flash("Please verify if you see your vote", "info")
            num_votes = 0
            max_votes = 0
            for candidate in candidates:
                num_votes += candidate.Candidate.votes
                if candidate.Candidate.votes > max_votes:
                    max_votes = candidate.Candidate.votes
            for candidate in candidates:
                if candidate.Candidate.votes == max_votes:
                    winners.append(candidates)
            voted_voters = Voter.query.filter_by(
                election_id=election.id).filter_by(voted=True).all()
            ax = 0
            max = num_votes
            for voter in voted_voters:
                if voter.verified == True and voter.vote_exists == True:
                    ax += 1
            percent_verified = ax * 100 / max
            if (num_votes != len(voted_voters)):
                flash("Warning: More votes received than expected", "danger")
            nonces = nonces_to_dict(nonces)
            tally = encrypted_numbers_to_dict(tally)
            candidate_dict = candidates_to_dict(candidates)
    return render_template('election.html',
                           election=election,
                           organizer=organizer,
                           candidates=candidates,
                           voters=voters,
                           open_form=open_form,
                           close_form=close_form,
                           voting_link=voting_link,
                           votes=ciphertexts,
                           nonces=nonces,
                           tally=tally,
                           candidate_dict=candidate_dict,
                           winners=winners,
                           num_votes=num_votes,
                           user_voted=user_voted,
                           percent_verified=percent_verified,
                           verify_vote_form=verify_vote_form)