Example #1
0
 def check(self):
     compounds = DBSession.query(Compound).all()
     pains1 = DBSession.query(PAINS1).all()
     pains2 = DBSession.query(PAINS2).all()
     pains3 = DBSession.query(PAINS3).all()
     ID = ''
     for compound in compounds:
         m = Chem.MolFromSmiles(str(compound.structure))
         mol = Chem.AddHs(m)
         for p1 in pains1:
             patt = Chem.MolFromSmarts(str(p1.structure))
             if patt:
                 if mol.HasSubstructMatch(patt):
                     compound.pains1 = p1
             else:
                 flash(l_(u'Pattern error'), 'error')
                 redirect(request.headers['Referer'])
         for p2 in pains2:
             patt = Chem.MolFromSmarts(str(p2.structure))
             if patt:
                 if mol.HasSubstructMatch(patt):
                     compound.pains2 = p2
             else:
                 flash(l_(u'Pattern error'), 'error')
                 redirect(request.headers['Referer'])
         for p3 in pains3:
             patt = Chem.MolFromSmarts(str(p3.structure))
             if patt:
                 if mol.HasSubstructMatch(patt):
                     compound.pains3 = p3
             else:
                 flash(l_(u'Pattern error'), 'error')
                 redirect(request.headers['Referer'])
     flash(l_(u'Task completed successfully'))
     redirect(request.headers['Referer'])
Example #2
0
    def editlist(self, *args, **kw):
        """Let the user know that's visiting a protected controller."""
        userid = request.identity['repoze.who.userid']
        user = DBSession.query(User).filter(User.user_name == userid).first()
        users = DBSession.query(User).order_by(User.display_name).all()
        id = args[0]
        mylist = DBSession.query(UserLists).get(id)
        assert mylist.tg_user_id == user.user_id, u"Brak uprawnien edycji"
        if kw:
            if not (kw.has_key('name') and kw['name'] != u''):
                flash(l_(u'Name is required'), 'error')
            else:
                if kw.has_key('name') and kw['name'] != mylist.name:
                    mylist.name=kw['name']
#                if kw.has_key('table') and kw['table'] != mylist.table:
#                    mylist.table=kw['table']
                if kw.has_key('notes') and kw['notes'] != mylist.notes:
                    mylist.notes = kw['notes']
                if kw.has_key('permitusers') and kw['permitusers'] != u'':
                    if isinstance(kw['permitusers'], (list, tuple)):
                        permitusers = [usr for usr in users if usr.user_name in kw['permitusers']]
                    else:
                        permitusers = [usr for usr in users if usr.user_name == kw['permitusers']]
                    if permitusers != mylist.permitusers:
                        mylist.permitusers = permitusers
                DBSession.flush()
                flash(l_(u'Task completed successfully'))
                redirect(request.headers['Referer'])
        return dict(mylist=mylist, user=user, users=users, page='index', pname=None)
Example #3
0
    class child(FormLayout):
        image_small_id = HiddenField()
        image_big_id = HiddenField()

        name = TextField(label=l_('Name'),
                         css_class='form-control',
                         validator=Required)

        description = TextArea(label=l_('Description'),
                               rows=10,
                               css_class='form-control',
                               validator=Required)

        image_small = FileField(label=pluggable_config.get(
            'image1_label', l_('Small Image')),
                                css_class='form-control',
                                attrs=dict(accept='image/*'))
        image_big = FileField(label=pluggable_config.get(
            'image2_label', l_('Big Image')),
                              css_class='form-control',
                              attrs=dict(accept='image/*'))
        parent_id = SingleSelectField(
            css_class='form-control',
            options=Deferred(lambda: [(c._id, c.name) for c in model.provider.
                                      query(model.Category, filters={})[1]]))
Example #4
0
    class child(twf.TableLayout):
        inline_engine_name = 'kajiki'
        template = '''
         <div  style="padding-top:20px">
<py:for each="c in w.children_hidden">
                ${c.display()}
            </py:for>
                            <div class="col-md-12 ks-section-name">
                                Recover password
                                <hr/>
                            </div>
        <div class="row">
            <div class="form-group col-md-4">
                ${w.children.password.display()}
                <span class="help-block" py:content="w.children.password.error_msg"/>
            </div>
        </div>
        <div class="row">
            <div class="form-group col-md-4">
                ${w.children.password_confirm.display()}
                <span class="help-block" py:content="w.children.password_confirm.error_msg"/>
        </div>
        </div>
        </div>

                '''
        data = HiddenField()
        password = PasswordField(label=l_('New password'), validator=Validator(required=True), css_class='form-control', placeholder=l_('New password'))
        password_confirm = PasswordField(label=l_('Confirm new password'), validator=Validator(required=True), css_class='form-control', placeholder=l_('Confirm password'))
        validator = FieldsMatch('password', 'password_confirm')
Example #5
0
class BuyProductForm(Form):
    child = CustomListLayout
    css_class = "form-horizontal"

    product = HiddenField(validator=Validator(required=True))

    quantity = SingleSelectField(label=l_("Quantity"), options=[],
                                 validator=IntValidator(min=1, required=True),
                                 container_attrs={'class': 'form-group'},
                                 label_attrs={'class': 'col-sm-12'},
                                 wrapper_attrs={'class': 'col-sm-4'},
                                 css_class="form-control -quantity")
    submit = None

    submit1 = SubmitButton(value=l_('Add to cart'), key='add_to_cart', name='action',
                          css_class='btn btn-block btn-success stroller2-buy-product-submit-button')
    submit2 = SubmitButton(value=l_('Buy now'), key='buy_now', name='action',
                           css_class='btn btn-block btn-success stroller2-buy-product-submit-button')

    def prepare(self):
        super(BuyProductForm, self).prepare()

        product_field = self.child.children.product
        quantity_field = self.child.children.quantity
        product = app_globals.shop.product.get(_id=product_field.value)
        opts = [({'value': c}, c) for c in range(1, product.configurations[0].qty + 1)]
        quantity_field.grouped_options = [(None, opts)]
Example #6
0
class ActionDescription(object):
    """
    Allowed status are:
    - open
    - closed-validated
    - closed-invalidated
    - closed-deprecated
    """

    ARCHIVING = 'archiving'
    COMMENT = 'content-comment'
    CREATION = 'creation'
    DELETION = 'deletion'
    EDITION = 'edition'  # Default action if unknow
    REVISION = 'revision'
    STATUS_UPDATE = 'status-update'
    UNARCHIVING = 'unarchiving'
    UNDELETION = 'undeletion'
    MOVE = 'move'

    _ICONS = {
        'archiving': 'fa fa-archive',
        'content-comment': 'fa-comment-o',
        'creation': 'fa-magic',
        'deletion': 'fa-trash',
        'edition': 'fa-edit',
        'revision': 'fa-history',
        'status-update': 'fa-random',
        'unarchiving': 'fa-file-archive-o',
        'undeletion': 'fa-trash-o',
        'move': 'fa-arrows'
    }

    _LABELS = {
        'archiving': l_('archive'),
        'content-comment': l_('Item commented'),
        'creation': l_('Item created'),
        'deletion': l_('Item deleted'),
        'edition': l_('item modified'),
        'revision': l_('New revision'),
        'status-update': l_('New status'),
        'unarchiving': l_('Item unarchived'),
        'undeletion': l_('Item undeleted'),
        'move': l_('Item moved')
    }

    def __init__(self, id):
        assert id in ActionDescription.allowed_values()
        self.id = id
        self.label = ActionDescription._LABELS[id]
        self.icon = ActionDescription._ICONS[id]
        self.css = ''

    @classmethod
    def allowed_values(cls):
        return [
            cls.ARCHIVING, cls.COMMENT, cls.CREATION, cls.DELETION,
            cls.EDITION, cls.REVISION, cls.STATUS_UPDATE, cls.UNARCHIVING,
            cls.UNDELETION, cls.MOVE
        ]
Example #7
0
        def _admin_init_attrs(self):
            if 'child' not in self.__base_widget_args__:
                self.__base_widget_args__['child'] = _BootstrapFormLayout

            if 'submit' not in self.__base_widget_args__:
                if isinstance(self, AddRecordForm):
                    submit_text = l_('Create')
                else:
                    submit_text = l_('Save')

                self.__base_widget_args__['submit'] = SubmitButton(css_class='btn btn-primary',
                                                                   value=submit_text)

            for f in self.__fields__:
                try:
                    field = self.__metadata__[f]
                except KeyError:
                    continue

                field_options = self.FIELD_OPTIONS.copy()

                field_widget_type = self._do_get_field_widget_type(f, field)
                if field_widget_type in (SubDocument, SubDocumentsList):
                    field_options.pop('css_class')
                    field_options['children_attrs'] = self.FIELD_OPTIONS

                if field_widget_type == SubDocument:
                    field_options['template'] = 'tgext.admin.templates.bootstrap_form_layout'

                if field_widget_type == SubDocumentsList:
                    field_options['child'] = SubDocument(template='tgext.admin.templates.bootstrap_form_layout')

                self.__field_widget_args__[f] = _merge_dicts(field_options,
                                                             self.__field_widget_args__.get(f, {}))
Example #8
0
 def tags(self, **kw):
     pname = request.environ['PATH_INFO'].split('/')[1]
     userid = request.identity['repoze.who.userid']
     alltags = [tag for tag in DBSession.query(Tags).order_by('name').all()]
     if kw:
         try:
             usun = kw['button1']
         except Exception:
             usun = None
         if usun:
             try:
                 if isinstance(kw['deltags'], basestring):
                     tagi = [DBSession.query(Tags).get(int(kw['deltags']))]
                 else:
                     tagi = [
                         DBSession.query(Tags).get(int(id))
                         for id in kw['deltags']
                     ]
             except Exception:
                 tagi = None
             if tagi:
                 for tag in tagi:
                     for compound in DBSession.query(Compound).all():
                         if tag in compound.tags:
                             compound.tags.remove(tag)
                             history = History()
                             history.user = userid
                             history.status = u'Usuwanie tagu'
                             history.changes = u'Usunieto tag %s ' % tag.name
                             compound.history += [history]
                             DBSession.add(history)
                     DBSession.delete(tag)
                     DBSession.flush()
                 flash(l_(u'Task completed successfully'))
                 alltags = [
                     tag for tag in DBSession.query(Tags).order_by(
                         'name').all()
                 ]
         else:
             try:
                 if kw['addtag'] != '':
                     tagname = kw['addtag']
                 else:
                     tagname = None
             except Exception:
                 tagname = None
             if tagname:
                 tag = Tags()
                 tag.name = tagname
                 flash(l_(u'Task completed successfully'))
                 DBSession.add(tag)
                 DBSession.flush()
                 alltags = [
                     tg
                     for tg in DBSession.query(Tags).order_by('name').all()
                 ]
             else:
                 flash(l_(u'Name required'), 'warning')
     return dict(alltags=alltags, page='kierownik', pname=pname)
