Esempio n. 1
0
 def get(self, method, lookup, rdb):
     ''' Lookup the user by the uid '''
     if method == 'uid':
         uid = lookup
     elif method == 'username':
         uid = self.getUID(lookup, rdb)
     results = r.table('users').get(uid).run(rdb)
     data = results
     if data:
         self.email = results['email']
         self.uid = results['id']
         self.username = results['username']
         self.status = results['status']
         self.company = results['company']
         self.contact = results['contact']
         self.acttype = results['acttype']
         self.stripeid = results['stripeid']
         self.stripe = results['stripe']
         self.subplans = results['subplans']
         self.payments = results['payments']
         self.subscription = results['subscription']
         self.creation_time = results['creation_time']
         self.confirmed = results['confirmed']
         ## Identify number of monitors and reactions
         monitor = Monitor()
         reaction = Reaction()
         self.monitorCount = monitor.count(self.uid, rdb)
         self.reactionCount = reaction.count(self.uid, rdb)
         return self
     else:
         return None
Esempio n. 2
0
 def test_getRID_works(self):
     # Ensure that getRID() works as expected.
     timestamp = str(datetime.datetime.now())
     new_timestamp = timestamp.replace(":", "")
     with self.client:
         self.client.post(
             '/login',
             data=dict(email="*****@*****.**", password="******"),
             follow_redirects=True
         )
         self.client.post(
             '/dashboard/reactions/enotify',
             data=dict(name=new_timestamp, trigger=1,
                       frequency=1, email="*****@*****.**",
                       send_true=True),
             follow_redirects=True
         )
         user = User()
         user_id = user.getUID('*****@*****.**', g.rdb_conn)
         get_reaction_id = Reaction()
         response = get_reaction_id.getRID(
             new_timestamp+':'+user_id, g.rdb_conn)
         results = r.table('reactions').filter(
             {'name': new_timestamp}).run(g.rdb_conn)
         for result in results:
             reaction_id = result['id']
             break
         self.assertEqual(response, reaction_id)
Esempio n. 3
0
 def test_getRID_works(self):
     # Ensure that getRID() works as expected.
     timestamp = str(datetime.datetime.now())
     new_timestamp = timestamp.replace(":", "")
     with self.client:
         self.client.post(
             '/login',
             data=dict(email="*****@*****.**", password="******"),
             follow_redirects=True
         )
         self.client.post(
             '/dashboard/reactions/enotify',
             data=dict(name=new_timestamp, trigger=1,
                       frequency=1, email="*****@*****.**",
                       send_true=True),
             follow_redirects=True
         )
         user = User()
         user_id = user.getUID('*****@*****.**', g.rdb_conn)
         get_reaction_id = Reaction()
         response = get_reaction_id.getRID(
             new_timestamp+':'+user_id, g.rdb_conn)
         results = r.table('reactions').filter(
             {'name': new_timestamp}).run(g.rdb_conn)
         for result in results:
             reaction_id = result['id']
             break
         self.assertEqual(response, reaction_id)
Esempio n. 4
0
def delreaction_page(rid):
    '''
    Dashboard Delete Domains:
    This will delete a domain based on url parameters
    '''
    verify = verifyLogin(app.config['SECRET_KEY'],
                         app.config['COOKIE_TIMEOUT'], request.cookies)
    if verify:
        user = User()
        user.get('uid', verify, g.rdb_conn)
        if user.status != "active":
            pass
        else:

            appliedcount = 0
            results = r.table('monitors').filter({
                'uid': user.uid
            }).run(g.rdb_conn)
            for x in results:
                if rid in x['data']['reactions']:
                    appliedcount = appliedcount + 1

            if appliedcount < 1:
                # Delete the Reaction
                reaction = Reaction(rid)
                result = reaction.deleteReaction(user.uid, rid, g.rdb_conn)
                if result:
                    flash('Reaction was successfully deleted', 'success')
                else:
                    flash('Reaction was not deleted', 'danger')
            else:
                flash(
                    'You must first detach this reaction from all monitors before deleting',
                    'danger')
    return redirect(url_for('member.dashboard_page'))
Esempio n. 5
0
def delreaction_page(rid):
    '''
    Dashboard Delete Domains:
    This will delete a domain based on url parameters
    '''
    verify = verifyLogin(
        app.config['SECRET_KEY'], app.config['COOKIE_TIMEOUT'], request.cookies)
    if verify:
        user = User()
        user.get('uid', verify, g.rdb_conn)
        if user.status != "active":
            pass
        else:

            appliedcount = 0
            results = r.table('monitors').filter(
                {'uid': user.uid}).run(g.rdb_conn)
            for x in results:
                if rid in x['data']['reactions']:
                    appliedcount = appliedcount + 1

            if appliedcount < 1:
                # Delete the Reaction
                reaction = Reaction(rid)
                result = reaction.deleteReaction(user.uid, rid, g.rdb_conn)
                if result:
                    flash('Reaction was successfully deleted.', 'success')
                else:
                    flash('Reaction was not deleted.', 'danger')
            else:
                flash('You must first detach this reaction \
                      from all monitors before deleting.', 'danger')
    return redirect(url_for('member.dashboard_page'))
