def send_concordance_url(auth, plugin_api, recipient, url): user_id = plugin_api.session['user']['id'] user_info = auth.get_user_info(user_id) user_email = user_info['email'] username = user_info['username'] smtp_server = settings.get('mailing', 'smtp_server') sender = settings.get('mailing', 'sender') text = _('KonText user %s has sent a concordance link to you') % (username, ) + ':' text += '\n\n' text += url + '\n\n' text += '\n---------------------\n' text += time.strftime('%d.%m. %Y %H:%M') text += '\n' s = smtplib.SMTP(smtp_server) msg = MIMEText(text, 'plain', 'utf-8') msg['Subject'] = _('KonText concordance link') msg['From'] = sender msg['To'] = recipient msg.add_header('Reply-To', user_email) try: s.sendmail(sender, [recipient], msg.as_string()) ans = True except Exception as ex: logging.getLogger(__name__).warn( 'There were errors sending concordance link via e-mail(s): %s' % (ex,)) ans = False finally: s.quit() return ans
def custom_action_callback(self, action, data): if action == "custom": if data[0] == 'is_probe_opened': self.has_opened = ('Yes' == data[1]) self.trace('Is probe opened...{0}'.format(data[1])) self.trace("Closing probe") self.gcs.send('M402') data = { 'id' : 'is_probe_closed', 'type': 'question', 'msg': _('Is the probe closed?'), 'buttons' : '[Yes][No]' } self.ns.notify('selftest', data) elif data[0] == 'is_probe_closed': self.has_closed = ('Yes' == data[1]) self.trace(_('Is probe closed...{0}').format(data[1])) if self.has_opened and self.has_closed: self.exit(0) else: self.exit(1) else: self.exit(1) else: self.trace(_('unknown action [{0}]').format(action)) self.exit(1)
def DrawLabels(self, dc): tilePair = self.tile_narrow + self.tile_wide x_shift = self.xOffset // 2 y_shift = -self.yOffset if self.editWalls: # wx.SWISS is the sans-serif font dc.SetFont(wx.Font(8, wx.SWISS, wx.NORMAL, wx.NORMAL)) pixelShift = dc.GetTextExtent("8") # try to centre the labels dc.SetTextForeground(self.wall_grid_colour) for row in range(self.num_rows): y = row * tilePair / 2 - pixelShift[1] // 4 + self.yTopOffset dc.DrawText(str(self.flipRow(row)), x_shift, y) for col in range(self.num_cols - 1): x = col * tilePair / 2 + self.tile_narrow / 2 + self.xOffset - pixelShift[0] // 2 dc.DrawText(str(col), x, self.maxHeight + y_shift) x_shift = self.xOffset // 4 y_shift = -self.yOffset // 2 else: dc.SetTextForeground(wx.BLACK) dc.SetFont(wx.Font(10, wx.SWISS, wx.NORMAL, wx.NORMAL)) dc.DrawText(_("Avenue"), 5 * x_shift, self.maxHeight + y_shift // 2) dc.DrawRotatedText(_("Street"), x_shift // 3, self.maxHeight + 3 * y_shift, 90) dc.SetFont(wx.Font(10, wx.SWISS, wx.NORMAL, wx.BOLD)) pixelShift = dc.GetTextExtent("8") # try to centre the labels dc.SetTextForeground(wx.BLACK) for row in range(1, self.num_rows, 2): y = row * tilePair / 2 - pixelShift[1] // 4 + self.yTopOffset dc.DrawText(str(self.flipRow(row) // 2 + 1), x_shift, y) for col in range(1, self.num_cols, 2): x = col * tilePair / 2 + self.tile_narrow / 2 + self.xOffset - pixelShift[0] // 2 dc.DrawText(str(col // 2 + 1), x, self.maxHeight + y_shift)
def __initwidgets__(self): self.header = urwid.Filler(urwid.Text(_('ARA: Query User'),align='center')) self.header = urwid.AttrWrap(self.header, 'reversed') self.idedit = urwid.Filler(urwid.Edit(caption=_(' * Enter ID: '), wrap='clip')) self.idedit.body.set_edit_text(self.default_user) self.btnsearch = urwid.Filler(urwid.Button(_('Search'), self.on_button_clicked)) self.btncancel = urwid.Filler(urwid.Button(_('Cancel'), self.on_button_clicked)) self.buttoncolumn = urwid.Columns([('weight', 60, self.idedit), ('weight', 20, self.btnsearch),('weight',20,self.btncancel)]) self.idtext = urwid.Filler(urwid.Text('')) self.nicktext = urwid.Filler(urwid.Text('')) self.introtext = urwid.Filler(urwid.Text('')) self.sigtext = urwid.Filler(urwid.Text('')) self.lasttext = urwid.Filler(urwid.Text('')) actiontext = urwid.Filler(urwid.Text(_(' * Enter user ID and press [Search]'))) content = [('fixed',1, self.header), ('fixed',1,widget.blanktext), ('fixed',1,self.buttoncolumn), ('fixed',1,widget.dash), ('fixed',1,self.idtext), ('fixed',1,self.nicktext), ('fixed',6,self.introtext), self.sigtext, ('fixed',1,self.lasttext), ('fixed',1,widget.dash), ('fixed',1,actiontext), ] self.mainpile = urwid.Pile(content) if self.default_user != '': self.query_information(self.idedit.body.get_edit_text())
def keypress(self, size, key): if key in self.keymap: key = self.keymap[key] if key.lower() == 'q': self.timer.cancel() self.parent.change_page('user_information', {'session_key': self.session_key}) elif key.lower() == 'm': if self.timer.state: self.infotext.body.set_text( _('(r)efresh (m)onitoring:start (q)uit (Enter) query')) self.timer.cancel() else: self.infotext.body.set_text( _('(r)efresh (m)onitoring:stop (q)uit (Enter) query')) self.timer.start() elif key.lower() == 'r': self.refresh_view() elif key == 'enter': # self.userlist.get_body().get_focus()[0].w.w.widget_list : 현재 활성화된 항목 username = self.userlist.get_body().get_focus( )[0].w.w.widget_list[0].get_text()[0] self.timer.cancel() self.parent.change_page('query_user', { 'session_key': self.session_key, 'default_user': username }) else: self.mainpile.keypress(size, key)
def on_button_clicked(self, button): retvalue = None if button == self.okbutton.body: if self.newpwedit.body.get_edit_text( ) == self.confirmedit.body.get_edit_text(): retvalue, message = self.server.member_manager.modify_password( self.session_key, { 'username': self.server.member_manager.get_info( self.session_key)[1]['username'], 'current_password': self.oldpwedit.body.get_edit_text(), 'new_password': self.newpwedit.body.get_edit_text() }) if retvalue: confirm = widget.Dialog(_('Password changed.'), [_('OK')], ('menu', 'bg', 'bgf'), 30, 5, self) self.overlay = confirm self.parent.run() self.parent.change_page("user_preferences", {'session_key': self.session_key}) else: confirm = widget.Dialog(message, [_('OK')], ('menu', 'bg', 'bgf'), 30, 5, self) self.overlay = confirm self.parent.run() self.overlay = None self.parent.run() elif button == self.cancelbutton.body: self.parent.change_page("user_preferences", {'session_key': self.session_key})
def test_case(args): current_table_tmp = args[1].split() planned_table_tmp = args[2].split() current_table = {} planned_table = {} RETR = 0 for pt in current_table_tmp: tmp = pt.split(':') current_table[tmp[0]] = tmp[1][:-1] for pt in planned_table_tmp: tmp = pt.split(':') meta = {} meta['fs'] = tmp[1] meta['size'] = tmp[2] planned_table['/dev/mmcblk0p' + str(tmp[0])] = meta for pt in planned_table: if pt in current_table: if planned_table[pt]['size'] != '-': tg_size = int(planned_table[pt]['size']) size = int(current_table[pt]) if size < (tg_size - 5) or size > (tg_size + 5): print "Partition", pt, "has the wrong size. Expected ", tg_size, "MB but has", size, "MB" RETR = 1 else: print _("Partition {0} size is correct".format(pt)) else: print _("Partition {0} does not exist".format(pt)) RETR = 1 # Result exit(RETR)
def __initwidgets__(self): self.keymap = { 'up': '', 'down': '', } self.header = urwid.Filler(urwid.Text(_('ARA: Change Password'), align='center')) self.header = urwid.AttrWrap(self.header, 'reversed') self.oldpwedit = urwid.Filler(widget.PasswordEdit(caption=_('Old password:'******'clip')) oldpwdesc = urwid.Filler(urwid.Text(_('Please enter your\nold password'))) self.oldpwcolumn = widget.EasyColumn(self.oldpwedit, oldpwdesc) self.newpwedit = urwid.Filler(widget.PasswordEdit(caption=_('New password:'******'clip')) newpwdesc = urwid.Filler(urwid.Text(_('Minimum password length\nis 4 characters'))) self.newpwcolumn = widget.EasyColumn(self.newpwedit, newpwdesc) self.confirmedit = urwid.Filler(widget.PasswordEdit(caption=_('Confirm\nnew password:'******'clip')) confirmdesc = urwid.Filler(urwid.Text(_('Re-enter your new\npassword'))) self.confirmcolumn = widget.EasyColumn(self.confirmedit, confirmdesc) self.pwpile = urwid.Pile([self.oldpwcolumn, self.newpwcolumn,self.confirmcolumn]) self.okbutton = urwid.Filler(urwid.Button(_('OK'), self.on_button_clicked)) self.cancelbutton = urwid.Filler(urwid.Button(_('Cancel'), self.on_button_clicked)) self.buttoncolumn = widget.EasyColumn(self.okbutton, self.cancelbutton, 50, 50) infotext = urwid.Filler(urwid.Text(_(""" * Press [Enter] to proceed to the next item, [Shift+Enter] - previous item * Press [Tab] to directly jump to OK or Cancel button"""))) content = [('fixed',1,self.header),self.pwpile,('fixed',2,infotext), ('fixed',1,widget.blank),('fixed',1,self.buttoncolumn)] self.mainpile = urwid.Pile(content)
def on_button_clicked(self, button): if button == self.btnokay: retvalue = None title = self.titleedit.body.get_edit_text() body = self.bodyedit.body.get_edit_text() try: title_content = {'title':title, 'content':body} if self.mode == 'modify': result = self.server.article_manager.modify(self.session_key, self.board_name, self.article_id, **title_content) elif self.mode == 'reply': result = self.server.article_manager.write_reply(self.session_key, self.board_name, self.article_id, **title_content) elif self.mode == 'post': result = self.server.article_manager.write_article(self.session_key, self.board_name, **title_content) else: return confirm = widget.Dialog(_('Article posted.'), [_('OK')], ('menu', 'bg', 'bgf'), 30, 5, self) self.overlay = confirm self.parent.run() if confirm.b_pressed == _('OK'): self.parent.change_page("list_article",{'session_key':self.session_key, 'board_name':self.board_name}) except: #self.overlay = None #self.parent.run() pass elif button == self.btncancel: self.parent.change_page("list_article",{'session_key':self.session_key, 'board_name':self.board_name}) elif button == self.btnhelp: # TODO: 편집 도움말 pass elif button == self.btnpreview: # TODO: 미리보기 pass else: assert("Call for undefined button")
def set_user_password(self, request): with plugins.runtime.AUTH as auth: curr_passwd = request.form['curr_passwd'] new_passwd = request.form['new_passwd'] new_passwd2 = request.form['new_passwd2'] fields = dict(curr_passwd=True, new_passwd=True, new_passwd2=True) ans = dict(fields=fields, messages=[]) if not self._uses_internal_user_pages(): raise UserActionException(_('This function is disabled.')) logged_in = auth.validate_user( self._plugin_api, self.session_get('user', 'user'), curr_passwd) if self._is_anonymous_id(logged_in['id']): fields['curr_passwd'] = False ans['messages'].append(_('Invalid user or password')) return ans if new_passwd != new_passwd2: fields['new_passwd'] = False fields['new_passwd2'] = False ans['messages'].append(_('New password and its confirmation do not match.')) return ans if not auth.validate_new_password(new_passwd): ans['messages'].append(auth.get_required_password_properties()) fields['new_passwd'] = False fields['new_passwd2'] = False return ans auth.update_user_password(self.session_get('user', 'id'), new_passwd) return ans
def ChangeLanguage(self): # update strings in dict self.running_dict = { '0': _("Program not running"), '1': _("Program is running"), '2': _("Program paused") } # program if self.fields_info['filename'] != '': self.prog_text = _( "Program File: %s") % self.fields_info['filename'] else: self.prog_text = _("No program loaded") # running status self.run_text = self.running_dict[self.fields_info['running']] # beepers carried if self.fields_info['robot'] == self.no_robot: self.beeper_text = _("No robot in this world") elif self.fields_info['beepers'] < 2: self.beeper_text = _( "Robot has %s beeper") % self.fields_info['beepers'] else: self.beeper_text = _( "Robot has %s beepers") % self.fields_info['beepers'] # world file if self.fields_info['world'] != '': self.world_text = _("World file: %s") % self.fields_info['world'] else: self.world_text = _("Default world")
def DrawLabels(self, dc): tilePair = self.tile_narrow + self.tile_wide x_shift = self.xOffset // 2 y_shift = -self.yOffset if self.editWalls: # wx.SWISS is the sans-serif font dc.SetFont(wx.Font(8, wx.SWISS, wx.NORMAL, wx.NORMAL)) pixelShift = dc.GetTextExtent("8") # try to centre the labels dc.SetTextForeground(self.wall_grid_colour) for row in range(self.num_rows): y = row * tilePair / 2 - pixelShift[1] // 4 + self.yTopOffset dc.DrawText(str(self.flipRow(row)), x_shift, y) for col in range(self.num_cols - 1): x = (col * tilePair / 2 + self.tile_narrow / 2 + self.xOffset - pixelShift[0] // 2) dc.DrawText(str(col), x, self.maxHeight + y_shift) x_shift = self.xOffset // 4 y_shift = -self.yOffset // 2 else: dc.SetTextForeground(wx.BLACK) dc.SetFont(wx.Font(10, wx.SWISS, wx.NORMAL, wx.NORMAL)) dc.DrawText(_("Avenue"), 5 * x_shift, self.maxHeight + y_shift // 2) dc.DrawRotatedText(_("Street"), x_shift // 3, self.maxHeight + 3 * y_shift, 90) dc.SetFont(wx.Font(10, wx.SWISS, wx.NORMAL, wx.BOLD)) pixelShift = dc.GetTextExtent("8") # try to centre the labels dc.SetTextForeground(wx.BLACK) for row in range(1, self.num_rows, 2): y = row * tilePair / 2 - pixelShift[1] // 4 + self.yTopOffset dc.DrawText(str(self.flipRow(row) // 2 + 1), x_shift, y) for col in range(1, self.num_cols, 2): x = (col * tilePair / 2 + self.tile_narrow / 2 + self.xOffset - pixelShift[0] // 2) dc.DrawText(str(col // 2 + 1), x, self.maxHeight + y_shift)
def _create_subcorpus(self, request): """ req. arguments: subcname -- name of new subcorpus create -- bool, sets whether to create new subcorpus cql -- custom within condition """ subcname = request.form['subcname'] within_json = request.form.get('within_json') raw_cql = request.form.get('cql') corp_encoding = self._corp().get_conf('ENCODING') if raw_cql: tt_query = () within_cql = raw_cql full_cql = 'aword,[] %s' % raw_cql imp_cql = (full_cql,) elif within_json: # user entered a subcorpus query manually tt_query = () within_cql = self._deserialize_custom_within(json.loads(within_json)) full_cql = 'aword,[] %s' % within_cql imp_cql = (full_cql,) else: tt_query = TextTypeCollector(self._corp(), request).get_query() full_cql = ' within '.join(['<%s %s />' % item for item in tt_query]) full_cql = 'aword,[] within %s' % full_cql full_cql = import_string(full_cql, from_encoding=corp_encoding) imp_cql = (full_cql,) basecorpname = self.args.corpname.split(':')[0] if not subcname: raise UserActionException(_('No subcorpus name specified!')) path = self.prepare_subc_path(basecorpname, subcname) if type(path) == unicode: path = path.encode('utf-8') if len(tt_query) == 1: result = corplib.create_subcorpus(path, self._corp(), tt_query[0][0], tt_query[0][1]) elif len(tt_query) > 1 or within_cql: conc = conclib.get_conc(self._corp(), self._session_get('user', 'user'), q=imp_cql) conc.sync() struct = self._corp().get_struct(tt_query[0][0]) if len(tt_query) == 1 else None result = corplib.subcorpus_from_conc(path, conc, struct) else: raise UserActionException(_('Nothing specified!')) if result: if plugins.has_plugin('subc_restore'): try: plugins.get('subc_restore').store_query(user_id=self._session_get('user', 'id'), corpname=self.args.corpname, subcname=subcname, cql=full_cql.split('[]')[-1]) except Exception as e: logging.getLogger(__name__).warning('Failed to store subcorpus query: %s' % e) self.add_system_message('warning', _('Subcorpus created but there was a problem saving a backup copy.')) return {} else: raise ConcError(_('Empty subcorpus!'))
def _send_mail(self, plugin_api, body, browser_info): user_info = self._auth.get_user_info(plugin_api) user_email = user_info['email'] username = user_info['username'] text = _('KonText feedback from user {0}').format(username) + ':' text += '\n\n' text += body text += '\n' text += '\n{0}\n'.format(40 * '-') text += _('browser info') + ':\n' text += self._dump_browser_info(browser_info) text += '\n{0}\n'.format(40 * '-') text += '\n' s = smtplib.SMTP(self._smtp_server) msg = MIMEText(text, 'plain', 'utf-8') msg['Subject'] = _('KonText feedback from user {0} for {1}').format( username, datetime.now().isoformat().rsplit('.')[0]) msg['From'] = self._mail_sender msg['To'] = ', '.join(self._mail_recipients) msg.add_header('Reply-To', user_email) try: s.sendmail(self._mail_sender, self._mail_recipients, msg.as_string()) ans = True except Exception as ex: logging.getLogger(__name__).warn( 'There were errors sending an issue report link via e-mail(s): %s' % (ex,)) ans = False finally: s.quit() return ans
def keypress(self, size, key): if key in self.keymap: key = self.keymap[key] if key == "enter" and not self.session_key == 'guest': # self.boardlist.get_body().get_focus()[0].w.w.widget_list : 현재 활성화된 항목 article_id = self.articlelist.get_body().get_focus()[0].w.w.widget_list[0].get_text()[0] if article_id != '': article_id = int(article_id) self.parent.change_page("read_article", {'session_key':self.session_key, 'board_name':self.board_name, 'article_id':article_id}) elif key == 'w' and not self.readonly and not self.session_key == 'guest': self.parent.change_page('post_article', {'session_key':self.session_key, 'board_name':self.board_name, 'mode':'post', 'article_id':''}) elif key == 'q': self.parent.change_page("main", {'session_key':self.session_key}) elif key == 'f': if self.session_key == 'guest': return input_dialog = widget.Dialog(_('Search term:'), [_('OK'), _('Cancel')], ('menu','bg','bgf'), 30, 7, self, 'Text') self.overlay = input_dialog self.parent.run() if input_dialog.b_pressed == _('OK'): search_term = input_dialog.edit_text else: search_term = '' if search_term.strip() == '': return listbody = urwid.ListBox(ArticleSearchWalker(self.session_key, self.board_name, self.make_widget, False, {'title':search_term})) self.articlelist.set_body(listbody) self.overlay = None self.parent.run() else: self.mainpile.keypress(size, key)
def process_file(file_text): if imp_use_as.search(file_text): # look for "import useful as ..." syn = imp_use_as.findall(file_text) added_text, safe_import_flag = import_useful_as(syn[0]) file_text = comment_import.sub('#import ', file_text) elif imp_use.search(file_text): # perhaps the "as ..." part is missing added_text, safe_import_flag = import_useful() file_text = comment_import.sub('#import ', file_text) elif from_use_imp_star.search(file_text): added_text, safe_import_flag = from_useful_import_star() file_text = comment_from.sub('#from ', file_text) elif from_use_imp_as.search(file_text): names = from_use_imp_as.findall(file_text) name = names[0][0] syn = names[0][1] added_text, safe_import_flag = from_useful_import_as(name, syn) file_text = comment_from.sub('#from ', file_text) elif from_use_imp_names.search(file_text): names = from_use_imp_names.findall(file_text) added_text, safe_import_flag = from_useful_import_names(names[0][0]) file_text = comment_from.sub('#from ', file_text) elif import_misuse.search(file_text): safe_import_flag = False file_text = '' # remove it all added_text = '# import keyword used improperly' print _('import keyword used improperly') else: added_text = '' safe_import_flag = True # nothing found added_text += file_text return added_text, safe_import_flag
def notify_guest(self): confirm = widget.Dialog(_('Not available in guest mode.'), [_('Ok')], ('menu', 'bg', 'bgf'), 30, 6, self) self.overlay = confirm self.parent.run() self.overlay = None self.parent.run()
def __initwidgets__(self): self.keymap = { 'j': 'down', 'k': 'up', } self.header = urwid.Filler( urwid.Text(_('ARA: Main Menu'), align='center')) self.header = urwid.AttrWrap(self.header, 'reversed') menuitems = [ widget.Item(" * " + w + "\n", None, 'selected') for w in self.menu ] self.menulist = urwid.ListBox(urwid.SimpleListWalker(menuitems)) tbtext = urwid.Filler(urwid.Text(_('Today Best'), align='center')) self.tblist_raw = self.server.article_manager.get_today_best_list(5) tbitems = [ "%(title)s (%(nickname)s, %(date)s)" % { "title": text.title, 'nickname': text.author_nickname, 'date': date.fromtimestamp(text.date).strftime("%Y/%m/%d") } for text in self.tblist_raw ] tbitems = [widget.Item(w, None, 'selected') for w in tbitems] self.tblist = urwid.ListBox(urwid.SimpleListWalker(tbitems)) self.todaybest = urwid.Pile([('fixed', 1, tbtext), self.tblist]) wbtext = urwid.Filler(urwid.Text(_('Weekly Best'), align='center')) self.wblist_raw = self.server.article_manager.get_weekly_best_list(5) wbitems = [ "%(title)s (%(nickname)s, %(date)s)" % { "title": text.title, 'nickname': text.author_nickname, 'date': date.fromtimestamp(text.date).strftime("%Y/%m/%d") } for text in self.wblist_raw ] wbitems = [widget.Item(w, None, 'selected') for w in wbitems] self.wblist = urwid.ListBox(urwid.SimpleListWalker(wbitems)) self.weeklybest = urwid.Pile([('fixed', 1, wbtext), self.wblist]) self.bests = urwid.Pile([self.todaybest, self.weeklybest]) self.copyrightnotice = urwid.Filler( urwid.Text( _(""" * Press [Tab] to jump between menu, today best, weekly best ARAra Release 1.0 Copyright (C) 2008, SPARCS""" ))) self.maincolumn = urwid.Columns([('weight', 40, self.menulist), ('weight', 60, self.bests)]) content = [('fixed', 1, self.header), ('fixed', 1, widget.blanktext), self.maincolumn, ('fixed', 1, widget.dash), ('fixed', 2, self.copyrightnotice)] self.mainpile = urwid.Pile(content) self.keymap = { "left": "", "right": "", "j": "down", "k": "up", }
def UpdateFields(self, *args): field, info = args[0].data[0] if field == self.notebook_new_page: if info != 1: # Code and Learn page self.ClearFields() return elif field == self.beeper_field: self.fields_info['beepers'] = info if info == self.no_robot: self.beeper_text = _("No robot in this world") self.fields_info['robot'] = self.no_robot else: self.fields_info['robot'] = self.no_robot+1 if info < 2: self.beeper_text = _("Robot has %s beeper") % info else: self.beeper_text = _("Robot has %s beepers") % info elif field == self.running_field: self.run_text = info for n in ['0', '1', '2']: if info == self.running_dict[n]: self.fields_info['running'] = n elif field == self.user_field: self.user_text = _("User ID: %s") % info self.fields_info['user'] = info elif field == self.problem_field: self.prob_text = _("Problem: %s") % info self.fields_info['problem'] = info self.WriteFields()
def __initwidgets__(self): self.header = urwid.Filler(urwid.Text(_('ARA: Change Introduction & Signature'), align='center')) self.header = urwid.AttrWrap(self.header, 'reversed') self.myinfo = self.server.member_manager.get_info(self.session_key) sigtext = urwid.Filler(urwid.Text(_('Signature'))) self.sigedit = urwid.Filler(urwid.Edit(wrap='clip')) introtext = urwid.Filler(urwid.Text(_('Introduction'))) self.introedit = urwid.Filler(urwid.Edit(wrap='clip')) self.btnokay = urwid.Button(_('OK'), self.on_button_clicked) self.btncancel = urwid.Button(_('Cancel'), self.on_button_clicked) self.bottomcolumn = urwid.Filler(urwid.Columns([self.btnokay,self.btncancel])) content = [('fixed',1, self.header), ('fixed',1,sigtext), ('fixed',1,widget.dash), self.sigedit, ('fixed',1,widget.dash), ('fixed',1,introtext), ('fixed',1,widget.dash), self.introedit, ('fixed',1,widget.dash), ('fixed',1,self.bottomcolumn)] self.mainpile = urwid.Pile(content) self.set_sig_intro()
def keypress(self, size, key): mainpile_focus = self.mainpile.get_focus() if mainpile_focus == self.boardlist: if key == "enter": # self.boardlist.get_body().get_focus()[0].w.w.widget_list : 현재 활성화된 항목 boardname = self.boardlist.get_body().get_focus( )[0].w.w.widget_list[0].get_text()[0] self.parent.change_page("list_article", { 'session_key': self.session_key, 'board_name': boardname }) else: self.mainpile.keypress(size, key) elif mainpile_focus == self.boardnameedit: if key == 'enter': boardname = self.boardnameedit.body.get_edit_text() try: status = self.server.board_manager.get_board(boardname) self.parent.change_page("list_article", { 'session_key': self.session_key, 'board_name': boardname }) except InvalidOperation, e: confirm = widget.Dialog( _('No such board. Returning to main menu.'), [_('Ok')], ('menu', 'bg', 'bgf'), 30, 6, self) self.overlay = confirm self.parent.run() self.parent.change_page('main', {'session_key': self.session_key}) else: self.mainpile.keypress(size, key)
def user_password(self, request): auth = plugins.get('auth') try: curr_passwd = request.form['curr_passwd'] new_passwd = request.form['new_passwd'] new_passwd2 = request.form['new_passwd2'] if not self._uses_internal_user_pages(): raise UserActionException(_('This function is disabled.')) logged_in = auth.validate_user(self._session_get('user', 'user'), curr_passwd) if self._is_anonymous_id(logged_in['id']): raise UserActionException(_('Invalid user or password')) if new_passwd != new_passwd2: raise UserActionException( _('New password and its confirmation do not match.')) if not auth.validate_new_password(new_passwd): raise UserActionException( auth.get_required_password_properties()) auth.update_user_password(self._session_get('user', 'id'), new_passwd) except UserActionException as e: self.add_system_message('error', e) return {}
def set_user_password(self, request): with plugins.runtime.AUTH as auth: curr_passwd = request.form['curr_passwd'] new_passwd = request.form['new_passwd'] new_passwd2 = request.form['new_passwd2'] fields = dict(curr_passwd=True, new_passwd=True, new_passwd2=True) ans = dict(fields=fields, messages=[]) if not self._uses_internal_user_pages(): raise UserActionException(_('This function is disabled.')) logged_in = auth.validate_user(self._plugin_api, self.session_get('user', 'user'), curr_passwd) if self._is_anonymous_id(logged_in['id']): fields['curr_passwd'] = False ans['messages'].append(_('Invalid user or password')) return ans if new_passwd != new_passwd2: fields['new_passwd'] = False fields['new_passwd2'] = False ans['messages'].append( _('New password and its confirmation do not match.')) return ans if not auth.validate_new_password(new_passwd): ans['messages'].append(auth.get_required_password_properties()) fields['new_passwd'] = False fields['new_passwd2'] = False return ans auth.update_user_password(self.session_get('user', 'id'), new_passwd) return ans
def __initwidgets__(self): self.header = urwid.Filler( urwid.Text(_('ARA: User Preferences'), align='center')) self.header = urwid.AttrWrap(self.header, 'reversed') menuitems = [ widget.Item(" * " + w + "\n", None, 'selected') for w in self.menu ] self.menulist = urwid.ListBox(urwid.SimpleListWalker(menuitems)) menudescs = [widget.Item(w, None, 'selected') for w in self.menudesc] self.menudesclist = urwid.ListBox(urwid.SimpleListWalker(menudescs)) self.maincolumn = urwid.Columns([('weight', 40, self.menulist), ('weight', 60, self.menudesclist)]) infotext = urwid.Filler( urwid.Text(_(' * Use [Tab] or arrow key to move each items'))) content = [ ('fixed', 1, self.header), ('fixed', 1, widget.blanktext), self.maincolumn, ('fixed', 1, widget.dash), ('fixed', 1, infotext), ] self.mainpile = urwid.Pile(content)
def construct_confirm_close(self, window, reqtype): """Create a confirmation dialog for closing things""" dialog = gtk.Dialog(_('Close?'), window, gtk.DIALOG_MODAL) dialog.set_has_separator(False) dialog.set_resizable(False) dialog.add_button(gtk.STOCK_CANCEL, gtk.RESPONSE_REJECT) c_all = dialog.add_button(gtk.STOCK_CLOSE, gtk.RESPONSE_ACCEPT) c_all.get_children()[0].get_children()[0].get_children()[1].set_label( _('Close _Terminals')) primary = gtk.Label(_('<big><b>Close multiple terminals?</b></big>')) primary.set_use_markup(True) primary.set_alignment(0, 0.5) secondary = gtk.Label( _('This %s has several terminals open. Closing \ the %s will also close all terminals within it.') % (reqtype, reqtype)) secondary.set_line_wrap(True) labels = gtk.VBox() labels.pack_start(primary, False, False, 6) labels.pack_start(secondary, False, False, 6) image = gtk.image_new_from_stock(gtk.STOCK_DIALOG_WARNING, gtk.ICON_SIZE_DIALOG) image.set_alignment(0.5, 0) box = gtk.HBox() box.pack_start(image, False, False, 6) box.pack_start(labels, False, False, 6) dialog.vbox.pack_start(box, False, False, 12) dialog.show_all() return (dialog)
def set_user_password(self, request): with plugins.runtime.AUTH as auth: curr_passwd = request.form['curr_passwd'] new_passwd = request.form['new_passwd'] new_passwd2 = request.form['new_passwd2'] if not self._uses_internal_user_pages(): raise UserActionException(_('This function is disabled.')) logged_in = auth.validate_user(self._plugin_api, self.session_get('user', 'user'), curr_passwd) if self._is_anonymous_id(logged_in['id']): raise UserActionException(_('Invalid user or password')) if new_passwd != new_passwd2: raise UserActionException( _('New password and its confirmation do not match.')) if not auth.validate_new_password(new_passwd): raise UserActionException( auth.get_required_password_properties()) auth.update_user_password(self.session_get('user', 'id'), new_passwd) return {}
def get_contents(self, plugin_api, return_url): tpl_path = self.get_template(plugin_api.user_lang) with open(tpl_path, mode='rb') as fin: html = fin.read().decode('utf-8') if not plugin_api.user_is_anonymous: msgs = dict(fullname=plugin_api.session.get( 'user', 'fullname'), logout_url='', logout_msg=_('logout')) login_html = '%(fullname)s (<a href="%(logout_url)s">%(logout_msg)s</a>)' % msgs else: msgs = dict(fullname=_('anonymous'), login_url='', login_msg=_('login')) login_html = ( '%(fullname)s (<a href="%(login_url)s" class ="signon" onclick="return false;">' '%(login_msg)s</a>)') % msgs contents = html + ( '<ul id="localization-bar" class="navbar-left pull-left list-unstyled" ' + 'style="position: absolute; top: 0px;">' + '</ul>' + '<!-- AUTH BAR -->' + '<div class="lindat-auth-bar">' + '<span class="user">%(user_label)s: %(login_html)s</span>' + '</div>' + '<!-- AUTH BAR END -->') % dict(user_label=_('User'), login_html=login_html) return contents
def UpdateFields(self, *args): field, info = args[0].data[0] if field == self.notebook_new_page: if info != 1: # Code and Learn page self.ClearFields() return elif field == self.beeper_field: self.fields_info['beepers'] = info if info == self.no_robot: self.beeper_text = _("No robot in this world") self.fields_info['robot'] = self.no_robot else: self.fields_info['robot'] = self.no_robot + 1 if info < 2: self.beeper_text = _("Robot has %s beeper") % info else: self.beeper_text = _("Robot has %s beepers") % info elif field == self.running_field: self.run_text = info for n in ['0', '1', '2']: if info == self.running_dict[n]: self.fields_info['running'] = n elif field == self.world_field: self.world_text = _("World file: %s") % info self.fields_info['world'] = info elif field == self.program_field: self.prog_text = _("Program File: %s") % info self.fields_info['program'] = info self.WriteFields()
def get_conc_desc(corpus, q=None, subchash=None, translate=True): """ arguments: corpus -- an extended version (corpname attribute must be present) of manatee.Corpus object as provided by corplib.CorpusManager.get_Corpus q -- tuple/list of query elements subchash -- hashed subcorpus name as provided by corplib.CorpusManager.get_Corpus translate -- if True then all the messages are translated according to the current thread's locale information """ if q is None: q = [] if translate: _t = lambda s: _(s) else: _t = lambda s: s desctext = { "q": _t("Query"), "a": _t("Query"), "r": _t("Random sample"), "s": _t("Sort"), "f": _t("Shuffle"), "n": _t("Negative filter"), "N": _t("Negative filter (excluding KWIC)"), "p": _t("Positive filter"), "P": _t("Positive filter (excluding KWIC)"), "w": _t("Word sketch item"), "t": _t("Word sketch texttype item"), "e": _t("GDEX"), "x": _t("Switch KWIC"), } desc = [] cache_map = cache_factory.get_mapping(corpus) q = tuple(q) for i in range(len(q)): cache_val = cache_map[(subchash, q[: i + 1])] if cache_val: size = cache_val[1] else: size = None opid = q[i][0] args = q[i][1:] url1 = [("q", qi) for qi in q[:i]] url2 = [("q", qi) for qi in q[: i + 1]] op = desctext.get(opid) if opid == "s" and args[0] != "*" and i > 0: sortopt = {"-1<0": "left context", "0<0~": "node", "1>0~": "right context"} sortattrs = args.split() if len(sortattrs) > 2: op = "Multilevel Sort" args = "%s in %s" % (sortattrs[0].split("/")[0], sortopt.get(sortattrs[1][:4], sortattrs[1])) url1.append(("skey", {"-1": "lc", "0<": "kw", "1>": "rc"}.get(sortattrs[1][:2], ""))) elif opid == "f": size = "" args = _("enabled") if op: desc.append((op, args, url1, url2, size)) return desc
def _create_ui(self): """creates UI """ frac = float(self._connection['quality'])/ \ float(self._connection['quality_max']) per = self._connection['quality'] self._quality_bar = gtk.ProgressBar() self._quality_bar.set_fraction(frac) self._quality_bar.set_text(_("%d%%") % int(per)) self._name_txt = gtk.Label("") self._name_txt.set_markup("<span color='blue'>" + self._connection['remote'] + "</span>") self._name_txt.set_alignment(0.0 , 0.5) self._encrypt_txt = gtk.Label(self._type) self._encrypt_txt.set_alignment(0.0 , 0.5) self._connect_btn = gtk.Button(_("Connect")) self.set_row_spacings(5) self.set_col_spacings(5) self.attach(self._quality_bar, 0, 1, 0, 2, gtk.SHRINK, gtk.SHRINK) self.attach(self._name_txt, 1, 2, 0, 1, gtk.EXPAND|gtk.FILL, gtk.SHRINK) self.attach(self._encrypt_txt, 1, 2, 1, 2, gtk.EXPAND|gtk.FILL, gtk.SHRINK) self.attach(self._connect_btn, 2, 3, 0, 2, gtk.SHRINK, gtk.SHRINK) self.attach(gtk.HSeparator(), 0, 3, 2, 3, gtk.FILL, gtk.SHRINK)
def send_concordance_url(auth, plugin_api, recipient, url): user_id = plugin_api.session['user']['id'] user_info = auth.get_user_info(user_id) user_email = user_info['email'] username = user_info['username'] smtp_server = settings.get('mailing', 'smtp_server') sender = settings.get('mailing', 'sender') text = _('KonText user %s has sent a concordance link to you') % ( username, ) + ':' text += '\n\n' text += url + '\n\n' text += '\n---------------------\n' text += time.strftime('%d.%m. %Y %H:%M') text += '\n' s = smtplib.SMTP(smtp_server) msg = MIMEText(text, 'plain', 'utf-8') msg['Subject'] = _('KonText concordance link') msg['From'] = sender msg['To'] = recipient msg.add_header('Reply-To', user_email) try: s.sendmail(sender, [recipient], msg.as_string()) ans = True except Exception as ex: logging.getLogger(__name__).warn( 'There were errors sending concordance link via e-mail(s): %s' % (ex, )) ans = False finally: s.quit() return ans
def _play(soundfile): if platform.startswith('win'): from winsound import PlaySound, SND_FILENAME, SND_ASYNC PlaySound(soundfile, SND_FILENAME|SND_ASYNC) elif 'linux' in platform: from wave import open as waveOpen from ossaudiodev import open as ossOpen s = waveOpen(soundfile,'rb') (nc,sw,fr,nf,comptype, compname) = s.getparams( ) try: from ossaudiodev import AFMT_S16_NE except ImportError: if byteorder == "little": AFMT_S16_NE = ossaudiodev.AFMT_S16_LE else: AFMT_S16_NE = ossaudiodev.AFMT_S16_BE dsp = None try: dsp = ossOpen('/dev/dsp','w') dsp.setparameters(AFMT_S16_NE, nc, fr) data = s.readframes(nf) s.close() dsp.write(data) except IOError: print _("Audio device is busy.") finally: if dsp: dsp.close()
def saveFile(self, event): user_code = self.PythonEditor.GetText() user_code = fixLineEnding(user_code) self.filename = dialogs.checkedSaveDialog(user_code, _("Save Python file as"), _("Python files (*.py)|*.py| All files (*.*)|*.*"), self.filename, os.getcwd())
def viewattrs(self): """ attrs, refs, structs form """ from collections import defaultdict if len(self.args.q) == 0: self.disabled_menu_items = (MainMenu.SAVE, MainMenu.CONCORDANCE, MainMenu.VIEW, MainMenu.FILTER, MainMenu.FREQUENCY, MainMenu.COLLOCATIONS) out = {} if self.args.maincorp: corp = corplib.manatee.Corpus(self.args.maincorp) out['AttrList'] = [{'label': corp.get_conf(n + '.LABEL') or n, 'n': n} for n in corp.get_conf('ATTRLIST').split(',') if n] else: corp = self._corp() out['fixed_attr'] = 'word' availstruct = corp.get_conf('STRUCTLIST').split(',') structlist = self.args.structs.split(',') out['Availstructs'] = [{'n': n, 'sel': 'selected' if n in structlist else '', 'label': corp.get_conf(n + '.LABEL')} for n in availstruct if n and n != '#'] availref = corp.get_conf('STRUCTATTRLIST').split(',') structattrs = defaultdict(list) reflist = self.args.refs.split(',') if self.args.refs else [] def ref_is_allowed(r): return r and r not in ( '#', plugins.get('corparch').get_corpus_info(self.args.corpname).get('speech_segment')) for item in availref: if ref_is_allowed(item): k, v = item.split('.', 1) structattrs[k].append(v) out['Availrefs'] = [{ 'n': '#', 'label': _('Token number'), 'sel': 'selected' if '#' in reflist else '' }] + \ [{ 'n': '=' + n, 'sel': 'selected' if ('=' + n) in reflist else '', 'label': (corp.get_conf(n + '.LABEL') or n) } for n in availref if ref_is_allowed(n) ] doc = corp.get_conf('DOCSTRUCTURE') if doc in availstruct: out['Availrefs'].insert(1, {'n': doc, 'label': _('Document number'), 'sel': (doc in reflist and 'selected' or '')}) out['newctxsize'] = self.args.kwicleftctx[1:] out['structattrs'] = structattrs out['curr_structattrs'] = self.args.structattrs out['query_overview'] = self.concdesc_json().get('Desc', []) return out
def __init__(self): """Class initialiser""" GObject.GObject.__init__(self) self.config = Config() self.get_style_context().add_class("terminator-terminal-searchbar") # Search text self.entry = Gtk.Entry() self.entry.set_activates_default(True) self.entry.show() self.entry.connect('activate', self.do_search) self.entry.connect('key-press-event', self.search_keypress) # Label label = Gtk.Label(label=_('Search:')) label.show() # Close Button close = Gtk.Button() close.set_relief(Gtk.ReliefStyle.NONE) close.set_focus_on_click(False) icon = Gtk.Image() icon.set_from_stock(Gtk.STOCK_CLOSE, Gtk.IconSize.MENU) close.add(icon) close.set_name('terminator-search-close-button') if hasattr(close, 'set_tooltip_text'): close.set_tooltip_text(_('Close Search bar')) close.connect('clicked', self.end_search) close.show_all() # Next Button self.next = Gtk.Button(_('Next')) self.next.show() self.next.set_sensitive(False) self.next.connect('clicked', self.next_search) # Previous Button self.prev = Gtk.Button(_('Prev')) self.prev.show() self.prev.set_sensitive(False) self.prev.connect('clicked', self.prev_search) # Wrap checkbox self.wrap = Gtk.CheckButton(_('Wrap')) self.wrap.show() self.wrap.set_sensitive(True) self.wrap.connect('toggled', self.wrap_toggled) self.pack_start(label, False, True, 0) self.pack_start(self.entry, True, True, 0) self.pack_start(self.prev, False, False, 0) self.pack_start(self.next, False, False, 0) self.pack_start(self.wrap, False, False, 0) self.pack_end(close, False, False, 0) self.hide() self.set_no_show_all(True)
def viewattrs(self): """ attrs, refs, structs form """ from collections import defaultdict if len(self.args.q) == 0: self.disabled_menu_items = (MainMenu.SAVE, MainMenu.CONCORDANCE, MainMenu.VIEW, MainMenu.FILTER, MainMenu.FREQUENCY, MainMenu.COLLOCATIONS) out = {} if self.args.maincorp: corp = corplib.manatee.Corpus(self.args.maincorp) else: corp = self.corp out['AttrList'] = [{'label': corp.get_conf(n + '.LABEL') or n, 'n': n} for n in corp.get_conf('ATTRLIST').split(',') if n] out['fixed_attr'] = 'word' out['attr_allpos'] = self.args.attr_allpos out['attr_vmode'] = self.args.attr_vmode availstruct = corp.get_conf('STRUCTLIST').split(',') structlist = set(self.args.structs.split(',')).union( set([x.split('.')[0] for x in self.args.structattrs])) out['Availstructs'] = [{'n': n, 'sel': 'selected' if n in structlist else '', 'label': corp.get_conf(n + '.LABEL')} for n in availstruct if n and n != '#'] availref = corp.get_conf('STRUCTATTRLIST').split(',') structattrs = defaultdict(list) reflist = self.args.refs.split(',') if self.args.refs else [] def ref_is_allowed(r): return r and r not in ( '#', self.get_corpus_info(self.args.corpname).get('speech_segment')) for item in availref: if ref_is_allowed(item): k, v = item.split('.', 1) structattrs[k].append(v) out['Availrefs'] = [dict(n='#', label=_('Token number'), sel='selected' if '#' in reflist else '')] for n in availref: if ref_is_allowed(n): out['Availrefs'].append(dict(n='=' + n, sel='selected' if ('=' + n) in reflist else '', label=(corp.get_conf(n + '.LABEL') or n))) doc = corp.get_conf('DOCSTRUCTURE') if doc in availstruct: out['Availrefs'].insert(1, dict(n=doc, label=_('Document number'), sel=(doc in reflist and 'selected' or ''))) out['newctxsize'] = self.args.kwicleftctx[1:] out['structattrs'] = structattrs out['curr_structattrs'] = self.args.structattrs out['query_overview'] = self.concdesc_json().get('Desc', []) out['CurrentAttrs'] = self.args.attrs.split(',') out['use_conc_toolbar'] = settings.get_bool('global', 'use_conc_toolbar') return out
def setup_view(self): self.store = gtk.ListStore(str, str) column = lambda x, y:gtk.TreeViewColumn(x, gtk.CellRendererText(), text=y) self.view = gtk.TreeView(self.store) self.view.append_column(column(_("Name"), 0)) self.view.append_column(column(_("Quality"), 1))
def run_with(self, event): '''Runs the user code with arguments passed to script''' dlg = wx.TextEntryDialog(self, _("Enter arguments list"), _("Running script with arguments"), self.arguments) if dlg.ShowModal() == wx.ID_OK: self.arguments = dlg.GetValue() dlg.Destroy() self.run("fake event")
def openFile(self, event): self.filename = dialogs.openDialog(_("Choose a file"), _("Python files (*.py)|*.py| All files (*.*)|*.*"), "", os.getcwd()) if self.filename != "": user_code = open(self.filename, 'r').read() self.PythonEditor.SetText(user_code)
def OnLoadFile(self, event): openedFileName = dialogs.openDialog(_("Choose a file"), _("html files (*.htm*)|*.htm*| All files (*.*)|*.*"), "", self.lessons_dir) if openedFileName != "": path = openedFileName self.html.LoadPage(path)
def set_delay(self, delay): '''Sets the delay value between robot actions.''' if delay >= 0 and delay <= 10: self._delay = delay else: mesg = _("""Setting delay failed. Accepted values are between 0 and 10.""") dialogs.messageDialog(mesg, _("Error"))
def pos_ctxs(min_hitlen, max_hitlen, max_ctx=3): ctxs = [{"n": _("%iL") % -c, "ctx": "%i<0" % c} for c in range(-max_ctx, 0)] if max_hitlen == 1: ctxs.append({"n": _("Node"), "ctx": "0~0>0"}) else: ctxs.extend([{"n": "Node %i" % c, "ctx": "%i<0" % c} for c in range(1, max_hitlen + 1)]) ctxs.extend([{"n": _("%iR") % c, "ctx": "%i>0" % c} for c in range(1, max_ctx + 1)]) return ctxs
def process(self, subreddit): try: _remove_subreddit(subreddit) directory.refresh() except InvalidSubreddit: dlg = Dialog() dlg.ok(_('Error'), _('There is not such subreddit.')) raise self.AskAgain
def OnLoadFile(self, event): openedFileName = dialogs.openDialog( _("Choose a file"), _("html files (*.htm*)|*.htm*| All files (*.*)|*.*"), "", self.lessons_dir) if openedFileName != "": path = openedFileName self.html.LoadPage(path)
def goToLine(self, event): dlg = wx.TextEntryDialog(self, _("Enter line number"), _("Go to line"), '') line = '' if dlg.ShowModal() == wx.ID_OK: line = int(dlg.GetValue()) - 1 dlg.Destroy() if line != '': self.PythonEditor.GotoLine(line) self.PythonEditor.SetFocus()
def __init__(self): """Class initialiser""" gtk.HBox.__init__(self) self.__gobject_init__() self.config = Config() # Search text self.entry = gtk.Entry() self.entry.set_activates_default(True) self.entry.show() self.entry.connect('activate', self.do_search) self.entry.connect('key-press-event', self.search_keypress) # Label label = gtk.Label(_('Search:')) label.show() # Result label self.reslabel = gtk.Label('') self.reslabel.show() # Close Button close = gtk.Button() close.set_relief(gtk.RELIEF_NONE) close.set_focus_on_click(False) icon = gtk.Image() icon.set_from_stock(gtk.STOCK_CLOSE, gtk.ICON_SIZE_MENU) close.add(icon) close.set_name('terminator-search-close-button') if hasattr(close, 'set_tooltip_text'): close.set_tooltip_text(_('Close Search bar')) close.connect('clicked', self.end_search) close.show_all() # Next Button self.next = gtk.Button(_('Next')) self.next.show() self.next.set_sensitive(False) self.next.connect('clicked', self.next_search) # Previous Button self.prev = gtk.Button(_('Prev')) self.prev.show() self.prev.set_sensitive(False) self.prev.connect('clicked', self.prev_search) self.pack_start(label, False) self.pack_start(self.entry) self.pack_start(self.reslabel, False) self.pack_start(self.prev, False, False) self.pack_start(self.next, False, False) self.pack_end(close, False, False) self.hide() self.set_no_show_all(True)
def delete_account(self): confirm = widget.Dialog(_('Do you want to delete your ARA account?'), [_('OK'),_('Cancel')], ('menu', 'bg', 'bgf'), 45, 5, self) self.overlay = confirm self.parent.run() if confirm.b_pressed == _('OK'): self.server.remove_user(self.session_key) sys.exit(0) else: self.overlay = None self.parent.run()
def select_test_file(self): ''' Dialog to select test file to use with doctest suite (unittest).''' wildcard = _("All files (*.*)|*.*") dlg = wx.FileDialog(self, _("Select file to be used in test suite"), os.getcwd(), "", wildcard, wx.OPEN | wx.CHANGE_DIR) if dlg.ShowModal() == wx.ID_OK: self.testfile_name = dlg.GetPath() else: self.testfile_name = None dlg.Destroy()
def collocs(self, cattr='-', csortfn='m', cbgrfns='mt', cfromw=-5, ctow=5, cminfreq=5, cminbgr=3, max_lines=0): statdesc = {'t': _('T-score'), 'm': _('MI'), '3': _('MI3'), 'l': _('log likelihood'), 's': _('min. sensitivity'), 'p': _('MI.log_f'), 'r': _('relative freq. [%]'), 'f': _('absolute freq.'), 'd': _('logDice') } items = [] colls = manatee.CollocItems(self, cattr, csortfn, cminfreq, cminbgr, cfromw, ctow, max_lines) qfilter = '%%s%i %i 1 [%s="%%s"]' % (cfromw, ctow, cattr) i = 0 while not colls.eos(): if 0 < max_lines < i: break items.append(dict( str=colls.get_item(), freq=colls.get_cnt(), Stats=[{'s': '%.3f' % colls.get_bgr(s)} for s in cbgrfns], pfilter=qfilter % ('P', escape(self.import_string(colls.get_item()))), nfilter=qfilter % ('N', escape(self.import_string(colls.get_item()))) )) colls.next() i += 1 head = [{'n': ''}, {'n': 'Freq', 's': 'f'}] + \ [{'n': statdesc.get(s, s), 's': s} for s in cbgrfns] return dict(Head=head, Items=items)
def viewattrs(self): """ attrs, refs, structs form """ from collections import defaultdict out = {} if self.args.maincorp: corp = corplib.manatee.Corpus(self.args.maincorp) else: corp = self.corp out['AttrList'] = [{'label': corp.get_conf(n + '.LABEL') or n, 'n': n} for n in corp.get_conf('ATTRLIST').split(',') if n] out['fixed_attr'] = 'word' out['attr_allpos'] = self.args.attr_allpos out['attr_vmode'] = self.args.attr_vmode availstruct = corp.get_conf('STRUCTLIST').split(',') structlist = set(self.args.structs.split(',')).union( set([x.split('.')[0] for x in self.args.structattrs])) out['Availstructs'] = [{'n': n, 'sel': 'selected' if n in structlist else '', 'label': corp.get_conf(n + '.LABEL')} for n in availstruct if n and n != '#'] availref = corp.get_conf('STRUCTATTRLIST').split(',') reflist = self.args.refs.split(',') if self.args.refs else [] structattrs = defaultdict(list) def ref_is_allowed(r): return r and r not in ( '#', self.get_corpus_info(self.args.corpname).get('speech_segment')) for item in availref: if ref_is_allowed(item): k, v = item.split('.', 1) structattrs[k].append(v) out['Availrefs'] = [dict(n='#', label=_('Token number'), sel='selected' if '#' in reflist else '')] for n in availref: if ref_is_allowed(n): out['Availrefs'].append(dict(n='=' + n, sel='selected' if ('=' + n) in reflist else '', label=(corp.get_conf(n + '.LABEL') or n))) doc = corp.get_conf('DOCSTRUCTURE') if doc in availstruct: out['Availrefs'].insert(1, dict(n=doc, label=_('Document number'), sel=(doc in reflist and 'selected' or ''))) out['newctxsize'] = self.args.kwicleftctx[1:] out['structattrs'] = structattrs out['curr_structattrs'] = self.args.structattrs out['query_overview'] = self.concdesc_json().get('Desc', []) out['CurrentAttrs'] = self.args.attrs.split(',') out['use_conc_toolbar'] = settings.get_bool('global', 'use_conc_toolbar') return out
def ajax_wipe_subcorpus(self, request): if plugins.has_plugin('subc_restore'): corpus_id = request.form['corpname'] subcorp_name = request.form['subcname'] plugins.get('subc_restore').delete_query(self._session_get('user', 'id'), corpus_id, subcorp_name) self.add_system_message('info', _('Subcorpus %s has been deleted permanently.') % subcorp_name) else: self.add_system_message('error', _('Unsupported operation (plug-in not present)')) return {}