Example #9
0
    def addlist(self, *args, **kw):
        """Let the user know that's visiting a protected controller."""
        userid = request.identity['repoze.who.userid']
        user = DBSession.query(User).filter(User.user_name == userid).first()
        users = DBSession.query(User).order_by(User.display_name).all()
        allproj = DBSession.query(Projects).order_by('id').all()
        if args and len(args) >= 2:
            ntable = args[0]
            get_args = args[1:]
        else:
            ntable, get_args = [None, ()]
        if kw:
            if not (kw.has_key('name') and kw['name'] != u''):
                flash(l_(u'Name is required'), 'error')
                redirect(request.headers['Referer'])
            elif not (kw.has_key('table') and kw['table'] != u''):
                flash(l_(u'Table is required'), 'error')
                redirect(request.headers['Referer'])
            elif not (kw.has_key('project') and kw['project'] != u''):
                flash(l_(u'Project is required'), 'error')
                redirect(request.headers['Referer'])
            else:
                lista = UserLists()
                lista.name = kw['name']
                lista.table = kw['table']
                lista.pname = kw['project']
                if kw.has_key('notes') and kw['notes'] != u'':
                    lista.notes = kw['notes']
                if kw.has_key('permitusers') and kw['permitusers'] != u'':
                    if isinstance(kw['permitusers'], (list, tuple)):
                        permitusers = [
                            usr for usr in users
                            if usr.user_name in kw['permitusers']
                        ]
                    else:
                        permitusers = [
                            usr for usr in users
                            if usr.user_name == kw['permitusers']
                        ]
                    lista.permitusers = permitusers
                if kw.has_key('argv') and kw['argv'] != u'':
                    elements = []
                    for arg in kw['argv']:
                        elements.append(arg)
                    import pickle
                    lista.elements = pickle.dumps(elements)

                user.lists.append(lista)
                DBSession.add(lista)
                DBSession.flush()
                flash(l_(u'Task completed successfully'))
                redirect(request.headers['Referer'])
        return dict(user=user,
                    allproj=allproj,
                    users=users,
                    page='index',
                    ntable=ntable,
                    get_args=get_args,
                    pname=None)
Example #10
0
    def mylists(self, page=1, *args, **kw):
        """Let the user know that's visiting a protected controller."""
        userid = request.identity['repoze.who.userid']
        user = DBSession.query(User).filter(User.user_name == userid).first()
        mylists = user.lists
        import pickle as pcl
        dsc = True
        tmpl = ''
        selection = None
        order = "id"
        try:
            if kw['search'] != u'':
                search_clicked = kw['search']
            else:
                search_clicked = None
        except Exception:
            search_clicked = None
        if kw:
            delkw = []
            for k, v in kw.iteritems():
                if str(k) == 'desc' and str(v) != '1':
                    dsc = None
                elif str(k) == 'order_by':
                    order = v
                if str(k) != 'select' and str(k) != 'remove' and str(v) != u'':
                    tmpl += str(k) + '=' + str(v) + '&'
                elif str(k) == 'select':
                    try:
                        if isinstance(kw['select'], basestring):
                            selection = [kw['select']]
                        else:
                            selection = [id for id in kw['select']]
                    except Exception:
                        selection = None
                elif str(v) == u'':
                    delkw.append(k)
            for k in delkw:
                del kw[k]
        mylists = sorted(mylists, key=lambda list: list.__getattribute__(order))
        if dsc:
            mylists.reverse()
            
        if selection and not search_clicked:
            argv =''
            for arg in selection:
                argv += '/' + arg
            if kw['akcja'] == u'edit':
                if len(selection) == 1:
                    redirect('/myaccount/editlist%s' %argv)
                else:
                    flash(l_(u'Editing only one by one'), 'warning')
                    redirect(request.headers['Referer'])
            elif kw['akcja'] == u'delete':
                redirect('/myaccount/removelist%s' % argv)
            else:
                flash(l_(u'Action error'), 'error')
                redirect(request.headers['Referer'])

        return dict(mylists=mylists, pcl=pcl, page='index', tmpl=tmpl, pname=None)
Example #11
0
class NewPasswordForm(TableForm):
    data = HiddenField()
    password = PasswordField(label=l_('New password'),
                             validator=Validator(required=True))
    password_confirm = PasswordField(label=l_('Confirm new password'),
                                     validator=Validator(required=True))
    validator = FieldsMatch('password', 'password_confirm')
    submit = SubmitButton(value=l_('Save new password'))
Example #12
0
class NewCategoryForm(ListForm):
    name = TextField(label=l_('Name'), validator=Validator(required=True), css_class='form-control',
                     container_attrs={'class': 'form-group'})
    parent_id = SingleSelectField(label=l_('Parent'),
                                  css_class="form-control", container_attrs={'class': 'form-group'},
                                  options=Deferred(lambda: [(c._id, c.name[tg.config.lang])
                                                            for c in app_globals.shop.category.get_all()]))
    submit = SubmitButton(value=l_('Create'), css_class='btn btn-default')
Example #13
0
 class fields(WidgetsList):
     name = TextField(
         label_text=l_("Calendar Name"),
         validator=validators.UnicodeString(not_empty=True))
     events_type = SingleSelectField(
         label_text=l_('Events Type'),
         options=lambda:
         [e.name for e in config['_calendarevents']['event_types']],
         validator=validators.UnicodeString(not_empty=False))
Example #14
0
 class NewCalendarForm(TableForm):
     name = TextField(label=l_("Calendar Name"), validator=Required)
     events_type = SingleSelectField(
         label=l_('Events Type'),
         prompt_text=None,
         validator=Required,
         options=Deferred(
             lambda:
             [e.name for e in config['_calendarevents']['event_types']]))
Example #15
0
 def _validate_python(self, value, state=None):
     document_accepted_type = ['output']
     for cond in value:
         if cond['type'] == 'output':
             output = model.Output.query.get(_id=ObjectId(cond['content']))
             if not output:
                 raise ValidationError(l_(u'Output not found.'), self)
         else:
             raise ValidationError(l_(u'Invalid Filter.'), self)
Example #16
0
    class Details(twf.ListFieldSet):
        label = None
        key = 'details'

        email = twf.TextField(validator=twc.Validator(required=True),
                              css_class="form-control",
                              label=l_("Email"))
        phone = twf.TextField(validator=twc.Validator(),
                              css_class="form-control",
                              label=l_("Telefono"))
Example #17
0
 def index(self, workspace, **kw):
     return dict(
         page='precondition-index',
         fields={
             'columns_name': [l_('Label'), l_('Type'), l_('Owner')],
             'fields_name': ['title', 'type', 'owner']
         },
         entities=model.Precondition.precondition_available_for_user(request.identity['user']._id, workspace=workspace),
         actions_content=[l_('New Output'),l_('New Q/A')],
         workspace=workspace
     )
Example #18
0
 def _validate_python(self, value, state=None):
     for cond in value:
         if cond['type'] == 'qa_response':
             qa = model.Qa.query.get(_id=ObjectId(cond['content']))
             if not qa:
                 raise ValidationError(l_(u'Question not found.'), self)
         elif cond['type'] == 'output':
             out = model.Output.query.get(_id=ObjectId(cond['content']))
             if not out:
                 raise ValidationError(l_(u'Output not found'), self)
         else:
             raise ValidationError(l_(u'Invalid Filter.'), self)
Example #19
0
 class fields(WidgetsList):
     user_name = TextField(
         label_text=l_('User Name'),
         validator=UniqueUserValidator(not_empty=True))
     email_address = TextField(
         label_text=l_('Email'),
         validator=UniqueEmailValidator(not_empty=True))
     password = PasswordField(
         label_text=l_('Password'),
         validator=validators.UnicodeString(not_empty=True))
     password_confirm = PasswordField(
         label_text=l_('Confirm Password'),
         validator=validators.UnicodeString(not_empty=True))
Example #20
0
    class child(KajikiBootstrapFormLayout):
        permission_name = TextField(label=l_('Name'),
                                    css_class='form-control',
                                    validator=UnicodeString(not_empty=True))

        description = TextArea(label=l_('Description'),
                               rows=10,
                               css_class='form-control',
                               validator=UnicodeString(not_empty=True))

        groups = MultipleSelectField(label=l_('Groups'),
                                     css_class="form-control",
                                     options=Deferred(h.query_groups))
Example #21
0
    class RegistrationForm(TableForm):
        # set additional extra info here to bring them across the registration process
        # you might want to serialize the extra info in json or something similar
        extra = HiddenField()

        user_name = TextField(label=l_('User Name'),
                              validator=UniqueUserValidator(not_empty=True))
        email_address = TextField(
            label=l_('Email'), validator=UniqueEmailValidator(not_empty=True))
        password = PasswordField(label=l_('Password'), validator=Required)
        password_confirm = PasswordField(label=l_('Confirm Password'),
                                         validator=Required)
        validator = validators.FieldsMatch('password', 'password_confirm')
Example #22
0
 class fields(WidgetsList):
     event = HiddenField()
     cal = HiddenField(validator=SQLAEntityConverter(model.Calendar))
     name = TextField(
         label_text=l_('Event Name'),
         validator=validators.UnicodeString(not_empty=True))
     summary = TextArea(
         label_text=l_('Event short summary'),
         validator=validators.UnicodeString(not_empty=False))
     datetime = CalendarDateTimePicker(label_text=l_('Event date'))
     location = TextField(
         label_text=l_('Event Location (es: turin,it)'),
         validator=validators.UnicodeString(not_empty=True))
     linked_entity = SingleSelectField(label_text=l_('Linked Entity'))
Example #23
0
 def tags(self, **kw):
     pname = request.environ['PATH_INFO'].split('/')[1]
     userid = request.identity['repoze.who.userid']
     alltags =[tag for tag in DBSession.query(Tags).order_by('name').all() ]
     if kw:
         try:
             usun = kw['button1']
         except Exception:
             usun = None
         if usun:
             try:
                 if isinstance(kw['deltags'], basestring):
                     tagi = [DBSession.query( Tags ).get(int(kw['deltags']))]
                 else:
                     tagi = [DBSession.query( Tags ).get(int(id)) for id in kw['deltags']]
             except Exception:
                 tagi = None
             if tagi:
                 for tag in tagi:
                     for compound in DBSession.query(Compound).all():
                         if tag in compound.tags:
                             compound.tags.remove(tag)
                             history = History()
                             history.user = userid
                             history.status = u'Usuwanie tagu'
                             history.changes = u'Usunieto tag %s ' % tag.name
                             compound.history += [history]
                             DBSession.add(history)
                     DBSession.delete(tag)
                     DBSession.flush()
                 flash(l_(u'Task completed successfully'))
                 alltags =[tag for tag in DBSession.query(Tags).order_by('name').all() ]
         else:
             try:
                 if kw['addtag'] != '':
                     tagname = kw['addtag']
                 else:
                     tagname = None
             except Exception:
                 tagname = None
             if tagname:
                 tag = Tags()
                 tag.name = tagname
                 flash(l_(u'Task completed successfully'))
                 DBSession.add(tag)
                 DBSession.flush()
                 alltags =[tg for tg in DBSession.query(Tags).order_by('name').all() ]
             else:
                 flash(l_(u'Name required'), 'warning')
     return dict(alltags=alltags, page='kierownik', pname=pname)
Example #24
0
class ManagementController(BaseController):
    # Uncomment this line if your controller requires an authenticated user
    allow_only = predicates.has_permission('administration',
                                           msg=l_('Only for administrators'))
    history = HistoryController()

    def _before(self, *args, **kw):
        tmpl_context.page_name = "Fortressd"

    @expose('fortress.templates.management.index')
    def index(self):
        """Handle the front-page."""
        return dict(page='index')

    @expose('fortress.templates.management.data_centers')
    def data_centers(self):
        """Handle the front-page."""
        return dict(page='index')

    @expose('fortress.templates.management.data_servers')
    def data_servers(self):
        """Handle the front-page."""
        return dict(page='index')

    @expose('fortress.templates.management.users')
    def users(self):
        """Handle the front-page."""
        return dict(page='index')

    @expose('fortress.templates.management.authorizations')
    def authorizations(self):
        """Handle the front-page."""
        return dict(page='index')