Esempio n. 6
0
 def get(self, method, lookup, rdb):
     ''' Lookup the user by the uid '''
     if method == 'uid':
         uid = lookup
     elif method == 'username':
         uid = self.getUID(lookup, rdb)
     results = r.table('users').get(uid).run(rdb)
     data = results
     if data:
         self.email = results['email']
         self.uid = results['id']
         self.username = results['username']
         self.status = results['status']
         self.company = results['company']
         self.contact = results['contact']
         self.acttype = results['acttype']
         self.stripeid = results['stripeid']
         self.stripe = results['stripe']
         self.subplans = results['subplans']
         self.payments = results['payments']
         self.subscription = results['subscription']
         self.creation_time = results['creation_time']
         self.confirmed = results['confirmed']
         ## Identify number of monitors and reactions
         monitor = Monitor()
         reaction = Reaction()
         self.monitorCount = monitor.count(self.uid, rdb)
         self.reactionCount = reaction.count(self.uid, rdb)
         return self
     else:
         return None
Esempio n. 7
0
 def get(self, method, lookup, rdb):
     """ Lookup the user by the uid """
     if method == "uid":
         uid = lookup
     elif method == "username":
         uid = self.getUID(lookup, rdb)
     results = r.table("users").get(uid).run(rdb)
     data = results
     if data:
         self.email = results["email"]
         self.uid = results["id"]
         self.username = results["username"]
         self.status = results["status"]
         self.company = results["company"]
         self.contact = results["contact"]
         self.acttype = results["acttype"]
         self.stripeid = results["stripeid"]
         self.stripe = results["stripe"]
         self.subplans = results["subplans"]
         self.payments = results["payments"]
         self.subscription = results["subscription"]
         self.creation_time = results["creation_time"]
         self.confirmed = results["confirmed"]
         ## Identify number of monitors and reactions
         monitor = Monitor()
         reaction = Reaction()
         self.monitorCount = monitor.count(self.uid, rdb)
         self.reactionCount = reaction.count(self.uid, rdb)
         return self
     else:
         return None
Esempio n. 8
0
 def unassign(self):
     if self.assignee is None:
         return
     self.set_status(ReportStatus.NEW)
     self.client.flows[self.assignee.id].remove(self.review_flow)
     self.assignee = None
     self.review_flow = None
     assignReaction = Reaction("✋",
                               click_handler=self.reaction_attempt_assign,
                               once_per_message=False)
     for msg in self._channel_messages:
         if msg[1]:  # Check if message is "assignable"
             asyncio.create_task(assignReaction.register_message(msg[0]))
Esempio n. 9
0
def _parse_reaction(line, all_species, parameters, reactions, tables):
    line_split_arrow = line.split('=>')
    if len(line_split_arrow) != 2:
        raise InvalidLine(
            f"Syntax error on line '{line}': There can only be one reaction per line. In a reaction, "
            f"the reactants and products are separated by the arrow '=>'.")
    left_side = line_split_arrow[0]
    line_split_excl = line_split_arrow[1].split('!')
    if len(line_split_excl) != 2:
        raise InvalidLine(
            f"Syntax error on line '{line}': Each reaction must have its rate specified. The rate "
            f"specification goes after the single exclamation mark '!'. The exclamation mark '!' "
            f"must not be used elsewhere.")
    right_side = line_split_excl[0]
    rate_spec = line_split_excl[1]

    reaction = Reaction(_parse_species(left_side, all_species),
                        _parse_species(right_side, all_species))
    _parse_rate(reaction, rate_spec, tables,
                parameters)  # fills attributes rate_fun and table_name
    reaction.scale(
        parameters)  # # scale the rate function: using the 'ratio' parameter
    reactions.append(reaction)