Example #25
0
 def login(self, came_from=lurl('/start')):
     """Start the user login."""
     login_counter = request.environ.get('repoze.who.logins', 0)
     if login_counter > 0:
         flash(l_('Wrong credentials'), 'warning')
     return dict(page='login', login_counter=str(login_counter),
                 came_from=came_from)
Example #26
0
        def _admin_init_attrs(self):
            if 'child' not in self.__base_widget_args__:
                self.__base_widget_args__['child'] = _BootstrapFormLayout

            if 'submit' not in self.__base_widget_args__:
                if isinstance(self, AddRecordForm):
                    submit_text = l_('Create')
                else:
                    submit_text = l_('Save')

                self.__base_widget_args__['submit'] = SubmitButton(css_class='btn btn-primary',
                                                                   value=submit_text)

            for f in self.__fields__:
                self.__field_widget_args__[f] = _merge_dicts(self.FIELD_OPTIONS,
                                                             self.__field_widget_args__.get(f, {}))
Example #27
0
class SecureController(BaseController):
    """Sample controller-wide authorization"""

    # The predicate that must be met for all the actions in this controller:
    allow_only = has_permission(
        'manage', msg=l_('Only for people with the "manage" permission'))

    @expose('addrbook.templates.index')
    def index(self):
        """Let the user know that's visiting a protected controller."""
        flash(_("Secure Controller here"))
        try:
            username = self.username()
        except:
            username = ""
        return dict(page='index',
                    contacts=[],
                    user="******",
                    total=0,
                    partial=0)

    @expose('addrbook.templates.index')
    def some_where(self):
        """Let the user know that this action is protected too."""
        return dict(page='some_where')
Example #28
0
            class UsersController(BaseController):
                """Subcontrollers for lookup.
                MAIN SITE FOR PROJECT INSTANCE.
                Parmission allowed only for logged user with added permision named as a project.
                """
                # The predicate that must be met for all the actions in this controller:
                allow_only = has_permission(
                    project_name,
                    msg=l_('Permission is not sufficient for this user.'))
                molecules = MoleculesController()
                select = SelectController()
                synthesis = SynthesisController()
                library = LibraryController()
                results = ResultsController()

                @expose('molgears.templates.users.index')
                def index(self):
                    """Main site for project."""
                    userid = request.identity['repoze.who.userid']
                    projects = DBSession.query(Projects).all()
                    user = DBSession.query(User).filter_by(
                        user_name=userid).first()
                    perms = [p.permission_name for p in list(user.permissions)]
                    return dict(page='index',
                                userid=userid,
                                projects=projects,
                                perms=perms,
                                pname=project_name)
Example #29
0
class RootController(TGController):

    allow_only = in_any_group(
        'voter',
        'managers',
        msg=l_('Only for people with the "manage" permission'))

    invitation = InvitationController(model,
                                      model.DBSession,
                                      config_type=TGAdminConfig)
    voter = VoterController(model, model.DBSession, config_type=TGAdminConfig)
    publication = PublicationController(model,
                                        model.DBSession,
                                        config_type=TGAdminConfig)
    project = ProjectController(model,
                                model.DBSession,
                                config_type=TGAdminConfig)
    account = AccountController(model,
                                model.DBSession,
                                config_type=TGAdminConfig)
    script = LoadDataControllers(model,
                                 model.DBSession,
                                 config_type=TGAdminConfig)

    def __init__(self):

        self.utility = Utility()

    @expose('managepoll.templates.index')
    def index(self):
        flash(_("Hello World!"))
        return dict(page='index', idproject=None)
Example #30
0
class EditDescriptionForm(Form):
    action = 'update_description'

    class child(BaseLayout):
        inline_engine_name = 'kajiki'

        template = '''

<div py:strip="">
    <py:for each="c in w.children_hidden">
        ${c.display()}
    </py:for>

    <div class="form form-horizontal">
        <div class="form-group">
        <div class="mail-templates-title">Edit model description</div>
            <div class="col-md-12">
             <div py:with="c=w.children.description"
                     class="form-group ${c.error_msg and 'has-error' or ''}">
                    <label for="${c.compound_id}" class="col-md-2 control-label">${c.label}</label>
                    <div class="col-md-10">
                        ${c.display()}
                        <span class="help-block" py:content="c.error_msg"/>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
'''
        model_id = HiddenField()
        description = TextArea(label='Description', css_class='form-control')

    submit = SubmitButton(css_class='btn btn-primary pull-right', value=l_('Save'))
Example #31
0
        def _admin_init_attrs(self):
            if 'child' not in self.__base_widget_args__:
                self.__base_widget_args__['child'] = _BootstrapFormLayout

            if 'submit' not in self.__base_widget_args__:
                if isinstance(self, AddRecordForm):
                    submit_text = l_('Create')
                else:
                    submit_text = l_('Save')

                self.__base_widget_args__['submit'] = SubmitButton(
                    css_class='btn btn-primary', value=submit_text)

            for f in self.__fields__:
                self.__field_widget_args__[f] = _merge_dicts(
                    self.FIELD_OPTIONS, self.__field_widget_args__.get(f, {}))
Example #32
0
 def _convert_to_python(self, value, state=None):
     if value['field'] == 'status_changes.changed_at':
         try:
             value['filt'] = datetime.strptime(value['filt'], self.date_format)
         except:
             raise twc.ValidationError(l_('Date format must be dd/mm/yyyy'))
     return value
Example #33
0
 def addlist(self, *args, **kw):        
     """Let the user know that's visiting a protected controller."""
     userid = request.identity['repoze.who.userid']
     user = DBSession.query(User).filter(User.user_name == userid).first()
     users = DBSession.query(User).order_by(User.display_name).all()
     allproj = DBSession.query(Projects).order_by('id').all()
     if args and len(args) >= 2:
         ntable = args[0]
         get_args = args[1:]
     else:
         ntable, get_args = [None, ()]
     if kw:
         if not (kw.has_key('name') and kw['name'] != u''):
             flash(l_(u'Name is required'), 'error')
             redirect(request.headers['Referer'])
         elif not (kw.has_key('table') and kw['table'] != u''):
             flash(l_(u'Table is required'), 'error')
             redirect(request.headers['Referer'])
         elif not (kw.has_key('project') and kw['project'] != u''):
             flash(l_(u'Project is required'), 'error')
             redirect(request.headers['Referer'])
         else:
             lista = UserLists()
             lista.name = kw['name']
             lista.table = kw['table']
             lista.pname = kw['project']
             if kw.has_key('notes') and kw['notes'] != u'':
                 lista.notes = kw['notes']
             if kw.has_key('permitusers') and kw['permitusers'] != u'':
                 if isinstance(kw['permitusers'], (list, tuple)):
                     permitusers = [usr for usr in users if usr.user_name in kw['permitusers']]
                 else:
                     permitusers = [usr for usr in users if usr.user_name == kw['permitusers']]
                 lista.permitusers = permitusers
             if kw.has_key('argv') and kw['argv'] != u'':
                 elements = []
                 for arg in kw['argv']:
                     elements.append(arg)
                 import pickle
                 lista.elements = pickle.dumps(elements)
                     
             user.lists.append(lista)
             DBSession.add(lista)
             DBSession.flush()
             flash(l_(u'Task completed successfully'))
             redirect(request.headers['Referer'])
     return dict(user=user, allproj=allproj, users=users, page='index', ntable=ntable, get_args=get_args, pname=None)
Example #34
0
class CategoryController(RestController):
    allow_only = predicates.has_any_permission('manage',
                                               'lawyer', msg=l_('Only for admin or lawyer'))

    @expose('json')
    @validate({
        'id': CategoryExistValidator(required=True),
    }, error_handler=validation_errors_response)
    def get_one(self, id, **kw):
        qa = Category.query.get(_id=ObjectId(id))
        return dict(qa=qa)

    @expose('json')
    def get_all(self):
        query = {'_owner': {'$in': [request.identity['user']._id, None]}, 'visible': True}
        categories = Category.query.find(query).sort('_id').all()
        return dict(categories=categories)

    @decode_params('json')
    @expose('json')
    @validate({
        'workspace_name': StringLengthValidator(min=2),
    }, error_handler=validation_errors_response)
    def create(self, workspace_name=None, **kw):
        user = request.identity['user']
        ws = Category.query.find({'name': str(workspace_name), '_owner': user._id}).first()
        if ws:
            response.status_code = 412
            return dict(errors={'workspace_name': 'This category already exists'})

        workspace = Category(
            visible=True,
            name=str(workspace_name),
            _owner=user._id
        )

        flash(_("Workspace %s successfully created!" % workspace.name))
        return dict(workspaces=self.get_all())

    @decode_params('json')
    @expose('json')
    @validate({
        'workspace_id': CategoryExistValidator(required=True),
    }, error_handler=validation_errors_response)
    def delete(self, workspace_id=None, **kw):
        workspace = Category.query.get(_id=ObjectId(workspace_id))
        if not workspace.owner:
            flash(_('This workspace can not be deleted'), 'warning')
            return dict(workspaces=self.get_all())
        Qa.query.remove({'_category': ObjectId(workspace_id)})
        Output.query.remove({'_category': ObjectId(workspace_id)})
        Precondition.query.remove({'_category': ObjectId(workspace_id)})
        documents = Document.query.find({'_category': ObjectId(workspace_id)}).all()
        doc = [document._id for document in documents]
        Questionary.query.remove({'_document': {'$in': doc}})
        Document.query.remove({'_id': {'$in': doc}})
        Category.query.remove({'_id': ObjectId(workspace_id)})
        flash(_("Category and all entities associated deleted"))
        return dict(workspaces=self.get_all())
Example #35
0
    def post_logout(self, came_from=lurl('/')):
        """
        Redirect the user to the initially requested page on logout and say
        goodbye as well.

        """
        flash(l_('We hope to see you soon!'))
        return HTTPFound(location=came_from)
Example #36
0
    def post_logout(self, came_from=lurl('/')):
        """
        Redirect the user to the initially requested page on logout and say
        goodbye as well.

        """
        flash(l_('We hope to see you soon!'))
        return HTTPFound(location=came_from)
Example #37
0
def get_user_data(user):
    user_data = get_profile_data(
        user, {
            'display_name': (l_('Display Name'), user.display_name),
            'email_address': (l_('Email Address'), user.email_address),
        })

    user_avatar = user_data.pop('avatar', [None, None])[1]

    if user_avatar is None:
        fbauth_info = getattr(user, 'fbauth', None)
        if fbauth_info is not None:
            user_avatar = fbauth_info.profile_picture + '?type=large'
        else:
            user_avatar = _get_user_gravatar(user_data['email_address'][1])

    return user_data, user_avatar