Esempio n. 10
0
def addreaction_page(rname):
    verify = verifyLogin(
        app.config['SECRET_KEY'], app.config['COOKIE_TIMEOUT'], request.cookies)
    if verify:
        user = User()
        user.config = app.config
        user.get('uid', verify, g.rdb_conn)
        data = startData(user)
        data['active'] = 'dashboard'
        data['url'] = '/dashboard/reactions/' + rname
        tmpl = 'reactions/create.html'
        data['js_bottom'] = ['reactions/base.js']
        # Check Users Status
        if user.status != "active":
            data['url'] = '/dashboard/mod-subscription'
            tmpl = 'member/mod-subscription.html'
        else:

            reform = __import__(
                "reactionforms." + rname, globals(),
                locals(), ['ReactForm'], -1)
            form = reform.ReactForm(request.form)
            if request.method == 'POST':
                if form.validate():
                    reaction = Reaction()
                    reaction.config = app.config
                    reaction.name = form.name.data
                    reaction.trigger = form.trigger.data
                    reaction.frequency = form.frequency.data
                    reaction.uid = user.uid
                    reaction.rtype = rname
                    tmpdata = {}
                    for item in form.__iter__():
                        tmpdata[item.name] = item.data
                    reaction.data = tmpdata

                    if reaction.count(user.uid, g.rdb_conn) < data['rlimit']:
                        results = reaction.createReaction(g.rdb_conn)
                    else:
                        results = "toomany"

                    if results == "exists":
                        print("/dashboard/reactions/{0} - \
                            Reaction creation failed: exists".format(rname))
                        flash('{0} seems to already exist. Try using a \
                              different name.'.format(reaction.name), 'danger')
                    elif results == "edit noexists":
                        print("/dashboard/reactions/{0} - Reaction \
                              edit failed: doesn't exist".format(rname))
                        flash('{0} cannot be edited as it does not \
                              exist.'.format(reaction.name), 'danger')
                    elif results == "edit true":
                        print("/dashboard/reactions/{0} - \
                              Reaction edit successful".format(rname))
                        flash('Reaction successfully edited: {0}.'.format(
                            reaction.name), 'success')
                    elif results == "edit failed":
                        print("/dashboard/reactions/{0} - \
                              Reaction edit failed: unknown".format(rname))
                        flash('Reaction not successfully edited: {0}.'.format(
                            reaction.name), 'danger')
                    elif results == "toomany":
                        print("/dashboard/reactions/{0} - \
                              Reaction creation failed: too many".format(rname))
                        flash('Could not create reaction: \
                              Too many reactions already created.', 'danger')
                    elif results is False:
                        print("/dashboard/reactions/{0} - \
                              Reaction creation failed: unknown".format(rname))
                        flash('Could not create reaction.', 'danger')
                    else:
                        stathat.ez_count(
                            app.config['STATHAT_EZ_KEY'],
                            app.config['ENVNAME'] + ' Reaction Added', 1)
                        print("/dashboard/reactions/{0} - \
                              Reaction creation successful".format(rname))
                        flash('Reaction "{0}" successfully added.'.format(
                            reaction.name), 'success')
                else:
                    print("/dashboard/reactions/{0} - \
                          Reaction creation failed: form invalid".format(rname))
                    flash('Form is not valid.', 'success')

        page = render_template(tmpl, data=data, form=form)
        return page
    else:
        flash('Please Login.', 'warning')
        return redirect(url_for('user.login_page'))
Esempio n. 11
0
def editreact_page(rname, rid):
    ''' This is a generic edit page for reactions '''
    verify = verifyLogin(
        app.config['SECRET_KEY'], app.config['COOKIE_TIMEOUT'], request.cookies)
    if verify:
        user = User()
        user.config = app.config
        user.get('uid', verify, g.rdb_conn)
        data = startData(user)
        data['active'] = 'dashboard'
        data['url'] = '/dashboard/edit-reactions/' + rname + '/' + rid
        tmpl = 'reactions/create.html'
        data['js_bottom'] = ['reactions/base.js', ]
        data['edit'] = True
        # Check Users Status
        if user.status != "active":
            data['url'] = '/dashboard/mod-subscription'
            tmpl = 'member/mod-subscription.html'
        else:
            reform = __import__(
                "reactionforms." + rname, globals(),
                locals(), ['ReactForm'], -1)
            form = reform.ReactForm(request.form)
            reaction = Reaction()
            reaction.config = app.config
            # If Edit get information
            reaction.get("rid", rid, g.rdb_conn)
            if reaction.uid == user.uid:
                data['reaction'] = {
                    'rid': reaction.rid,
                    'name': reaction.name,
                    'trigger': reaction.trigger,
                    'frequency': reaction.frequency,
                    'uid': reaction.uid,
                    'rtype': reaction.rtype,
                    'data': reaction.data
                }
            data['selects'] = []
            for item in form.__iter__():
                if item.type == "SelectField" or \
                        item.type == "SelectMultipleField":
                    item.default = data['reaction']['data'][item.name]
            tmpl = 'reactions/create.html'
            if request.method == 'POST':
                if form.validate():
                    reaction2 = Reaction()
                    reaction2.config = app.config
                    reaction2.rid = reaction.rid
                    reaction2.name = form.name.data
                    reaction2.trigger = form.trigger.data
                    reaction2.frequency = form.frequency.data
                    reaction2.lastrun = reaction.lastrun
                    reaction2.uid = user.uid
                    reaction2.rtype = reaction.rtype
                    tmpdata = {}
                    for item in form.__iter__():
                        tmpdata[item.name] = item.data
                        if item.type == "SelectField" or\
                                item.type == "SelectMultipleField":
                            item.default = item.data
                    reaction2.data = tmpdata

                    data['reaction'] = {
                        'rid': reaction2.rid,
                        'name': reaction2.name,
                        'trigger': reaction2.trigger,
                        'frequency': reaction2.frequency,
                        'uid': reaction2.uid,
                        'rtype': reaction2.rtype,
                        'data': reaction2.data
                    }
                    if reaction.uid == user.uid:
                        results = reaction2.editReaction(g.rdb_conn)
                    else:
                        results = False
                        print("/dashboard/reactions/{0} - \
                            Reaction edit failed: not owner".format(rname))
                        flash("It doesn't appear that you own this reaction.",
                              'danger')
                    if results == "exists":
                        print("/dashboard/reactions/{0} - \
                              Reaction edit failed: exists".format(rname))
                        flash('This reaction seems to already exist. \
                              Try using a different name.', 'danger')
                    elif results == "edit noexists":
                        print("/dashboard/reactions/{0} - \
                              Reaction edit failed: exists".format(rname))
                        flash('This reaction can not be edited \
                              as it does not exist.', 'danger')
                    elif results == "edit true":
                        print("/dashboard/reactions/{0} - \
                              Reaction edit successful".format(rname))
                        flash('Reaction successfully edited.', 'success')
                    elif results == "edit failed":
                        print("/dashboard/reactions/{0} - \
                              Reaction edit failed: unknown".format(rname))
                        flash('Reaction not successfully edited.', 'danger')
                    elif results is False:
                        print("/dashboard/reactions/{0} - \
                              Reaction edit failed: unknown".format(rname))
                        flash('Could not create reaction.', 'danger')
                    else:
                        stathat.ez_count(
                            app.config['STATHAT_EZ_KEY'],
                            app.config['ENVNAME'] + ' Reaction Added', 1)
                        print("/dashboard/reactions/{0} - \
                              Reaction edit success".format(rname))
                        flash('Reaction "{0}" successfully \
                              added.'.format(reaction2.name), 'danger')
                else:
                    print("/dashboard/reactions/{0} - \
                          Reaction edit failed: form invalid".format(rname))
                    flash('Form is not valid.', 'danger')
        form.process()
        page = render_template(tmpl, data=data, form=form)
        return page
    else:
        flash('Please Login.', 'warning')
        return redirect(url_for('user.login_page'))
Esempio n. 12
0
def addreaction_page(rname):
    verify = verifyLogin(app.config['SECRET_KEY'],
                         app.config['COOKIE_TIMEOUT'], request.cookies)
    if verify:
        user = User()
        user.get('uid', verify, g.rdb_conn)
        data = startData(user)
        data['active'] = 'dashboard'
        data['url'] = '/dashboard/reactions/' + rname
        tmpl = 'reactions/' + rname + '.html'
        data['js_bottom'] = ['reactions/base.js', 'reactions/' + rname + '.js']
        # Check Users Status
        if user.status != "active":
            data['url'] = '/dashboard/mod-subscription'
            tmpl = 'member/mod-subscription.html'
        else:

            reform = __import__("reactionforms." + rname, globals(), locals(),
                                ['ReactForm'], -1)
            form = reform.ReactForm(request.form)
            if request.method == 'POST':
                if form.validate():
                    reaction = Reaction()
                    reaction.name = form.name.data
                    reaction.trigger = form.trigger.data
                    reaction.frequency = form.frequency.data
                    reaction.uid = user.uid
                    reaction.rtype = rname
                    tmpdata = {}
                    for item in form.__iter__():
                        tmpdata[item.name] = item.data
                    reaction.data = tmpdata

                    if reaction.count(user.uid, g.rdb_conn) < data['rlimit']:
                        results = reaction.createReaction(g.rdb_conn)
                    else:
                        results = "toomany"

                    if results == "exists":
                        data[
                            'msg'] = "This reaction seems to already exist, try using a different name: %s" % reaction.name
                        print(
                            "/dashboard/reactions/%s - Reaction creation failed: exists"
                        ) % rname
                        data['error'] = True
                    elif results == "edit noexists":
                        data[
                            'msg'] = "This reaction can not be edited as it does not exist: %s" % reaction.name
                        print(
                            "/dashboard/reactions/%s - Reaction edit failed: doesnt exist"
                        ) % rname
                        data['error'] = True
                    elif results == "edit true":
                        data[
                            'msg'] = "Reaction successfully edited: %s" % reaction.name
                        print(
                            "/dashboard/reactions/%s - Reaction edit successful"
                        ) % rname
                        data['error'] = False
                    elif results == "edit false":
                        data[
                            'msg'] = "Reaction not successfully edited: %s" % reaction.name
                        print(
                            "/dashboard/reactions/%s - Reaction edit failed: unknown"
                        ) % rname
                        data['error'] = True
                    elif results == "toomany":
                        data[
                            'msg'] = "Could not create reaction: Too many reactions already created [%d]" % data[
                                'rlimit']
                        print(
                            "/dashboard/reactions/%s - Reaction creation failed: too many"
                        ) % rname
                        data['error'] = True
                    elif results is False:
                        data['msg'] = "Could not create reaction"
                        print(
                            "/dashboard/reactions/%s - Reaction creation failed: unknown"
                        ) % rname
                        data['error'] = True
                    else:
                        stathat.ez_count(
                            app.config['STATHAT_EZ_KEY'],
                            app.config['ENVNAME'] + ' Reaction Added', 1)
                        data[
                            'msg'] = 'Reaction "%s" successfully added' % reaction.name
                        print(
                            "/dashboard/reactions/%s - Reaction creation successful"
                        ) % rname
                        data['error'] = False
                else:
                    data['msg'] = "Form is not valid"
                    print(
                        "/dashboard/reactions/%s - Reaction creation failed: form invalid"
                    ) % rname
                    data['error'] = True

        page = render_template(tmpl, data=data, form=form)
        return page
    else:
        return redirect(url_for('user.login_page'))