Example #38
0
 def removelist(self, *args, **kw):
     """Let the user know that's visiting a protected controller."""
     userid = request.identity['repoze.who.userid']
     user = DBSession.query(User).filter(User.user_name == userid).first()
     id = args[0]
     mylist = DBSession.query(UserLists).get(id)
     if mylist.tg_user_id != user.user_id:
         flash(l_(u'Permission denied'), 'error')
         redirect(request.headers['Referer'])
     assert mylist.tg_user_id == user.user_id, u"Brak uprawnien usuwania"
     if mylist:
         DBSession.delete(mylist)
         DBSession.flush()
         flash(l_(u'Task completed successfully'))
         redirect(request.headers['Referer'])
     else:
         flash(l_(u'List is required'), 'warning')
         redirect(request.headers['Referer'])
Example #39
0
 def removelist(self, *args, **kw):
     """Let the user know that's visiting a protected controller."""
     userid = request.identity['repoze.who.userid']
     user = DBSession.query(User).filter(User.user_name == userid).first()
     id = args[0]
     mylist = DBSession.query(UserLists).get(id)
     if mylist.tg_user_id != user.user_id:
         flash(l_(u'Permission denied'), 'error')
         redirect(request.headers['Referer'])
     assert mylist.tg_user_id == user.user_id, u"Brak uprawnien usuwania"
     if mylist:
         DBSession.delete(mylist)
         DBSession.flush()
         flash(l_(u'Task completed successfully'))
         redirect(request.headers['Referer'])
     else:
         flash(l_(u'List is required'), 'warning')
         redirect(request.headers['Referer'])
Example #40
0
class UploadFileForm(twf.Form):
    class child(twf.TableLayout):
        inline_engine_name = 'kajiki'
        template = '''

            '''
        upload = FileField(label='')
    submit = SubmitButton(css_class="btn btn-primary", value=l_("Import"))
    action = lurl('/')
Example #41
0
 def save(self, **kw):
     order = Order.query.get(_id=ObjectId(kw['_id']))
     if kw.get('bill'):
         for k, v in kw.get('bill_info').iteritems():
             setattr(order.bill_info, k, v)
     for k, v in kw.get('shipment_info').iteritems():
         setattr(order.shipment_info, k, v)
     for k, v in kw.get('details').iteritems():
         setattr(order.details, k, v)
     flash(l_('Order successfully edited'))
     return redirect(self.mount_point + '/orders')
Example #42
0
    def deletefromlist(self, ulist_id, *args):
        """
            Delete compound from User List.
        """
        ulist = DBSession.query(UserLists).get(ulist_id)
#        pname = request.environ['PATH_INFO'].split('/')[1]
        userid = request.identity['repoze.who.userid']
        user = DBSession.query(User).filter_by(user_name=userid).first()
#        ulists = [l for l in user.lists if l.table == 'Results']
        if (ulist in user.lists) or (user in ulist.permitusers):
            if ulist.elements:
                import pickle
                elements = [int(el) for el in pickle.loads(ulist.elements)]
                for arg in args:
                    if int(arg) in elements:
                        elements.remove(int(arg))
                ulist.elements = pickle.dumps(elements)
                flash(l_(u'Task completed successfully'))
        else:
            flash(l_(u'Permission denied'), 'error')
        redirect(request.headers['Referer'])
Example #43
0
    def add_to_list(self, *args, **kw):
        if args:
            listid = args[0]
#            table = args[1]
            ulist = DBSession.query(UserLists).get(listid)

            values = []
            if args[2:]:
                for arg in args[2:]:
                    values.append(arg)
            import pickle
            if ulist and ulist.elements and ulist.elements != u"":
                elements = pickle.loads(ulist.elements)
            else:
                elements = []
            new_elements = set(elements + values)
            ulist.elements = pickle.dumps(list(new_elements))
            flash(l_(u'Task completed successfully'))
            redirect(request.headers['Referer'])
        else:
            flash(l_(u'Args error'), 'error')
            redirect("/")
Example #44
0
    def post_login(self, came_from=lurl('/start')):
        """
        Redirect the user to the initially requested page on successful
        authentication or redirect her back to the login page if login failed.

        """
        if not request.identity:
            login_counter = request.environ.get('repoze.who.logins', 0) + 1
            redirect('/login',
                params=dict(came_from=came_from, __logins=login_counter))
        userid = request.identity['repoze.who.userid']
        flash(l_('Welcome back, %s!') % userid)
        redirect(came_from)
Example #45
0
 def remove_from_list(self, *args, **kw):
     ulistid = args[0]
     ulist = DBSession.query(UserLists).get(ulistid)
     userid = request.identity['repoze.who.userid']
     user = DBSession.query(User).filter(User.user_name == userid).first()
     if (ulist in user.lists):
         if ulist.elements:
             import pickle
             elements = pickle.loads(ulist.elements)
             if args[1:]:
                 for arg in args[1:]:
                     elements.remove(arg)
                 ulist.elements = pickle.dumps(elements)
                 flash(l_(u'Task completed successfully'))
                 redirect(request.headers['Referer'])
             else:
                 flash(l_(u'Args error'), 'error')
                 redirect(request.headers['Referer'])
         else:
             flash(l_(u'List error'), 'error')
             redirect(request.headers['Referer'])
     else:
         flash(l_(u'Permission denied'), 'error')
         redirect(request.headers['Referer'])
Example #46
0
    def start(self):
        """
        Home page for authorized users.
        """
        from tg.predicates import not_anonymous
        if not not_anonymous():
            flash(l_(u'Permission is not sufficient for this user'), 'error')
            redirect('/')
        userid = request.identity['repoze.who.userid']
        projects = DBSession.query(Projects).order_by('id').all()
        user = DBSession.query(User).filter_by(user_name=userid).first()
        perms = list(user.permissions)
        perms_names = [p.permission_name for p in perms]
        user_projects = [project for project in projects if project.name in perms_names]
#        flash(l_(u'Alpha version. Please send error reporting to: [email protected]. \t\t :)'), 'warning')
        return dict(page='start', projects=user_projects, pname=None)
Example #47
0
        def __actions__(self, obj):
            primary_fields = self.__provider__.get_primary_fields(self.__entity__)
            pklist = '/'.join(map(lambda x: str(getattr(obj, x)), primary_fields))

            return Markup('''
    <a href="%(pklist)s/edit" class="btn btn-primary">
        <span class="glyphicon glyphicon-pencil"></span>
    </a>
    <div class="hidden-lg hidden-md">&nbsp;</div>
    <form method="POST" action="%(pklist)s" style="display: inline">
        <input type="hidden" name="_method" value="DELETE" />
        <button type="submit" class="btn btn-danger" onclick="return confirm('%(msg)s')">
            <span class="glyphicon glyphicon-trash"></span>
        </button>
    </form>
''' % dict(msg=l_('Are you sure?'),
           pklist=pklist))
Example #48
0
    def prefs(self, **kwargs):
        user = request.identity['user']

        if kwargs:
            DBSession.add(user)
            for key, value in kwargs.iteritems():
                setattr(user, key, value)
            flash(l_('Your settings have been updated.'))

        if not user.firstname or not user.lastname or not user.email:
            ldap_firstname, ldap_lastname, ldap_email = nimsutil.ldap_query(user.uid)
        firstname = user.firstname or ldap_firstname
        lastname = user.lastname or ldap_lastname
        email = user.email or ldap_email

        prefs = OrderedDict()
        prefs['firstname'] = ('First Name', firstname)
        prefs['lastname'] = ('Last Name', lastname)
        prefs['email'] = ('Email Address', email)

        return dict(page='prefs', prefs=prefs)
Example #49
0
 def _lookup(self, project_name, *remainder):
     """
     Project instance lookup.
     """
     from tg.predicates import not_anonymous
     try:
         came_from = request.headers['Referer']
     except Exception:
         came_from = request.path_url
     if not not_anonymous():
         flash(l_('Permission is not sufficient for this user.'), 'error')
         redirect('/login?came_from=%s' % came_from)
     if DBSession.query(Projects).filter(Projects.name==project_name).first():
         class UsersController(BaseController):
             """Subcontrollers for lookup.
             MAIN SITE FOR PROJECT INSTANCE.
             Parmission allowed only for logged user with added permision named as a project.
             """
             # The predicate that must be met for all the actions in this controller:
             allow_only = has_permission(project_name,
                                         msg=l_('Permission is not sufficient for this user.'))
             molecules = MoleculesController()
             select = SelectController()
             synthesis = SynthesisController()
             library = LibraryController()
             results = ResultsController()
             
             @expose('molgears.templates.users.index')
             def index(self):
                 """Main site for project."""
                 userid = request.identity['repoze.who.userid']    
                 projects = DBSession.query(Projects).all()
                 user = DBSession.query(User).filter_by(user_name=userid).first()
                 perms = [p.permission_name for p in list(user.permissions)]
                 return dict(page='index', userid=userid, projects=projects, perms=perms, pname=project_name)
         users = UsersController()
     else:
         users = ErrorController()
     return users, remainder
Example #50
0
    def index(self, page=1, *args, **kw):
        """
        Index controller for molecules
        """
        pname = request.environ['PATH_INFO'].split('/')[1]
        project = DBSession.query(Projects).filter(Projects.name==pname).first()
        alltags =[tag for tag in DBSession.query(Tags).order_by('name').all() ]
        from sqlalchemy import or_
        compound = DBSession.query(Compound).filter(Compound.project.any(Projects.name==pname)).filter(or_(Compound.pcompounds != None, Compound.lcompounds != None))
        dsc = True
        tmpl = ''
        selection = None
        similarity = None
        userid = request.identity['repoze.who.userid']
        user = DBSession.query(User).filter_by(user_name=userid).first()
        threshold = float(user.threshold)/100.0
        items = user.items_per_page
        order = "gid"
        try:
            if kw['search'] != u'':
                search_clicked = kw['search']
            else:
                search_clicked = None
        except Exception:
            search_clicked = None
        if kw:
            delkw = []
            for k, v in kw.iteritems():
                if str(k) == 'desc' and str(v) != '1':
                    dsc = None
                elif str(k) == 'order_by':
                    order = v
                if str(k) != 'select' and str(k) != 'remove' and str(v) != u'':
                    tmpl += str(k) + '=' + str(v) + '&'
                elif str(k) == 'select':
                    try:
                        if isinstance(kw['select'], basestring):
                            selection = [kw['select']]
                        else:
                            selection = [id for id in kw['select']]
                    except Exception:
                        selection = None
                elif str(v) == u'':
                    delkw.append(k)
            for k in delkw:
                del kw[k]
            if search_clicked:
                try:
                    smiles = str(kw['smiles'])
                except Exception:
                    smiles = None
                    pass
                try:
                    method = str(kw['method'])
                except Exception:
                    method = None
                    pass
                if smiles:
                    if checksmi(smiles):
                        from razi.functions import functions
                        from razi.expression import TxtMoleculeElement
                        if method == 'similarity':
                            from razi.postgresql_rdkit import tanimoto_threshold
                            DBSession.execute(tanimoto_threshold.set(threshold))
                            query_bfp = functions.morgan_b(TxtMoleculeElement(smiles), 2)
                            constraint = Compound.morgan.tanimoto_similar(query_bfp)
                            tanimoto_sml = Compound.morgan.tanimoto_similarity(query_bfp).label('tanimoto')
                            limit = user.limit_sim
                            search = DBSession.query(Compound, tanimoto_sml).filter(constraint).filter(Compound.project.any(Projects.name==pname)).order_by(desc(tanimoto_sml)).limit(limit).all()
                            compound = ()
                            similarity = ()
                            for row in search:
                                compound += (row[0], )
                                similarity += (row[1], )
                            page_url = paginate.PageURL_WebOb(request)
                            currentPage = paginate.Page(compound, page, url=page_url, items_per_page=items)
                            return dict(length=len(compound), compound=currentPage.items, currentPage=currentPage, tmpl=tmpl, page='samples', pname=pname, alltags=alltags, similarity=similarity)
    
                        elif method == 'substructure':
                            constraint = Compound.structure.contains(smiles)
                            compound = DBSession.query(Compound).filter(constraint).filter(Compound.project.any(Projects.name==pname))
                        elif method == 'identity':
                            compound = DBSession.query(Compound).filter(Compound.structure.equals(smiles)).filter(Compound.project.any(Projects.name==pname))
                    else:
                        flash(l_(u'Smiles error'), 'warning')
                        redirect(request.headers['Referer'])
                if kw.has_key('text_GID') and kw['text_GID'] !=u'':
                    try:
                        gid = int(kw['text_GID'])
                        compound = compound.filter_by(gid = gid )
                    except Exception as msg:
                        flash(l_(u'GID should be a number: %s' % msg), 'error')
                        redirect(request.headers['Referer'])
                if kw.has_key('text_name') and kw['text_name'] !=u'':
                    compound = compound.filter(Compound.names.any(Names.name.like(kw['text_name'].strip().replace('*', '%'))))
                if kw.has_key('text_creator') and kw['text_creator'] !=u'':
                    compound = compound.filter(Compound.creator.like(kw['text_creator'].replace('*', '%')))
                if kw.has_key('text_notes') and kw['text_notes'] !=u'':
                    compound = compound.filter(Compound.notes.like(kw['text_notes'].replace('*', '%')))
                if kw.has_key('date_from') and kw['date_from'] !=u'':
                    date_from = datetime.strptime(str(kw['date_from']), '%Y-%m-%d')
                    compound = compound.filter(Compound.create_date > date_from)
                else:
                    date_from = None
                if kw.has_key('date_to') and kw['date_to'] !=u'':
                    date_to = datetime.strptime(str(kw['date_to']), '%Y-%m-%d')
                    if date_from:
                        if date_to>date_from:
                            compound = compound.filter(Compound.create_date < date_to)
                        else:
                            flash(l_(u'The End date must be later than the initial'), 'error')
                            redirect(request.headers['Referer'])
                    else:
                        compound = compound.filter(Compound.create_date < date_to)
                try:
                    tags = kw['text_tags']
                except Exception:
                    tags = None
                    pass
                if tags:
                    if isinstance(tags, basestring):
                        tagi = eval(tags)
                        if type(tagi) != type([]):
                            tagi = [int(tags)]
                    else:
                        tagi = [int(id) for id in tags]
        