Esempio n. 13
0
def editreact_page(rname, rid):
  ''' This is a generic edit page for reactions '''
  verify = verifyLogin(app.config['SECRET_KEY'], app.config['COOKIE_TIMEOUT'], request.cookies)
  if verify:
    user = User()
    user.get('uid', verify, g.rdb_conn)
    data = startData(user)
    data['active'] = 'dashboard'
    data['url'] = '/dashboard/edit-reactions/' + rname + '/' + rid
    tmpl = 'reactions/index.html'
    data['js_bottom'] = [ 'reactions/base.js', 'reactions/' + rname + '.js' ]
    data['edit'] = True
    ## Check Users Status
    if user.status != "active":
      data['url'] = '/dashboard/mod-subscription'
      tmpl = 'mod-subscription.html'
    else:
      reform = __import__("reactionforms." + rname, globals(), locals(), ['ReactForm'], -1)
      form = reform.ReactForm(request.form)
      reaction = Reaction()
      ## If Edit get information
      reaction.get("rid", rid, g.rdb_conn)
      if reaction.uid == user.uid:
        data['reaction'] = {
          'rid': reaction.rid,
          'name': reaction.name,
          'trigger': reaction.trigger,
          'frequency': reaction.frequency,
          'uid': reaction.uid,
          'rtype': reaction.rtype,
          'data': reaction.data
        }
      data['selects'] = []
      for item in form.__iter__():
        if item.type == "SelectField" or item.type == "SelectMultipleField":
          item.default = data['reaction']['data'][item.name]
      tmpl = 'reactions/' + rname + '.html'
      if request.method == 'POST':
        if form.validate():
          reaction2 = Reaction()
          reaction2.rid = reaction.rid
          reaction2.name = form.name.data
          reaction2.trigger = form.trigger.data
          reaction2.frequency = form.frequency.data
          reaction2.uid = user.uid
          reaction2.rtype = reaction.rtype
          tmpdata = {}
          for item in form.__iter__():
            tmpdata[item.name] = item.data
            if item.type == "SelectField" or item.type == "SelectMultipleField":
              item.default = item.data
          reaction2.data = tmpdata

          data['reaction'] = {
            'rid': reaction2.rid,
            'name': reaction2.name,
            'trigger': reaction2.trigger,
            'frequency': reaction2.frequency,
            'uid': reaction2.uid,
            'rtype': reaction2.rtype,
            'data': reaction2.data
          }
          if reaction.uid == user.uid:
            results = reaction2.editReaction(g.rdb_conn)
          else:
            results = False
            data['msg'] = "I Doesn't appear that you own this reaction"
            print("/dashboard/reactions/%s - Reaction edit failed: not owner") % rname
            data['error'] = True
          if results == "exists":
            data['msg'] = "This reaction seems to already exist, try using a different name: %s" % reaction2.name
            print("/dashboard/reactions/%s - Reaction edit failed: exists") % rname
            data['error'] = True
          elif results == "edit noexists":
            data['msg'] = "This reaction can not be edited as it does not exist: %s" % reaction2.name
            print("/dashboard/reactions/%s - Reaction edit failed: exists") % rname
            data['error'] = True
          elif results == "edit true":
            data['msg'] = "Reaction successfully edited: %s" % reaction2.name
            print("/dashboard/reactions/%s - Reaction edit successful") % rname
            data['error'] = False
          elif results == "edit false":
            data['msg'] = "Reaction not successfully edited: %s" % reaction2.name
            print("/dashboard/reactions/%s - Reaction edit failed: unknown") % rname
            data['error'] = True 
          elif results == False:
            data['msg'] = "Could not create reaction"
            print("/dashboard/reactions/%s - Reaction edit failed: unknown") % rname
            data['error'] = True
          else:
            stathat.ez_count(app.config['STATHAT_EZ_KEY'], app.config['ENVNAME'] + ' Reaction Added', 1)
            data['msg'] = 'Reaction "%s" successfully added' % reaction2.name
            print("/dashboard/reactions/%s - Reaction edit success") % rname
            data['error'] = False
        else:
          data['msg'] = "Form is not valid"
          print("/dashboard/reactions/%s - Reaction edit failed: form invalid") % rname
          data['error'] = True
    form.process()
    page = render_template(tmpl, data=data, form=form)
    return page
  else:
    return redirect(url_for('login_page')) 