#                    import sqlalchemy
                    compound = compound.filter(Compound.tags.any(Tags.id.in_(tagi)))
                    
                    
        if selection and not search_clicked:
            argv =''
            for arg in selection:
                argv += '/' + arg
            if kw['akcja'] == u'edit':
                if len(selection) == 1:
                    redirect('/%s/samples/edit%s' % (pname, argv))
                else:
                    redirect('/%s/samples/multiedit/index%s' % (pname, argv))
            elif kw['akcja'] == u'accept':
                if len(selection) == 1:
                    redirect('/%s/samples/accept%s' % (pname, argv))
                else:
                    redirect('/%s/samples/multiaccept/index%s' % (pname, argv))
            elif kw['akcja'] == u'library':
                if len(selection) == 1:
                    redirect('/%s/samples/library%s' % (pname, argv))
                else:
                    redirect('/%s/samples/multilibrary/index%s' % (pname, argv))
            elif kw['akcja'] == u'pdf':
                redirect('/%s/samples/index/download%s/pdf/samples_selected.pdf' % (pname, argv))
            elif kw['akcja'] == u'xls':
                redirect('/%s/samples/download%s/xls/samples_selected.xls' % (pname, argv))
            elif kw['akcja'] == u'txt':
                redirect('/%s/samples/download%s/txt/samples_selected.txt' % (pname, argv))
            elif kw['akcja'] == u'delete':
                redirect('/%s/samples/remove%s' % (pname, argv))
            else:
                flash(l_(u'Action error'), 'error')
                redirect(request.headers['Referer'])
        else:
            try:
                akcja = kw['akcja']
            except Exception:
                akcja = None
            if akcja:
                if akcja == u'pdf':
                    redirect('/%s/samples/index/download/pdf/samples_all.pdf' % pname)
                elif akcja == u'xls':
                    redirect('/%s/samples/download/xls/samples_all.xls' % pname)
                elif akcja == u'txt':
                    redirect('/%s/samples/download/txt/samples_all.txt' % pname)
        if dsc:
            compound = compound.order_by(desc(order).nullslast())
        else:
            compound = compound.order_by((order))
        
        page_url = paginate.PageURL_WebOb(request)
        currentPage = paginate.Page(compound, page, url=page_url, items_per_page=items)
        return dict(compound=currentPage.items, currentPage=currentPage, tmpl=tmpl, page='samples', pname=pname, alltags=alltags, similarity=similarity)
Example #51
0
    def index(self, page=1, *args, **kw):
        pname = request.environ['PATH_INFO'].split('/')[1]
        project = DBSession.query(Projects).filter_by(name=pname).first()
        page_url = paginate.PageURL_WebOb(request)
        import pickle
        try:
            cells = pickle.loads([test.cell_line for test in project.tests if test.name == 'CT'][0])
        except:
            cells = None
        lcompound = DBSession.query(LCompound).join(LCompound.mol).filter(Compound.project.any(Projects.name==pname)).filter(LCompound.showme==True)
        
        dsc = True
        order = LCompound.id
        tmpl = ''
        alltags =[tag for tag in DBSession.query(Tags).order_by('name').all() ]
        selection = None
        similarity = None
        userid = request.identity['repoze.who.userid']
        user = DBSession.query(User).filter_by(user_name=userid).first()
        ulist = None
        ulists = set([l for l in user.lists if l.table == 'Results'] + [l for l in user.tg_user_lists if l.table == 'Results'])
        items = user.items_per_page
        
        try:
            if kw['search'] != u'':
                search_clicked = kw['search']
            else:
                search_clicked = None
        except Exception:
            search_clicked = None
        if kw:
            if kw.has_key('mylist'):
                try:
                    ulist_id = int(kw['mylist'])
                    ulist = DBSession.query(UserLists).get(ulist_id)
                except Exception:
                    flash(l_(u'List error'), 'error')
                    redirect(request.headers['Referer'])
                if (ulist in user.lists) or (user in ulist.permitusers):
                    if ulist.elements:
                        import pickle
                        elements = [int(el) for el in pickle.loads(ulist.elements)]
                        if ulist.table == 'Results':
                            lcompound = DBSession.query(LCompound).join(LCompound.mol).filter(Compound.project.any(Projects.name==pname)).filter(LCompound.id.in_(elements))
                        else:
                            flash(l_(u'Table error'), 'error')
                            redirect(request.headers['Referer'])
                else:
                    flash(l_(u'Permission denied'), 'error')
                    redirect(request.headers['Referer'])
            for k, v in kw.iteritems():
                if str(k) == 'desc' and str(v) != '1':
                    dsc = None
                elif str(k) == 'order_by':
                    if v in ('gid', 'create_date', 'box', 'form', 'state', 'entry', 'source', 'MDM2', 'MDM4', 'lcode'):
                        if v=='lcode':
                            order = LCompound.lcode
                        else:
                            order = LCompound.__getattribute__(LCompound, v)
                    else:
                        if v=='last_point':
                            lcompound=lcompound.join(LCompound.solubility)
                            order = v
                        elif hasattr(LCompound, v):
                            order = LCompound.__getattribute__(LCompound, v)
                        elif 'CTOX_' in v:
                            v = v.replace('CTOX_', '')
                            all_lcompounds = DBSession.query(LCompound).join(LCompound.mol).filter(Compound.project.any(Projects.name==pname)).all()
                            for l in all_lcompounds:
                                l.avg_ct = v.replace('pp', '+')
                            order = '_avg_ct'
                        else:
                            order = v
                if str(k) != 'select' and str(k) != 'remove' and str(v) != u'':
                    tmpl += str(k) + '=' + str(v) + '&'
                elif str(k) == 'select':
                    try:
                        if isinstance(kw['select'], basestring):
                            selection = [kw['select']]
                        else:
                            selection = [id for id in kw['select']]
                    except Exception:
                        selection = None
                        
            if search_clicked:
                try:
                    smiles = str(kw['smiles'])
                    if 'pp' in smiles:
                        smiles = smiles.replace('pp', '+')
                    method = str(kw['method'])
                except Exception:
                    smiles = None
                    method = None
                if smiles:
                    if checksmi(smiles):
                        from razi.functions import functions
                        from razi.expression import TxtMoleculeElement
                        if method == 'similarity':