Esempio n. 14
0
def addreaction_page(rname):
    verify = verifyLogin(
        app.config['SECRET_KEY'], app.config['COOKIE_TIMEOUT'], request.cookies)
    if verify:
        user = User()
        user.get('uid', verify, g.rdb_conn)
        data = startData(user)
        data['active'] = 'dashboard'
        data['url'] = '/dashboard/reactions/' + rname
        tmpl = 'reactions/' + rname + '.html'
        data['js_bottom'] = ['reactions/base.js', 'reactions/' + rname + '.js']
        # Check Users Status
        if user.status != "active":
            data['url'] = '/dashboard/mod-subscription'
            tmpl = 'member/mod-subscription.html'
        else:

            reform = __import__(
                "reactionforms." + rname, globals(),
                locals(), ['ReactForm'], -1)
            form = reform.ReactForm(request.form)
            if request.method == 'POST':
                if form.validate():
                    reaction = Reaction()
                    reaction.name = form.name.data
                    reaction.trigger = form.trigger.data
                    reaction.frequency = form.frequency.data
                    reaction.uid = user.uid
                    reaction.rtype = rname
                    tmpdata = {}
                    for item in form.__iter__():
                        tmpdata[item.name] = item.data
                    reaction.data = tmpdata

                    if reaction.count(user.uid, g.rdb_conn) < data['rlimit']:
                        results = reaction.createReaction(g.rdb_conn)
                    else:
                        results = "toomany"

                    if results == "exists":
                        print("/dashboard/reactions/{0} - \
                            Reaction creation failed: exists".format(rname))
                        flash('{0} seems to already exist. Try using a \
                              different name.'.format(reaction.name), 'danger')
                    elif results == "edit noexists":
                        print("/dashboard/reactions/{0} - Reaction \
                              edit failed: doesn't exist".format(rname))
                        flash('{0} cannot be edited as it does not \
                              exist.'.format(reaction.name), 'danger')
                    elif results == "edit true":
                        print("/dashboard/reactions/{0} - \
                              Reaction edit successful".format(rname))
                        flash('Reaction successfully edited: {0}.'.format(
                            reaction.name), 'success')
                    elif results == "edit failed":
                        print("/dashboard/reactions/{0} - \
                              Reaction edit failed: unknown".format(rname))
                        flash('Reaction not successfully edited: {0}.'.format(
                            reaction.name), 'danger')
                    elif results == "toomany":
                        print("/dashboard/reactions/{0} - \
                              Reaction creation failed: too many".format(rname))
                        flash('Could not create reaction: \
                              Too many reactions already created.', 'danger')
                    elif results is False:
                        print("/dashboard/reactions/{0} - \
                              Reaction creation failed: unknown".format(rname))
                        flash('Could not create reaction.', 'danger')
                    else:
                        stathat.ez_count(
                            app.config['STATHAT_EZ_KEY'],
                            app.config['ENVNAME'] + ' Reaction Added', 1)
                        print("/dashboard/reactions/{0} - \
                              Reaction creation successful".format(rname))
                        flash('Reaction "{0}" successfully added.'.format(
                            reaction.name), 'success')
                else:
                    print("/dashboard/reactions/{0} - \
                          Reaction creation failed: form invalid".format(rname))
                    flash('Form is not valid.', 'success')

        page = render_template(tmpl, data=data, form=form)
        return page
    else:
        flash('Please Login.', 'warning')
        return redirect(url_for('user.login_page'))
Esempio n. 15
0
def addreaction_page(rname):
    verify = verifyLogin(
        app.config['SECRET_KEY'], app.config['COOKIE_TIMEOUT'], request.cookies)
    if verify:
        user = User()
        user.get('uid', verify, g.rdb_conn)
        data = startData(user)
        data['active'] = 'dashboard'
        data['url'] = '/dashboard/reactions/' + rname
        tmpl = 'reactions/' + rname + '.html'
        data['js_bottom'] = ['reactions/base.js', 'reactions/' + rname + '.js']
        # Check Users Status
        if user.status != "active":
            data['url'] = '/dashboard/mod-subscription'
            tmpl = 'member/mod-subscription.html'
        else:

            reform = __import__(
                "reactionforms." + rname, globals(),
                locals(), ['ReactForm'], -1)
            form = reform.ReactForm(request.form)
            if request.method == 'POST':
                if form.validate():
                    reaction = Reaction()
                    reaction.name = form.name.data
                    reaction.trigger = form.trigger.data
                    reaction.frequency = form.frequency.data
                    reaction.uid = user.uid
                    reaction.rtype = rname
                    tmpdata = {}
                    for item in form.__iter__():
                        tmpdata[item.name] = item.data
                    reaction.data = tmpdata

                    if reaction.count(user.uid, g.rdb_conn) < data['rlimit']:
                        results = reaction.createReaction(g.rdb_conn)
                    else:
                        results = "toomany"

                    if results == "exists":
                        data['msg'] = "This reaction seems to already exist, try using a different name: %s" % reaction.name
                        print("/dashboard/reactions/%s - Reaction creation failed: exists") % rname
                        data['error'] = True
                    elif results == "edit noexists":
                        data['msg'] = "This reaction can not be edited as it does not exist: %s" % reaction.name
                        print("/dashboard/reactions/%s - Reaction edit failed: doesnt exist") % rname
                        data['error'] = True
                    elif results == "edit true":
                        data['msg'] = "Reaction successfully edited: %s" % reaction.name
                        print("/dashboard/reactions/%s - Reaction edit successful") % rname
                        data['error'] = False
                    elif results == "edit false":
                        data['msg'] = "Reaction not successfully edited: %s" % reaction.name
                        print("/dashboard/reactions/%s - Reaction edit failed: unknown") % rname
                        data['error'] = True
                    elif results == "toomany":
                        data['msg'] = "Could not create reaction: Too many reactions already created [%d]" % data['rlimit']
                        print("/dashboard/reactions/%s - Reaction creation failed: too many") % rname
                        data['error'] = True
                    elif results is False:
                        data['msg'] = "Could not create reaction"
                        print("/dashboard/reactions/%s - Reaction creation failed: unknown") % rname
                        data['error'] = True
                    else:
                        stathat.ez_count(
                            app.config['STATHAT_EZ_KEY'],
                            app.config['ENVNAME'] + ' Reaction Added', 1)
                        data['msg'] = 'Reaction "%s" successfully added' % reaction.name
                        print("/dashboard/reactions/%s - Reaction creation successful") % rname
                        data['error'] = False
                else:
                    data['msg'] = "Form is not valid"
                    print("/dashboard/reactions/%s - Reaction creation failed: form invalid") % rname
                    data['error'] = True

        page = render_template(tmpl, data=data, form=form)
        return page
    else:
        return redirect(url_for('user.login_page'))