#                            from razi.postgresql_rdkit import tanimoto_threshold
                            query_bfp = functions.morgan_b(TxtMoleculeElement(smiles), 2)
                            constraint = Compound.morgan.tanimoto_similar(query_bfp)
                            tanimoto_sml = Compound.morgan.tanimoto_similarity(query_bfp).label('tanimoto')
                            search = DBSession.query(LCompound, tanimoto_sml).join(LCompound.mol).join(LCompound.purity).filter(Compound.project.any(Projects.name==pname)).filter(constraint)
                            if order != LCompound.id:
                                if order == 'purity':
                                    order = LPurity.value
                                if dsc:
                                    search = search.order_by(desc(order).nullslast())
                                else:
                                    search = search.order_by(order)
                            else:
                                search = search.order_by(desc(tanimoto_sml)).all()
                            lcompound = ()
                            similarity = ()
                            for row in search:
                                lcompound += (row[0], )
                                similarity += (row[1], )
                            currentPage = paginate.Page(lcompound, page, url=page_url, items_per_page=items)
                            return dict(currentPage=currentPage,tmpl=tmpl, page='results', pname=pname, alltags=alltags, similarity=similarity,htmlRgb=htmlRgb, htmlRgb100=htmlRgb100, Num2Rgb=Num2Rgb, cells=cells, ulists=ulists, ulist=ulist)
    
                        elif method == 'substructure':
                            constraint = Compound.structure.contains(smiles)
                            lcompound = DBSession.query(LCompound).join(LCompound.mol).filter(Compound.project.any(Projects.name==pname)).filter(constraint)
                        elif method == 'identity':
                            lcompound = DBSession.query(LCompound).filter(Compound.project.any(Projects.name==pname)).join(LCompound.mol).filter(Compound.structure.equals(smiles))
                    else:
                        if method == 'smarts':
                            if dsc:
                                lcompound = lcompound.order_by(desc(order).nullslast())
                            else:
                                lcompound = lcompound.order_by(order)
                            search = lcompound.all()
                            sub_lcompounds = ()
                            patt = Chem.MolFromSmarts(smiles)
                            if not patt:
                                flash(l_(u'SMARTS error'), 'warning')
                                redirect(request.headers['Referer'])
                            for row in search:
                                m = Chem.MolFromSmiles(str(row.mol.structure))
                                mol = Chem.AddHs(m)
                                if mol.HasSubstructMatch(patt):
                                    sub_lcompounds += (row, )
                            currentPage = paginate.Page(sub_lcompounds, page, url=page_url, items_per_page=items)
                            return dict(currentPage=currentPage,tmpl=tmpl, page='results', pname=pname, alltags=alltags, similarity=similarity,htmlRgb=htmlRgb, htmlRgb100=htmlRgb100, Num2Rgb=Num2Rgb, cells=cells, ulists=ulists, ulist=ulist)
                        else:
                            flash(l_(u'SMILES error'), 'warning')
                            redirect(request.headers['Referer'])
                if kw.has_key('text_GID') and kw['text_GID'] !=u'':
                    try:
                        gid = int(kw['text_GID'])
                        lcompound = lcompound.filter(LCompound.gid == gid)
                    except Exception as msg:
                        flash(l_(u'GID should be a number: %s' % msg), 'error')
                        redirect(request.headers['Referer'])
                if kw.has_key('text_ID') and kw['text_ID'] !=u'':
                    try:
                        id = int(kw['text_ID'])
                        lcompound = lcompound.filter(LCompound.id == id)
                    except Exception as msg:
                        flash(l_(u'ID should be a number: %s' % msg), 'error')
                        redirect(request.headers['Referer'])
                if kw.has_key('text_name') and kw['text_name'] !=u'':
                    lcompound = lcompound.filter(Compound.names.any(Names.name.like(kw['text_name'].strip().replace('*', '%'))))
                if kw.has_key('text_notes') and kw['text_notes'] !=u'':
                    lcompound = lcompound.filter(LCompound.notes.like(kw['text_notes'].replace('*', '%')))
                if kw.has_key('text_lso') and kw['text_lso'] !=u'':
                    lcompound = lcompound.filter(LCompound.lso.like(kw['text_lso'].replace('*', '%')))
                if kw.has_key('text_entry') and kw['text_entry'] !=u'':
                    lcompound = lcompound.filter(LCompound.entry.like(kw['text_entry'].replace('*', '%')))
                if kw.has_key('text_box') and kw['text_box'] !=u'':
                    lcompound = lcompound.filter(LCompound.box.like(kw['text_box'].replace('*', '%')))
                if kw.has_key('date_from') and kw['date_from'] !=u'':
                    date_from = datetime.strptime(str(kw['date_from']), '%Y-%m-%d')
                    lcompound = lcompound.filter(LCompound.create_date > date_from)
                else:
                    date_from = None
                if kw.has_key('date_to') and kw['date_to'] !=u'':
                    date_to = datetime.strptime(str(kw['date_to']), '%Y-%m-%d')
                    if date_from:
                        if date_to>date_from:
                            lcompound = lcompound.filter(LCompound.create_date < date_to)
                        else:
                            flash(l_(u'The End date must be later than the initial'), 'error')
                            redirect(request.headers['Referer'])
                    else:
                        lcompound = lcompound.filter(LCompound.create_date < date_to)
                        
                if kw.has_key('text_mdm2_hill_from') and kw['text_mdm2_hill_from'] !=u'':
                    text_mdm2_hill_from = float(kw['text_mdm2_hill_from'])
                    lcompound = lcompound.filter(LCompound.avg_hillslope_mdm2 >= text_mdm2_hill_from)
                else:
                    text_mdm2_hill_from = None
                if kw.has_key('text_mdm2_hill_to') and kw['text_mdm2_hill_to'] !=u'':
                    text_mdm2_hill_to = float(kw['text_mdm2_hill_to'])
                    if text_mdm2_hill_from:
                        if text_mdm2_hill_to>=text_mdm2_hill_from:
                            lcompound = lcompound.filter(LCompound.avg_hillslope_mdm2 <= text_mdm2_hill_to)
                        else:
                            flash(l_(u'The final value must be greater than the initial'))
                            redirect(request.headers['Referer'])
                    else:
                        lcompound = lcompound.filter(LCompound.avg_hillslope_mdm2 <= text_mdm2_hill_to)
                if kw.has_key('text_mdm2_fluor_from') and kw['text_mdm2_fluor_from'] !=u'':
                    text_mdm2_fluor_from = float(kw['text_mdm2_fluor_from'])
                    lcompound = lcompound.filter(LCompound.avg_fluorescence_mdm2 >= text_mdm2_fluor_from)
                else:
                    text_mdm2_fluor_from = None
                if kw.has_key('text_mdm2_fluor_to') and kw['text_mdm2_fluor_to'] !=u'':
                    text_mdm2_fluor_to = float(kw['text_mdm2_fluor_to'])
                    if text_mdm2_fluor_from:
                        if text_mdm2_fluor_to>=text_mdm2_fluor_from:
                            lcompound = lcompound.filter(LCompound.avg_fluorescence_mdm2 <= text_mdm2_fluor_to)
                        else:
                            flash(l_(u'The final value must be greater than the initial'))
                            redirect(request.headers['Referer'])
                    else:
                        lcompound = lcompound.filter(LCompound.avg_fluorescence_mdm2 <= text_mdm2_fluor_to)
                if kw.has_key('text_mdm2_ki_from') and kw['text_mdm2_ki_from'] !=u'':
                    text_mdm2_ki_from = float(kw['text_mdm2_ki_from'])
                    lcompound = lcompound.filter(LCompound.avg_ki_mdm2 >= text_mdm2_ki_from)
                else:
                    text_mdm2_ki_from = None
                if kw.has_key('text_mdm2_ki_to') and kw['text_mdm2_ki_to'] !=u'':
                    text_mdm2_ki_to = float(kw['text_mdm2_ki_to'])
                    if text_mdm2_ki_from:
                        if text_mdm2_ki_to>=text_mdm2_ki_from:
                            lcompound = lcompound.filter(LCompound.avg_ki_mdm2 <= text_mdm2_ki_to)
                        else:
                            flash(l_(u'The final value must be greater than the initial'))
                            redirect(request.headers['Referer'])
                    else:
                        lcompound = lcompound.filter(LCompound.avg_ki_mdm2 <= text_mdm2_ki_to)

                if kw.has_key('text_mdm4_hill_from') and kw['text_mdm4_hill_from'] !=u'':
                    text_mdm4_hill_from = float(kw['text_mdm4_hill_from'])
                    lcompound = lcompound.filter(LCompound.avg_hillslope_mdm4 >= text_mdm4_hill_from)
                else:
                    text_mdm4_hill_from = None
                if kw.has_key('text_mdm4_hill_to') and kw['text_mdm4_hill_to'] !=u'':
                    text_mdm4_hill_to = float(kw['text_mdm4_hill_to'])
                    if text_mdm4_hill_from:
                        if text_mdm4_hill_to>=text_mdm4_hill_from:
                            lcompound = lcompound.filter(LCompound.avg_hillslope_mdm4 <= text_mdm4_hill_to)
                        else:
                            flash(l_(u'The final value must be greater than the initial'))
                            redirect(request.headers['Referer'])
                    else:
                        lcompound = lcompound.filter(LCompound.avg_hillslope_mdm4 <= text_mdm4_hill_to)
                        
                if kw.has_key('text_mdm4_fluor_from') and kw['text_mdm4_fluor_from'] !=u'':
                    text_mdm4_fluor_from = float(kw['text_mdm4_fluor_from'])
                    lcompound = lcompound.filter(LCompound.avg_fluorescence_mdm4 >= text_mdm4_fluor_from)
                else:
                    text_mdm4_fluor_from = None
                if kw.has_key('text_mdm4_fluor_to') and kw['text_mdm4_fluor_to'] !=u'':
                    text_mdm4_fluor_to = float(kw['text_mdm4_fluor_to'])
                    if text_mdm4_fluor_from:
                        if text_mdm4_fluor_to>=text_mdm4_fluor_from:
                            lcompound = lcompound.filter(LCompound.avg_fluorescence_mdm4 <= text_mdm4_fluor_to)
                        else:
                            flash(l_(u'The final value must be greater than the initial'))
                            redirect(request.headers['Referer'])
                    else:
                        lcompound = lcompound.filter(LCompound.avg_fluorescence_mdm4 <= text_mdm4_fluor_to)
                        
                if kw.has_key('text_mdm4_ki_from') and kw['text_mdm4_ki_from'] !=u'':
                    text_mdm4_ki_from = float(kw['text_mdm4_ki_from'])
                    lcompound = lcompound.filter(LCompound.avg_ki_mdm4 >= text_mdm4_ki_from)
                else:
                    text_mdm4_ki_from = None
                if kw.has_key('text_mdm4_ki_to') and kw['text_mdm4_ki_to'] !=u'':
                    text_mdm4_ki_to = float(kw['text_mdm4_ki_to'])
                    if text_mdm4_ki_from:
                        if text_mdm4_ki_to>=text_mdm4_ki_from:
                            lcompound = lcompound.filter(LCompound.avg_ki_mdm4 <= text_mdm4_ki_to)
                        else:
                            flash(l_(u'The final value must be greater than the initial'))
                            redirect(request.headers['Referer'])
                    else:
                        lcompound = lcompound.filter(LCompound.avg_ki_mdm4 <= text_mdm4_ki_to)

                try:
                        tags = kw['text_tags']
                except Exception:
                    tags = None
                    pass
                if tags:
                    if isinstance(tags, basestring):
                        tagi = eval(tags)
                        if type(tagi) != type([]):
                            tagi = [int(tags)]
                    else:
                        tagi = [int(tid) for tid in tags]
                    lcompound = lcompound.filter(Compound.tags.any(Tags.id.in_(tagi)))
                    
        if dsc:
            lcompound = lcompound.order_by(desc(order).nullslast())
        else:
            lcompound = lcompound.order_by(order)
            
        if search_clicked and kw['search'] == "Download":
            if kw['file_type'] and kw['file_type'] != u'' and kw['sell_type'] and kw['sell_type'] != u'':
                if kw['sell_type'] == u'all':
                    lcompounds = lcompound.all()
                elif kw['sell_type'] == u'selected':
                    if selection:
                        lcompounds = ()
                        for el in selection:
                            lcompounds += (DBSession.query(LCompound).get(el), )
                    else:
                        flash(l_(u'Lack of selected structures for download'), 'error')
                        redirect(request.headers['Referer'])
                elif kw['sell_type'] == u'range':
                    lcompounds = lcompound.all()
                    if kw.has_key('select_from') and kw['select_from'] != u'':
                        try:
                            select_from = int(kw['select_from']) -1 
                            if select_from<1 or select_from>len(lcompounds):
                                select_from = 0
                        except Exception:
                            select_from = 0
                    else:
                        select_from = 0
                    if kw.has_key('select_to') and kw['select_to'] != u'':
                        try:
                            select_to = int(kw['select_to'])
                            if select_to<2 or select_to>len(lcompounds):
                                select_to = len(lcompounds)
                        except Exception:
                            select_to = len(lcompounds)
                    else:
                        select_to = len(lcompounds)
                    lcompounds_new = ()
                    for el in range(select_from, select_to):
                        lcompounds_new += (lcompounds[el], )
                    lcompounds = lcompounds_new
                else:
                    flash(l_(u'Lack of items to download'), 'error')
                    redirect(request.headers['Referer'])
                try:
                    if isinstance(kw['options'], basestring):
                        options = [kw['options']]
                    else:
                        options = kw['options']
                except Exception:
                    flash(l_('Choose download options'), 'error')
                    redirect(request.headers['Referer'])
                if 'getsize' in kw:
                    size = int(kw['getsize']), int(kw['getsize'])
                else:
                    size = 100, 100
                if kw['file_type'] == 'pdf':
                    filename = userid + '_selected.pdf'
                    from xhtml2pdf.pisa import CreatePDF
                    from tg.render import render as render_template
                    import cStringIO
                    html = render_template({"length":len(lcompounds), "lcompound":lcompounds, "cells":cells, "options":options, "size":size}, "genshi", "molgears.templates.users.results.print2", doctype=None)
                    dest = './molgears/files/pdf/' + filename
                    result = file(dest, "wb")
                    CreatePDF(cStringIO.StringIO(html.encode("UTF-8")), result, encoding="utf-8")
                    result.close()
                    import paste.fileapp
                    f = paste.fileapp.FileApp('./molgears/files/pdf/'+ filename)
                    from tg import use_wsgi_app
                    return use_wsgi_app(f)
                elif kw['file_type'] == 'xls':
                    filename = userid + '_selected.xls'
                    filepath = os.path.join('./molgears/files/download/', filename)
                    from PIL import Image
                    import xlwt
                    wbk = xlwt.Workbook()
                    sheet = wbk.add_sheet('sheet1')
                    j=0
                    if 'nr' in options:
                        sheet.write(0,j,u'Nr.')
                        j+=1
                    if 'gid' in options:
                        sheet.write(0,j,u'GID')
                        j+=1
                    if 'id' in options:
                        sheet.write(0,j,u'ID')
                        j+=1
                    if 'name' in options:
                        sheet.write(0,j,u'Name')
                        j+=1
                    if 'names' in options:
                        sheet.write(0,j,u'Names')
                        j+=1
                    if 'image' in options:
                        sheet.write(0,j,u'Image')
                        j+=1
                    if 'smiles' in options:
                        sheet.write(0,j,u'SMILES')
                        j+=1
                    if 'inchi' in options:
                        sheet.write(0,j,u'InChi')
                        j+=1
                    if 'lso' in options:
                        sheet.write(0,j,u'LSO')
                        j+=1
                    if 'num_atoms' in options:
                        sheet.write(0,j,u'Atoms')
                        j+=1
                    if 'mw' in options:
                        sheet.write(0,j,u'MW')
                        j+=1
                    if 'hba' in options:
                        sheet.write(0,j,u'hba')
                        j+=1
                    if 'hbd' in options:
                        sheet.write(0,j,u'hbd')
                        j+=1
                    if 'tpsa' in options:
                        sheet.write(0,j,u'tpsa')
                        j+=1
                    if 'logp' in options:
                        sheet.write(0,j,u'logP')
                        j+=1
                    if 'purity' in options:
                        sheet.write(0,j, u'Purity')
                        j+=1
                    if 'create_date' in options:
                        sheet.write(0,j,u'Date')
                        j+=1
                    if 'box' in options:
                        sheet.write(0,j,u'Box')
                        j+=1
                    if 'entry' in options:
                        sheet.write(0,j,u'Entry')
                        j+=1
                    if 'source' in options:
                        sheet.write(0,j,u'Source')
                        j+=1
                    if 'content' in options:
                        sheet.write(0,j,u'Content')
                        j+=1
                    if 'tags' in options:
                        sheet.write(0,j,u'Tags')
                        j+=1
                    if 'notes' in options:
                        sheet.write(0,j,u'Notes')
                        j+=1
                    for cell_line in cells:
                        if '_CT_%s' % cell_line in options:
                            sheet.write(0,j,u'CT %s' % cell_line)
                            j+=1
                    i = 1
                    for row in lcompounds:
                        j=0
                        if 'nr' in options:
                            sheet.write(i,j, str(i))
                            j+=1
                        if 'gid' in options:
                            sheet.write(i,j, row.gid)
                            j+=1
                        if 'id' in options:
                            sheet.write(i,j, row.id)
                            j+=1
                        if 'name' in options:
                            sheet.write(i,j, row.mol.name)
                            j+=1
                        if 'names' in options:
                            names = u''
                            for n in row.mol.names:
                                names += n.name + u', '
                            sheet.write(i,j, names)
                            j+=1
                        if 'image' in options:
                            file_in = './molgears/public/img/%s.png' % row.gid
                            img = Image.open(file_in)
                            file_out = './molgears/public/img/bitmap/thumb%s.bmp' %row.gid
                            img.thumbnail(size, Image.ANTIALIAS)
                            img.save(file_out)
                            sheet.insert_bitmap(file_out , i,j, 5, 5)
                            j+=1
                        if 'smiles' in options:
                            sheet.write(i,j, str(row.mol.structure))
                            j+=1
                        if 'inchi' in options:
                            sheet.write(i,j, str(row.mol.inchi))
                            j+=1
                        if 'lso' in options:
                            sheet.write(i,j, row.lso)
                            j+=1
                        if 'num_atoms' in options:
                            sheet.write(i,j,str(row.mol.num_hvy_atoms)+'/'+str(row.mol.num_atoms))
                            j+=1
                        if 'mw' in options:
                            sheet.write(i,j, str(row.mol.mw))
                            j+=1
                        if 'hba' in options:
                            sheet.write(i,j, str(row.mol.hba))
                            j+=1
                        if 'hbd' in options:
                            sheet.write(i,j, str(row.mol.hbd))
                            j+=1
                        if 'tpsa' in options:
                            sheet.write(i,j, str(row.mol.tpsa))
                            j+=1
                        if 'logp' in options:
                            sheet.write(i,j, str(row.mol.logp))
                            j+=1
                        if 'state' in options:
                            sheet.write(i,j, str(row.state))
                            j+=1
                        if 'purity' in options:
                            pur = u''
                            for p in sorted(row.purity, key=lambda p: p.value, reverse=True):
                                pur += u'%s : %s\n' % (p.value, p.type)
                            sheet.write(i,j, pur)
                            j+=1
                        if 'create_date' in options:
                            sheet.write(i,j, str(row.create_date))
                            j+=1
                        if 'owner' in options:
                            sheet.write(i,j, row.owner)
                            j+=1
                        if 'box' in options:
                            sheet.write(i,j, row.box)
                            j+=1
                        if 'entry' in options:
                            sheet.write(i,j, row.entry)
                            j+=1
                        if 'source' in options:
                            sheet.write(i,j, row.source)
                            j+=1
                        if 'content' in options:
                            if row.content:
                                sheet.write(i,j, str(row.content.value))
                            else:
                                sheet.write(i,j, 'None')
                            j+=1
                        if 'tags' in options:
                            tagsy=u''
                            for tag in row.mol.tags:
                                tagsy += tag.name + u', '
                            sheet.write(i,j,tagsy)
                            j+=1
                        if 'notes' in options:
                            sheet.write(i,j, row.notes)
                            j+=1
                        for cell_line in cells:
                            if '_CT_%s' % cell_line in options:
                                res = []
                                if row.ctoxicity:
                                    for ct in sorted(row.ctoxicity, key=lambda ct: ct.id):
                                        if ct.cell_line==cell_line:
                                            res.append(ct.ic50)
                                if len(res)>0:
                                    sheet.write(i,j, str(round(sum(res)/len(res), 3)))
                                else:
                                    sheet.write(i,j, '')
                                j+=1
                        i += 1
                    wbk.save(filepath)
                    import paste.fileapp
                    f = paste.fileapp.FileApp(filepath)
                    from tg import use_wsgi_app
                    return use_wsgi_app(f)
                    
                elif kw['file_type'] == 'sdf':
                    filepath = './molgears/files/download/out.sdf'
                    ww = Chem.SDWriter(filepath)
                    from rdkit.Chem import AllChem
                    for row in lcompounds:
                        m2 = Chem.MolFromSmiles(str(row.mol.structure))
                        AllChem.Compute2DCoords(m2)
                        AllChem.EmbedMolecule(m2)
                        AllChem.UFFOptimizeMolecule(m2)
                        if 'smiles' in options:
                            m2.SetProp("smiles", str(row.mol.structure))
                        if 'name' in options:
                            m2.SetProp("_Name", str(row.mol.name.encode('ascii', 'ignore')))
                        if 'nr' in options:
                            m2.SetProp("Nr", str(lcompounds.index(row)+1))
                        if 'gid' in options:
                            m2.SetProp("GID", str(row.gid))
                        if 'names' in options:
                            names = u''
                            for n in row.mol.names:
                                names += n.name + ', '
                            m2.SetProp("names", str(names.encode('ascii', 'ignore')))
                        if 'inchi' in options:
                            m2.SetProp("InChi", str(row.mol.inchi))
                        if 'lso' in options:
                            m2.SetProp("LSO", str(row.lso))
                        if 'num_atoms' in options:
                           m2.SetProp("atoms", str(row.mol.num_hvy_atoms)+'/'+str(row.mol.num_atoms))
                        if 'mw' in options:
                            m2.SetProp("mw", str(row.mol.mw))
                        if 'hba' in options:
                            m2.SetProp("hba", str(row.mol.hba))
                        if 'hbd' in options:
                            m2.SetProp("hbd", str(row.mol.hbd))
                        if 'tpsa' in options:
                            m2.SetProp("TPSA", str(row.mol.tpsa))
                        if 'logp' in options:
                            m2.SetProp("logP", str(row.mol.tpsa))
                        if 'create_date' in options:
                            m2.SetProp("create_date", str(row.create_date))
                        if 'owner' in options:
                            m2.SetProp("owner", str(row.owner))
                        if 'tags' in options:
                            tagsy=u''
                            for tag in row.mol.tags:
                                tagsy += tag.name + u', '
                            m2.SetProp("tagi", str(tagsy.encode('ascii', 'ignore')))
                        if 'purity' in options:
                            pur = u''
                            for p in sorted(row.purity, key=lambda p: p.value, reverse=True):
                                pur += u'%s : %s \n' % (p.value, p.type)
                            m2.SetProp("purity", str(pur.encode('ascii', 'ignore')))
                        if 'content' in options:
                            if row.content:
                                m2.SetProp("content", str(row.content.value))
                            else:
                                m2.SetProp("content", "None")
                            j+=1
                        if 'box' in options:
                            m2.SetProp("box", str(row.box))
                        if 'entry' in options:
                            m2.SetProp("entry", str(row.entry))
                        if 'notes' in options:
                            if row.notes:
                                m2.SetProp("notes", str(row.notes.encode('ascii', 'ignore')))
                            else:
                                m2.SetProp("notes", " ")
                        for cell_line in cells:
                            if '_CT_%s' % cell_line in options:
                                res = []
                                if row.ctoxicity:
                                    for ct in sorted(row.ctoxicity, key=lambda ct: ct.id):
                                        if ct.cell_line==cell_line:
                                            res.append(ct.ic50)
                                if len(res)>0:
                                    m2.SetProp('CT_%s' % cell_line, str(round(sum(res)/len(res), 3)))
                                else:
                                    m2.SetProp('CT_%s' % cell_line, ' ')
                                
                        ww.write(m2)
                    ww.close()
                    import paste.fileapp
                    f = paste.fileapp.FileApp(filepath)
                    from tg import use_wsgi_app
                    return use_wsgi_app(f)
                    
                elif kw['file_type'] == 'csv' or 'txt':
                    filename = userid + '_selected.' + kw['file_type']
                    filepath = os.path.join('./molgears/files/download/', filename)
                    from molgears.widgets.unicodeCSV import UnicodeWriter
                    import csv
                    if kw['file_type'] == u'csv':
                        delimiter = ';'
                    else:
                        delimiter = ' '
                    with open(filepath, 'wb') as csvfile:
                        
                        spamwriter = UnicodeWriter(csvfile, delimiter=delimiter,
                                                quotechar='|', quoting=csv.QUOTE_MINIMAL)
                        for row in lcompounds:
                            line =[]
                            if 'smiles' in options:
                                line.append(str(row.mol.structure))
                            if 'name' in options:
                                line.append(row.mol.name)
                            if 'nr' in options:
                                line.append(unicode(lcompounds.index(row)+1))
                            if 'gid' in options:
                                line.append(unicode(row.gid))
                            if 'names' in options:
                                names = u''
                                for n in row.mol.names:
                                    names += n.name + u', '
                                line.append(names)
                            if 'inchi' in options:
                                line.append(row.mol.inchi)
                            if 'lso' in options:
                                line.append(row.lso)
                            if 'num_atoms' in options:
                               line.append(unicode(row.mol.num_hvy_atoms)+'/'+unicode(row.mol.num_atoms))
                            if 'mw' in options:
                                line.append(unicode(row.mol.mw))
                            if 'hba' in options:
                                line.append(unicode(row.mol.hba))
                            if 'hbd' in options:
                                line.append(unicode(row.mol.hbd))
                            if 'tpsa' in options:
                                line.append(unicode(row.mol.tpsa))
                            if 'logp' in options:
                                line.append(unicode(row.mol.logp))
                            if 'purity' in options:
                                pur = u''
                                for p in sorted(row.purity, key=lambda p: p.value, reverse=True):
                                    pur += u'%s : %s\n' % (p.value, p.type)
                                line.append(pur)
                            if 'create_date' in options:
                                line.append(unicode(row.create_date))
                            if 'owner' in options:
                                line.append(row.owner)
                            if 'box' in options:
                                line.append(row.box)
                            if 'entry' in options:
                                line.append(row.entry)
                            if 'source' in options:
                                line.append(row.source)
                            if 'content' in options:
                                if row.content:
                                    line.append(unicode(row.content.value))
                                else:
                                    line.append(u'None')
                            if 'tags' in options:
                                tagsy= ''
                                for tag in row.mol.tags:
                                    tagsy += tag.name + ', '
                                line.append(tagsy)
                            if 'notes' in options:
                                line.append(row.notes)
                            spamwriter.writerow(line)
                    import paste.fileapp
                    f = paste.fileapp.FileApp(filepath)
                    from tg import use_wsgi_app
                    return use_wsgi_app(f)

        if selection and not search_clicked:
            argv =''
            gids = ''
            for arg in selection:
                argv += '/' + arg
                tmp_result = DBSession.query(LCompound).get(arg)
                gids += '/' + str(tmp_result.gid)
            if kw['akcja'] == u'edit':
                redirect('/%s/molecules/multiedit/index%s' % (pname, gids))
            elif kw['akcja'] == u'results':
                if len(selection) == 1:
                    redirect('/%s/results/new_result%s' % (pname, argv))
                else:
                    redirect('/%s/results/multiresults/index%s' % (pname, argv))
            elif kw['akcja'] == u'htrf':
                if len(selection) == 1:
                    redirect('/%s/results/htrf/add_result2%s' % (pname, argv))
        currentPage = paginate.Page(lcompound, page, url=page_url, items_per_page=items)
        return dict(currentPage=currentPage,tmpl=tmpl, page='results', htmlRgb=htmlRgb, htmlRgb100=htmlRgb100, Num2Rgb=Num2Rgb, pname=pname, alltags=alltags, similarity=similarity, cells=cells, ulists=ulists, ulist=ulist)