def genReactionScheme(visc, visc2):
    return [
        Reaction('S0 + I <-> S1', k_emmision
                 ),  #excitation (this works if we redefine I as being I/I_sat)
        Reaction('S1 <-> S0',
                 k_emmision),  #emmission - we ignore the emitted photon
        Reaction('S1 <-> T1', 6.6e-1),  #intersystem crossing
        Reaction('T1 <-> S0', 5e-5),  #radiationless deactivation
        Reaction('2T1 <-> T1 + S0', 5e2 / visc2),  #triplet quenching
        Reaction('T1 + S0 <-> 2S0', 5e1 / visc2),  #triplet quenching
        Reaction('2T1 <-> R + X', 6e2 / visc2),  #electron transfer
        Reaction('T1 + S0 <-> R + X', 6e2 / visc2),  #electron transfer
        Reaction('T1 + X <-> S0 + X', 1e3 / visc2,
                 catalysts=['X']),  #quenching by X
        Reaction('T1 + R <-> S0 + R', 1e3 / visc2,
                 catalysts=['R']),  #quenching by R
        Reaction('T1 + O2 <-> S0 + O2',
                 1.56e3 / visc),  #physical quenching by 02
        Reaction('T1 + O2 <-> X + HO2',
                 1.4e2 / visc),  #chemical quenching by 02
        Reaction('T1 + q <-> S0 + q', k10 / visc),  #quencher
        Reaction('T1 + q <-> R + qo', k11 / visc),
        Reaction(
            'R + q <-> S0 + q', k12 / visc
        ),  #should nominally be a reaction with qo, but cannot determine rate constant for this - instead assume that q and qo are in some form of equilibrium and use the relationship to q
        Reaction('X + q <-> S0 + qo', k13 / visc),
        Reaction('X <-> P',
                 k14 / visc),  #postulated permanent bleaching pathway
        Reaction('R <-> P',
                 k15 / visc),  #postulated permanent bleaching pathway
        Reaction(
            'R + O2 <-> S0 + HO2', 5e2 / visc
        ),  #oxidation of R by 02 - rate constant from [kaske & linquist `64]
    ]
Esempio n. 17
0
def editreact_page(rname, rid):
    ''' This is a generic edit page for reactions '''
    verify = verifyLogin(app.config['SECRET_KEY'],
                         app.config['COOKIE_TIMEOUT'], request.cookies)
    if verify:
        user = User()
        user.get('uid', verify, g.rdb_conn)
        data = startData(user)
        data['active'] = 'dashboard'
        data['url'] = '/dashboard/edit-reactions/' + rname + '/' + rid
        tmpl = 'reactions/index.html'
        data['js_bottom'] = ['reactions/base.js', 'reactions/' + rname + '.js']
        data['edit'] = True
        # Check Users Status
        if user.status != "active":
            data['url'] = '/dashboard/mod-subscription'
            tmpl = 'member/mod-subscription.html'
        else:
            reform = __import__("reactionforms." + rname, globals(), locals(),
                                ['ReactForm'], -1)
            form = reform.ReactForm(request.form)
            reaction = Reaction()
            # If Edit get information
            reaction.get("rid", rid, g.rdb_conn)
            if reaction.uid == user.uid:
                data['reaction'] = {
                    'rid': reaction.rid,
                    'name': reaction.name,
                    'trigger': reaction.trigger,
                    'frequency': reaction.frequency,
                    'uid': reaction.uid,
                    'rtype': reaction.rtype,
                    'data': reaction.data
                }
            data['selects'] = []
            for item in form.__iter__():
                if item.type == "SelectField" or \
                        item.type == "SelectMultipleField":
                    item.default = data['reaction']['data'][item.name]
            tmpl = 'reactions/' + rname + '.html'
            if request.method == 'POST':
                if form.validate():
                    reaction2 = Reaction()
                    reaction2.rid = reaction.rid
                    reaction2.name = form.name.data
                    reaction2.trigger = form.trigger.data
                    reaction2.frequency = form.frequency.data
                    reaction2.lastrun = reaction.lastrun
                    reaction2.uid = user.uid
                    reaction2.rtype = reaction.rtype
                    tmpdata = {}
                    for item in form.__iter__():
                        tmpdata[item.name] = item.data
                        if item.type == "SelectField" or\
                                item.type == "SelectMultipleField":
                            item.default = item.data
                    reaction2.data = tmpdata

                    data['reaction'] = {
                        'rid': reaction2.rid,
                        'name': reaction2.name,
                        'trigger': reaction2.trigger,
                        'frequency': reaction2.frequency,
                        'uid': reaction2.uid,
                        'rtype': reaction2.rtype,
                        'data': reaction2.data
                    }
                    if reaction.uid == user.uid:
                        results = reaction2.editReaction(g.rdb_conn)
                    else:
                        results = False
                        data[
                            'msg'] = "It doesn't appear that you own this reaction"
                        print(
                            "/dashboard/reactions/%s - Reaction edit failed: not owner"
                        ) % rname
                        data['error'] = True
                    if results == "exists":
                        data[
                            'msg'] = "This reaction seems to already exist, try using a different name: %s" % reaction2.name
                        print(
                            "/dashboard/reactions/%s - Reaction edit failed: exists"
                        ) % rname
                        data['error'] = True
                    elif results == "edit noexists":
                        data[
                            'msg'] = "This reaction can not be edited as it does not exist: %s" % reaction2.name
                        print(
                            "/dashboard/reactions/%s - Reaction edit failed: exists"
                        ) % rname
                        data['error'] = True
                    elif results == "edit true":
                        data[
                            'msg'] = "Reaction successfully edited: %s" % reaction2.name
                        print(
                            "/dashboard/reactions/%s - Reaction edit successful"
                        ) % rname
                        data['error'] = False
                    elif results == "edit false":
                        data[
                            'msg'] = "Reaction not successfully edited: %s" % reaction2.name
                        print(
                            "/dashboard/reactions/%s - Reaction edit failed: unknown"
                        ) % rname
                        data['error'] = True
                    elif results is False:
                        data['msg'] = "Could not create reaction"
                        print(
                            "/dashboard/reactions/%s - Reaction edit failed: unknown"
                        ) % rname
                        data['error'] = True
                    else:
                        stathat.ez_count(
                            app.config['STATHAT_EZ_KEY'],
                            app.config['ENVNAME'] + ' Reaction Added', 1)
                        data[
                            'msg'] = 'Reaction "%s" successfully added' % reaction2.name
                        print("/dashboard/reactions/%s - Reaction edit success"
                              ) % rname
                        data['error'] = False
                else:
                    data['msg'] = "Form is not valid"
                    print(
                        "/dashboard/reactions/%s - Reaction edit failed: form invalid"
                    ) % rname
                    data['error'] = True
        form.process()
        page = render_template(tmpl, data=data, form=form)
        return page
    else:
        return redirect(url_for('user.login_page'))