Example #52
0
from tg.i18n import lazy_ugettext as l_
from tw.forms.validators import FieldStorageUploadConverter
from skylines.forms import BootstrapForm, MultiFileField, pilot


file_field_validator = FieldStorageUploadConverter(
    not_empty=True,
    messages=dict(empty=l_("Please add one or more IGC or ZIP files")),
    accept_iterator=True
)

file_field = MultiFileField(
    'file', label_text=l_("IGC or ZIP file(s)"), validator=file_field_validator)

form = BootstrapForm('upload_form', submit_text="Upload", action='do', children=[
    file_field,
    pilot.SelectField('pilot', label_text=l_("Pilot"))
])
Example #53
0
# on login:
base_config.sa_auth.post_login_url = '/post_login'

# You may optionally define a page where you want users to be redirected to
# on logout:
base_config.sa_auth.post_logout_url = '/post_logout'

# INFO - This is the way to specialize the resetpassword email properties
# plug(base_config, 'resetpassword', None, mail_subject=reset_password_email_subject)
plug(base_config, 'resetpassword', 'reset_password')

replace_template(base_config, 'resetpassword.templates.index', 'tracim.templates.reset_password_index')
replace_template(base_config, 'resetpassword.templates.change_password', 'mako:tracim.templates.reset_password_change_password')

# Note: here are fake translatable strings that allow to translate messages for reset password email content
duplicated_email_subject = l_('Password reset request')
duplicated_email_body = l_('''
We've received a request to reset the password for this account.
Please click this link to reset your password:

%(password_reset_link)s

If you no longer wish to make the above change, or if you did not initiate this request, please disregard and/or delete this e-mail.
''')

#######
#
# INFO - D.A. - 2014-10-31
# The following code is a dirty way to integrate translation for resetpassword tgapp in tracim
# TODO - Integrate these translations into tgapp-resetpassword
#
Example #54
0
 def edit(self, **kw):
     order = Order.query.get(_id=ObjectId(kw.get('order_id', kw.get('_id'))))
     if order.status == 'shipped':
         flash(l_('Is not possible to edit a shipped Order'), 'error')
         return redirect(self.mount_point + '/orders')
     return dict(form=get_edit_order_form(), value=order)
Example #55
0
        """This method showcases how you can use the same controller for a data page and a display page"""
        seishub_stations = "http://10.110.0.134/seismology/station/getList?format=json&network_id=BL"
        req = urllib2.Request(seishub_stations)
        opener = urllib2.build_opener()
        f = opener.open(req)
        json = loads(f.read())
        #return dict(params=kw)
        return dict(params=dict(args=kw, json=json))

    @expose('portal.templates.authentication')
    def auth(self):
        """Display some information about auth* on this application."""
        return dict(page='auth')

    @expose('portal.templates.index')
    @require(predicates.has_permission('manage', msg=l_('Permitido apenas para funcionários')))
    def manage_permission_only(self, **kw):
        """Illustrate how a page for managers only works."""
        return dict(page='managers stuff')

    @expose('portal.templates.index')
    @require(predicates.is_user('editor', msg=l_('Permitido apenas para editor')))
    def editor_user_only(self, **kw):
        """Illustrate how a page exclusive for the editor works."""
        return dict(page='editor stuff')

    @expose('portal.templates.login')
    def login(self, came_from=url('/')):
        """Start the user login."""
        login_counter = request.environ['repoze.who.logins']
        if login_counter > 0:
Example #56
0
    (u'mph', lambda value: format_decimal(value * 2.23693629, format=u'0.0 mph')),
)

lift_units = (
    (u'm/s', lambda value: format_decimal(value, format=u'0.0 m/s')),
    (u'kt', lambda value: format_decimal(value * 1.94384449, format=u'0.0 kt')),
    (u'ft/min', lambda value: format_decimal(value * 196.850394,
                                             format=u'0 ft/min')),
)
altitude_units = (
    (u'm', lambda value: "%d m" % value),
    (u'ft', lambda value: "%d ft" % (value * 3.2808399))
)

unit_presets = (
    (l_("Custom"), {}),

    (l_("European (metric)"),
     {'distance_unit': u'km',
      'speed_unit': u'km/h',
      'lift_unit': u'm/s',
      'altitude_unit': u'm'
      }),

    (l_("British (imperial, distance in km)"),
     {'distance_unit': u'km',
      'speed_unit': u'kt',
      'lift_unit': u'kt',
      'altitude_unit': u'ft'
      }),
Example #57
0
            continue

        fixes = map(lambda x: (x.longitude, x.latitude), contest_trace.locations)
        times = []
        for time in contest_trace.times:
            times.append(flight.takeoff_time.hour * 3600 + flight.takeoff_time.minute * 60 + flight.takeoff_time.second + \
                         (time - flight.takeoff_time).days * 86400 + (time - flight.takeoff_time).seconds)

        contest_traces.append(dict(name=contest['contest_type'] + " " + contest['trace_type'],
                                   turnpoints=encoder.encode(fixes, [0] * len(fixes))['points'],
                                   times=encoder.encodeList(times)))

    return contest_traces

CIRCDIR_NAMES = {None: "",
                 FlightPhase.CD_LEFT: l_("Left"),
                 FlightPhase.CD_MIXED: l_("Mixed"),
                 FlightPhase.CD_RIGHT: l_("Right"),
                 FlightPhase.CD_TOTAL: l_("Total")}

PHASETYPE_NAMES = {None: "",
                   FlightPhase.PT_POWERED: l_("Powered"),
                   FlightPhase.PT_CIRCLING: l_("Circling"),
                   FlightPhase.PT_CRUISE: l_("Cruise")}


def format_phase(phase):
    """Format phase properties to human readable format
    """
    is_circling = phase.phase_type == FlightPhase.PT_CIRCLING
    r = dict(start="%s" % format_time(phase.start_time),
Example #58
0

class NewClubForm(AddRecordForm):
    __base_widget_type__ = BootstrapForm
    __model__ = Club
    __limit_fields__ = ['name']
    __field_widget_args__ = { 'name': dict(label_text=l_('Name')) }

    name = TextField

new_club_form = NewClubForm(DBSession)

user_validator = Schema(chained_validators=(FieldsMatch('password',
                                                        'verify_password',
                                                        messages={'invalidNoMatch':
                                                                  l_('Passwords do not match')}),))


class NewUserForm(AddRecordForm):
    __base_widget_type__ = BootstrapForm
    __model__ = User
    __required_fields__ = ['password']
    __limit_fields__ = ['email_address', 'display_name', 'password', 'verify_password', 'club']
    __base_validator__ = user_validator
    __field_widget_args__ = {
        'email_address': dict(label_text=l_('eMail Address')),
        'display_name': dict(label_text=l_('Name')),
        'club': dict(label_text=l_('Club')),
        'password': dict(label_text=l_('Password')),
        'verify_password': dict(label_text=l_('Verify Password')),
    }
Example #59
0
# coding=utf-8
from __future__ import unicode_literals
from datetime import date, datetime
from itertools import groupby
from bson import ObjectId
from tg import TGController, expose, validate, lurl, redirect, request, tmpl_context, config, flash, predicates
from tg.i18n import lazy_ugettext as l_
import tw2.core as twc
import tw2.forms as twf
from tw2.forms.widgets import BaseLayout
from tgext.ecommerce.lib import get_edit_order_form
from tgext.ecommerce.model import Order


FILTER_FIELDS = [('status_changes.changed_at', l_('date')), ('status', l_('status')), ('user', l_('user'))]


class MaybeDateValidator(twc.Validator):
    date_format = '%d/%m/%Y'

    def _convert_to_python(self, value, state=None):
        if value['field'] == 'status_changes.changed_at':
            try:
                value['filt'] = datetime.strptime(value['filt'], self.date_format)
            except:
                raise twc.ValidationError(l_('Date format must be dd/mm/yyyy'))
        return value

    def _convert_from_python(self, value, state=None):
        if value['field'] == 'status_changes.changed_at':
            value['filt'] = value['filt'].strftime(self.date_format)