Esempio n. 18
0
    def _populate(self):
        """Populate with reactions.

        Arguments:
            None

        Returns:
            None

        Populates:
            self
        """

        # try to
        try:

            # read in the configurationn
            yam = self._acquire(self.yam)

            # unpack yam
            species, reactions, bonds, forces = yam['species'], yam[
                'reactions'], yam['bonds'], yam['repulsions']

            # convert bonds to dictionary
            species = {record['chemical']: record for record in species}
            bonds = {record['bond']: record for record in bonds}
            forces = {record['repulsion']: record for record in forces}

            # update each species with its energy
            for chemical, record in species.items():

                # calculate attractions and repulsions, and update energy
                attractions = sum(
                    [bonds[bond]['energy'] for bond in self._bind(chemical)])
                repulsions = sum([
                    forces[force]['energy']
                    for force in self._repulse(chemical)
                ])
                record.update({'energy': attractions + repulsions})

            # for each reaction
            for reaction in reactions:

                # unpack reaction
                electrophile, nucleophile = reaction['electrophile'], reaction[
                    'nucleophile']
                reactant, product, leaver = reaction['reactant'], reaction[
                    'product'], reaction['leaver']
                catalysis = reaction['catalysis']

                # get bond energies of reactants
                chemicals = (nucleophile, reactant)
                reactants = sum([
                    bonds[bond]['energy'] for chemical in chemicals
                    for bond in self._bind(chemical)
                ])
                reactants += sum([
                    forces[force]['energy'] for chemical in chemicals
                    for force in self._repulse(chemical)
                ])

                # get bond energies of transition state
                chemicals = (nucleophile, electrophile, leaver)
                transition = sum([
                    bonds[bond]['energy'] for chemical in chemicals
                    for bond in self._bind(chemical)
                ])
                transition += sum([
                    forces[force]['energy'] for chemical in chemicals
                    for force in self._repulse(chemical)
                ])

                # get bond energies of products
                chemicals = (product, leaver)
                products = sum([
                    bonds[bond]['energy'] for chemical in chemicals
                    for bond in self._bind(chemical)
                ])
                products += sum([
                    forces[force]['energy'] for chemical in chemicals
                    for force in self._repulse(chemical)
                ])

                # calculate the forward and backward reection rates
                forward = math.exp(-(catalysis + transition - reactants))
                backward = math.exp(-(catalysis + transition - products))

                # create reaction instance
                energies = (reactants, transition + catalysis, products)
                member = Reaction(reaction, forward, backward, energies)
                self.append(member)

            # add attributes
            self.species = species
            self.bonds = bonds
            self.forces = forces

            # add list of chemicals
            chemicals = list(species.keys())
            chemicals.sort()
            self.chemicals = chemicals

        # unless not found
        except (KeyError, FileNotFoundError):

            # print warning
            self._print('no yams!, generating...')

            # generate from text
            text = self.yam.replace('yaml', 'txt')
            self._generate(text)

        return None