code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
with lock: if float_bits == 32: encode_func[float] = encode_float32 elif float_bits == 64: encode_func[float] = encode_float64 else: raise ValueError('Float bits (%d) is not 32 or 64' % float_bits) r = [] encode_func[type(x)](x, r) ...
def dumps(x, float_bits=DEFAULT_FLOAT_BITS)
Dump data structure to str. Here float_bits is either 32 or 64.
2.810918
2.730417
1.029483
chars = list(u"".join(words)) start = True for i in xrange(len(chars)): char = chars[i] if char.isalpha(): if start: chars[i] = char.upper() else: chars[i] = char.lower() st...
def join(self, words)
Capitalize the first alpha character in the reply and the first alpha character that follows one of [.?!] and a space.
2.866751
2.687528
1.066687
self._learning = True self.graph.cursor().execute("PRAGMA journal_mode=memory") self.graph.drop_reply_indexes()
def start_batch_learning(self)
Begin a series of batch learn operations. Data will not be committed to the database until stop_batch_learning is called. Learn text using the normal learn(text) method.
15.37835
13.396716
1.147919
self._learning = False self.graph.commit() self.graph.cursor().execute("PRAGMA journal_mode=truncate") self.graph.ensure_indexes()
def stop_batch_learning(self)
Finish a series of batch learn operations.
9.228198
8.397696
1.098896
if type(text) != types.UnicodeType: # Assume that non-Unicode text is encoded as utf-8, which # should be somewhat safe in the modern world. text = text.decode("utf-8", "ignore") tokens = self.tokenizer.split(text) trace("Brain.learn_input_token_coun...
def learn(self, text)
Learn a string of text. If the input is not already Unicode, it will be decoded as utf-8.
6.995018
6.542152
1.069223
# prepend self.order Nones chain = self._end_context + tokens + self._end_context has_space = False context = [] for i in xrange(len(chain)): context.append(chain[i]) if len(context) == self.order: if chain[i] == self.SPACE_TOK...
def _to_edges(self, tokens)
This is an iterator that returns the nodes of our graph: "This is a test" -> "None This" "This is" "is a" "a test" "test None" Each is annotated with a boolean that tracks whether whitespace was found between the two tokens.
5.332711
5.242954
1.01712
prev = None for context in contexts: if prev is None: prev = context continue yield prev[0], context[1], context[0] prev = context
def _to_graph(self, contexts)
This is an iterator that returns each edge of our graph with its two nodes
4.374341
3.513209
1.245113
if type(text) != types.UnicodeType: # Assume that non-Unicode text is encoded as utf-8, which # should be somewhat safe in the modern world. text = text.decode("utf-8", "ignore") tokens = self.tokenizer.split(text) input_ids = map(self.graph.get_toke...
def reply(self, text, loop_ms=500, max_len=None)
Reply to a string of text. If the input is not already Unicode, it will be decoded as utf-8.
4.496746
4.467593
1.006525
log.info("Initializing a cobe brain: %s" % filename) if tokenizer is None: tokenizer = "Cobe" if tokenizer not in ("Cobe", "MegaHAL"): log.info("Unknown tokenizer: %s. Using CobeTokenizer", tokenizer) tokenizer = "Cobe" graph = Graph(sqlite...
def init(filename, order=3, tokenizer=None)
Initialize a brain. This brain's file must not already exist. Keyword arguments: order -- Order of the forward/reverse Markov chains (integer) tokenizer -- One of Cobe, MegaHAL (default Cobe). See documentation for cobe.tokenizers for details. (string)
8.637465
5.735863
1.50587
'Same arguments as with class instance init.' chan_map = c.PA_CHANNEL_MAP() if not channel_list: c.pa.channel_map_init_mono(chan_map) else: if not is_str(channel_list): channel_list = b','.join(map(c.force_bytes, channel_list)) c.pa.channel_map_parse(chan_map, channel_list) if not isinstance(volume,...
def struct_from_value( cls, name, volume, channel_list=None, mute=False, device=None )
Same arguments as with class instance init.
4.468398
3.82557
1.168035
'''Connect to pulseaudio server. "autospawn" option will start new pulse daemon, if necessary. Specifying "wait" option will make function block until pulseaudio server appears.''' if self._loop_closed: raise PulseError('Eventloop object was already' ' destroyed and cannot be reused from this instance....
def connect(self, autospawn=False, wait=False)
Connect to pulseaudio server. "autospawn" option will start new pulse daemon, if necessary. Specifying "wait" option will make function block until pulseaudio server appears.
5.730145
4.038365
1.418927
'''timeout should be in seconds (float), 0 for non-blocking poll and None (default) for no timeout.''' with self._pulse_loop() as loop: ts = c.mono_time() ts_deadline = timeout and (ts + timeout) while True: delay = max(0, int((ts_deadline - ts) * 1000000)) if ts_deadline else -1 c.pa.mainloop_p...
def _pulse_poll(self, timeout=None)
timeout should be in seconds (float), 0 for non-blocking poll and None (default) for no timeout.
5.068789
4.049858
1.251597
'''Creates following synchronous wrapper for async pa_operation callable: wrapper(index, ...) -> pulse_op(index, [*]args_func(...)) index_arg=False: wrapper(...) -> pulse_op([*]args_func(...))''' def _wrapper(self, *args, **kws): if index_arg: if 'index' in kws: index = kws.pop('index') else: index...
def _pulse_method_call(pulse_op, func=None, index_arg=True)
Creates following synchronous wrapper for async pa_operation callable: wrapper(index, ...) -> pulse_op(index, [*]args_func(...)) index_arg=False: wrapper(...) -> pulse_op([*]args_func(...))
3.751573
2.567587
1.461128
'''Update module-stream-restore db entry for specified name. Can be passed PulseExtStreamRestoreInfo object or list of them as argument, or name string there and object init keywords (e.g. volume, mute, channel_list, etc). "mode" is PulseUpdateEnum value of 'merge' (default), 'replace' or 'set' (replace...
def stream_restore_write( obj_name_or_list, mode='merge', apply_immediately=False, **obj_kws )
Update module-stream-restore db entry for specified name. Can be passed PulseExtStreamRestoreInfo object or list of them as argument, or name string there and object init keywords (e.g. volume, mute, channel_list, etc). "mode" is PulseUpdateEnum value of 'merge' (default), 'replace' or 'set' (replaces ALL...
5.569167
2.362282
2.357537
'''Can be passed string name, PulseExtStreamRestoreInfo object or a list of any of these.''' if is_str(obj_name_or_list, PulseExtStreamRestoreInfo): obj_name_or_list = [obj_name_or_list] name_list = list((obj.name if isinstance( obj, PulseExtStreamRestoreInfo ) else obj) for obj in obj_name_or_list) na...
def stream_restore_delete(obj_name_or_list)
Can be passed string name, PulseExtStreamRestoreInfo object or a list of any of these.
4.95722
3.120051
1.588827
'Set passed sink or source to be used as default one by pulseaudio server.' assert_pulse_object(obj) method = { PulseSinkInfo: self.sink_default_set, PulseSourceInfo: self.source_default_set }.get(type(obj)) if not method: raise NotImplementedError(type(obj)) method(obj)
def default_set(self, obj)
Set passed sink or source to be used as default one by pulseaudio server.
7.434845
3.737092
1.989473
'''Does not return until PulseLoopStop gets raised in event callback or timeout passes. timeout should be in seconds (float), 0 for non-blocking poll and None (default) for no timeout. raise_on_disconnect causes PulseDisconnected exceptions by default. Do not run any pulse operations from these callb...
def event_listen(self, timeout=None, raise_on_disconnect=True)
Does not return until PulseLoopStop gets raised in event callback or timeout passes. timeout should be in seconds (float), 0 for non-blocking poll and None (default) for no timeout. raise_on_disconnect causes PulseDisconnected exceptions by default. Do not run any pulse operations from these callbacks.
13.667617
3.449852
3.961798
'''Stop event_listen() loop from e.g. another thread. Does nothing if libpulse poll is not running yet, so might be racey with event_listen() - be sure to call it in a loop until event_listen returns or something.''' self._loop_stop = True c.pa.mainloop_wakeup(self._loop)
def event_listen_stop(self)
Stop event_listen() loop from e.g. another thread. Does nothing if libpulse poll is not running yet, so might be racey with event_listen() - be sure to call it in a loop until event_listen returns or something.
18.209717
2.932541
6.209536
'''Can be used to integrate pulse client into existing eventloop. Function will be passed a list of pollfd structs and timeout value (seconds, float), which it is responsible to use and modify (set poll flags) accordingly, returning int value >= 0 with number of fds that had any new events within timeout. ...
def set_poll_func(self, func, func_err_handler=None)
Can be used to integrate pulse client into existing eventloop. Function will be passed a list of pollfd structs and timeout value (seconds, float), which it is responsible to use and modify (set poll flags) accordingly, returning int value >= 0 with number of fds that had any new events within timeout. fu...
9.370031
1.955341
4.792019
''' Updat the link. ''' entry = TabLink.update( name=post_data['name'], link=post_data['link'], order=post_data['order'], logo=post_data['logo'] if 'logo' in post_data else '', ).where(TabLink.uid == uid) try: en...
def update(uid, post_data)
Updat the link.
4.140456
3.390038
1.22136
''' Add record in link. ''' if MLink.get_by_uid(id_link): return False try: the_order = int(post_data['order']) except: the_order = 999 TabLink.create(name=post_data['name'], link=post_data['link'], ...
def create_link(id_link, post_data)
Add record in link.
3.916279
3.467592
1.129394
''' List recent wiki. ''' kwd = { 'pager': '', 'title': 'Recent Pages', } self.render('wiki_page/wiki_list.html', view=MWiki.query_recent(), format_date=tools.format_date, kwd=kwd, ...
def recent(self)
List recent wiki.
10.006101
7.425787
1.34748
''' List the wikis of dated. ''' kwd = { 'pager': '', 'title': '最近文档', } self.render('wiki_page/wiki_list.html', view=MWiki.query_dated(16), format_date=tools.format_date, kwd=kwd, ...
def refresh(self)
List the wikis of dated.
12.422719
7.459726
1.665305
''' To judge if there is a post of the title. Then, to show, or to add. ''' postinfo = MWiki.get_by_wiki(title) if postinfo: if postinfo.kind == self.kind: self.view(postinfo) else: return False else: ...
def view_or_add(self, title)
To judge if there is a post of the title. Then, to show, or to add.
7.83196
3.695213
2.119488
''' Update the wiki. ''' postinfo = MWiki.get_by_uid(uid) if self.check_post_role()['EDIT'] or postinfo.user_name == self.get_current_user(): pass else: return False post_data = self.get_post_data() post_data['user_name'] = self.use...
def update(self, uid)
Update the wiki.
4.101202
3.831862
1.07029
''' View the wiki. ''' kwd = { 'pager': '', 'editable': self.editable(), } self.render('wiki_page/wiki_view.html', postinfo=view, kwd=kwd, userinfo=self.userinfo)
def view(self, view)
View the wiki.
8.797318
6.830267
1.28799
''' Add wiki ''' post_data = self.get_post_data() if title == '': pass else: post_data['title'] = title post_data['user_name'] = self.get_current_user() if MWiki.get_by_wiki(post_data['title']): pass else: ...
def add(self, title='')
Add wiki
4.35203
3.981352
1.093104
''' 生成分页的导航 ''' pagination_num = int(math.ceil(rec_num * 1.0 / 10)) if pagination_num == 1 or pagination_num == 0: fenye_str = '' elif pagination_num > 1: pager_mid, pager_pre, pager_next, pager_last, pager_home = '', '', '', '', '' fenye_str = '<ul class="pagination"...
def echo_html_fenye_str(rec_num, fenye_num)
生成分页的导航
2.091093
2.040398
1.024845
''' Show the HTML ''' logger.info('info echo html: {0}'.format(url_str)) condition = self.gen_redis_kw() url_arr = self.parse_url(url_str) sig = url_arr[0] num = (len(url_arr) - 2) // 2 catinfo = MCategory.get_by_uid(sig) if catinfo.p...
def echo_html(self, url_str)
Show the HTML
4.858377
4.742795
1.02437
''' 生成 list 后的 HTML 格式的字符串 ''' zhiding_str = '' tuiguang_str = '' imgname = 'fixed/zhanwei.png' kwd = { 'imgname': imgname, 'zhiding': zhiding_str, 'tuiguang': tuiguang_str, } self.render('autogen/infolist/info...
def echo_html_list_str(self, catid, infos)
生成 list 后的 HTML 格式的字符串
7.62545
6.359673
1.199032
''' 页面打开后的渲染方法,不包含 list 的查询结果与分页导航 ''' logger.info('Infocat input: {0}'.format(catid)) condition = self.gen_redis_kw() sig = catid bread_title = '' bread_crumb_nav_str = '<li>当前位置:<a href="/">信息</a></li>' _catinfo = MCategory.get_by_uid(catid) ...
def list(self, catid)
页面打开后的渲染方法,不包含 list 的查询结果与分页导航
3.667927
3.347313
1.095783
''' 生成 Filter . ''' if WORK_BOOK: pass else: return False html_dics = {} for wk_sheet in WORK_BOOK: for column in FILTER_COLUMNS: kkey, kval = __write_filter_dic(wk_sheet, column) if kkey: html_dics[kkey] = kval return ht...
def gen_html_dic()
生成 Filter .
8.56238
6.303007
1.358459
''' Return the dictionay of the switcher form XLXS file. if valud of the column of the row is `1`, it will be added to the array. ''' if WORK_BOOK: pass else: return False papa_id = 0 switch_dics = {} kind_dics = {} for work_sheet in WORK_BOOK: kind_si...
def gen_array_crud()
Return the dictionay of the switcher form XLXS file. if valud of the column of the row is `1`, it will be added to the array.
3.828253
2.844678
1.34576
''' if valud of the column of the row is `1`, it will be added to the array. ''' u_dic = [] for col_idx in FILTER_COLUMNS: cell_val = work_sheet['{0}{1}'.format(col_idx, row_num)].value if cell_val in [1, '1']: # Appending the slug name of the switcher. u_di...
def __get_switch_arr(work_sheet, row_num)
if valud of the column of the row is `1`, it will be added to the array.
6.734259
3.754826
1.793494
''' Create the record if new, else update it. ''' rec = MUsage.query_by_signature(user_id, post_id) cate_rec = MInfor2Catalog.get_first_category(post_id) if cate_rec: cat_id = cate_rec.tag_id else: return False if rec.count() > 0:...
def add_or_update(user_id, post_id, kind)
Create the record if new, else update it.
4.003621
3.622617
1.105174
''' Send email to all user. ''' for user_rec in MUser.query_all(): email_add = user_rec.user_email send_mail([email_add], "{0}|{1}".format(SMTP_CFG['name'], email_cfg['title']), email_cfg['content'])
def run_send_all(*args)
Send email to all user.
8.633872
7.225855
1.194858
''' Send email to who not logged in recently. ''' for user_rec in MUser.query_nologin(): email_add = user_rec.user_email print(email_add) send_mail([email_add], "{0}|{1}".format(SMTP_CFG['name'], email_cfg['title']), email_cfg['content']) ...
def run_send_nologin(*args)
Send email to who not logged in recently.
7.844623
6.095729
1.286905
''' Genereting catetory from xlsx file. ''' if os.path.exists(XLSX_FILE): pass else: return # 在分类中排序 order_index = 1 all_cate_arr = [] for sheet_ranges in load_workbook(filename=XLSX_FILE): kind_sig = str(sheet_ranges['A1'].value).strip() for row_nu...
def gen_xlsx_category()
Genereting catetory from xlsx file.
2.746605
2.61568
1.050054
''' Genereting catetory from YAML file. ''' out_dic = yaml.load(open(yaml_file)) for key in out_dic: if key.endswith('00'): uid = key[1:] cur_dic = out_dic[key] porder = cur_dic['order'] cat_dic = { 'uid': uid, ...
def gen_category(yaml_file, sig)
Genereting catetory from YAML file.
2.823588
2.606113
1.083448
''' find YAML. ''' for wroot, _, wfiles in os.walk('./database/meta'): for wfile in wfiles: if wfile.endswith('.yaml'): gen_category(os.path.join(wroot, wfile), wfile[0])
def gen_yaml_category()
find YAML.
5.897772
4.922375
1.198156
''' running some migration. ''' print('Begin migrate ...') torcms_migrator = migrate.PostgresqlMigrator(config.DB_CON) memo_field = migrate.TextField(null=False, default='', help_text='Memo', ) try: migrate.migrate(torcms_migrator.add_column('tabpost', 'memo', memo_field)) exc...
def run_migrate(*args)
running some migration.
3.855345
3.646861
1.057168
''' Generate the difference as the table format. :param rawinfo: :param newinfo: :return: ''' return HtmlDiff.make_table(HtmlDiff(), rawinfo.split('\n'), newinfo.split('\n'), context=True, numlines=1)
def diff_table(rawinfo, newinfo)
Generate the difference as the table format. :param rawinfo: :param newinfo: :return:
5.912592
4.006292
1.475827
''' 随机获取给定位数的整数 ''' sel_arr = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'] rarr = random.sample(sel_arr, lenth) while rarr[0] == '0': rarr = random.sample(sel_arr, lenth) return int(''.join(rarr))
def get_uudd(lenth)
随机获取给定位数的整数
3.239917
2.261685
1.432524
''' Convert markdown text to HTML. with extensions. :param markdown_text: The markdown text. :return: The HTML text. ''' html = markdown.markdown( markdown_text, extensions=[ WikiLinkExtension(base_url='/wiki/', end_url=''), 'markdown.extensions.extra',...
def markdown2html(markdown_text)
Convert markdown text to HTML. with extensions. :param markdown_text: The markdown text. :return: The HTML text.
3.122209
2.530882
1.233644
''' Generate pager of purecss. ''' if page_num == 1: return '' pager_shouye = '''<li class="pure-menu-item {0}"> <a class="pure-menu-link" href="{1}">&lt;&lt; 首页</a></li>'''.format( 'hidden' if current <= 1 else '', cat_slug ) pager_pre = '''<li class="pure-menu-item {0...
def gen_pager_purecss(cat_slug, page_num, current)
Generate pager of purecss.
2.003798
1.95281
1.026111
''' Get the configure value. ''' cfg_var = dir(cfg) if 'DB_CFG' in cfg_var: db_cfg = cfg.DB_CFG else: db_cfg = ConfigDefault.DB_CFG if 'SMTP_CFG' in cfg_var: smtp_cfg = cfg.SMTP_CFG else: smtp_cfg = ConfigDefault.SMTP_CFG if 'SITE_CFG' in cfg_var: ...
def get_cfg()
Get the configure value.
2.171391
2.116767
1.025806
''' When access with the slug, It will add the page if there is no record in database. ''' rec_page = MWiki.get_by_uid(slug) if rec_page: if rec_page.kind == self.kind: self.view(rec_page) else: return False else: ...
def view_or_add(self, slug)
When access with the slug, It will add the page if there is no record in database.
7.923716
4.152249
1.908295
''' To Add page. ''' kwd = { 'cats': MCategory.query_all(), 'slug': citiao, 'pager': '', } self.render('wiki_page/page_add.html', kwd=kwd, userinfo=self.userinfo)
def to_add(self, citiao)
To Add page.
10.05754
8.183568
1.228992
''' Test if the user could edit the page. ''' page_rec = MWiki.get_by_uid(slug) if not page_rec: return False if self.check_post_role()['EDIT']: return True elif page_rec.user_name == self.userinfo.user_name: return True ...
def __could_edit(self, slug)
Test if the user could edit the page.
6.063014
5.235289
1.158105
''' Update the page. ''' post_data = self.get_post_data() post_data['user_name'] = self.userinfo.user_name pageinfo = MWiki.get_by_uid(slug) cnt_old = tornado.escape.xhtml_unescape(pageinfo.cnt_md).strip() cnt_new = post_data['cnt_md'].strip() ...
def update(self, slug)
Update the page.
4.279276
4.055441
1.055194
''' Try to modify the page. ''' kwd = { 'pager': '', } self.render('wiki_page/page_edit.html', postinfo=MWiki.get_by_uid(uid), kwd=kwd, cfg=CMS_CFG, userinfo=self.userinfo)
def to_modify(self, uid)
Try to modify the page.
9.930079
7.932567
1.251812
''' View the page. ''' kwd = { 'pager': '', } self.render('wiki_page/page_view.html', postinfo=rec, kwd=kwd, author=rec.user_name, format_date=tools.format_date, ...
def view(self, rec)
View the page.
8.10226
7.014067
1.155144
''' post count plus one via ajax. ''' output = { 'status': 1 if MWiki.view_count_plus(slug) else 0, } return json.dump(output, self)
def ajax_count_plus(self, slug)
post count plus one via ajax.
11.828489
7.735763
1.529066
''' View the list of the pages. ''' kwd = { 'pager': '', 'title': '单页列表', } self.render('wiki_page/page_list.html', kwd=kwd, view=MWiki.query_recent(), view_all=MWiki.query_all(), ...
def list(self)
View the list of the pages.
8.363318
6.397851
1.307207
''' Add new page. ''' post_data = self.get_post_data() post_data['user_name'] = self.userinfo.user_name if MWiki.get_by_uid(slug): self.set_status(400) return False else: MWiki.create_page(slug, post_data) tornado...
def add_page(self, slug)
Add new page.
5.068398
4.726242
1.072395
''' in infor. ''' post_data = {} for key in self.request.arguments: post_data[key] = self.get_arguments(key)[0] MLog.add(post_data) kwargs.pop('uid', None) # delete `uid` if exists in kwargs self.redirect('/log/')
def add(self, **kwargs)
in infor.
8.123283
7.209315
1.126776
''' View the list of the Log. ''' if cur_p == '': current_page_number = 1 else: current_page_number = int(cur_p) current_page_number = 1 if current_page_number < 1 else current_page_number pager_num = int(MLog.total_number() / CMS_CFG['l...
def list(self, cur_p='')
View the list of the Log.
3.125771
2.893759
1.080177
''' View the list of the Log. ''' if cur_p == '': current_page_number = 1 else: current_page_number = int(cur_p) current_page_number = 1 if current_page_number < 1 else current_page_number pager_num = int(MLog.total_number() / CMS_CFG['l...
def user_log_list(self, userid, cur_p='')
View the list of the Log.
3.003334
2.790831
1.076144
''' View the list of the Log. ''' if cur_p == '': current_page_number = 1 else: current_page_number = int(cur_p) current_page_number = 1 if current_page_number < 1 else current_page_number pager_num = int(MLog.total_number() / CMS_CFG['l...
def pageview(self, cur_p='')
View the list of the Log.
4.133822
3.799031
1.088125
''' Delete by uid ''' del_count = TabPostHist.delete().where(TabPostHist.uid == uid) try: del_count.execute() return False except: return True
def delete(uid)
Delete by uid
7.118481
6.419911
1.108813
''' Update the content by ID. ''' entry = TabPostHist.update( user_name=post_data['user_name'], cnt_md=tornado.escape.xhtml_escape(post_data['cnt_md']), time_update=tools.timestamp(), ).where(TabPostHist.uid == uid) entry.execute()
def update_cnt(uid, post_data)
Update the content by ID.
6.610137
5.254656
1.257958
''' Query history of certian records. ''' recs = TabPostHist.select().where( TabPostHist.post_id == postid ).order_by( TabPostHist.time_update.desc() ).limit(limit) return recs
def query_by_postid(postid, limit=5)
Query history of certian records.
6.807238
4.166614
1.633758
''' Get the last one of the records. ''' recs = TabPostHist.select().where( TabPostHist.post_id == postid ).order_by(TabPostHist.time_update.desc()).limit(limit) if recs.count(): return recs.get() return None
def get_last(postid, limit=10)
Get the last one of the records.
4.876302
3.812691
1.278966
''' Create the history of certain post. ''' uid = tools.get_uuid() TabPostHist.create( uid=uid, title=raw_data.title, post_id=raw_data.uid, user_name=raw_data.user_name, cnt_md=raw_data.cnt_md, time_update=to...
def create_post_history(raw_data)
Create the history of certain post.
5.183705
4.284715
1.209813
''' Get posts of certain catid. In Json. 根据分类ID(catid)获取 该分类下 post 的相关信息,返回Json格式 ''' out_arr = {} for catinfo in MPost2Catalog.query_postinfo_by_cat(catid): out_arr[catinfo.uid] = catinfo.title json.dump(out_arr, self)
def ajax_list_catalog(self, catid)
Get posts of certain catid. In Json. 根据分类ID(catid)获取 该分类下 post 的相关信息,返回Json格式
11.6307
4.273985
2.721277
''' Get the sub category. ToDo: The menu should display by order. Error fond in DRR. 根据父类ID(pid)获取子类,返回Json格式 ''' out_arr = {} for catinfo in MCategory.query_sub_cat(pid): out_arr[catinfo.uid] = catinfo.name json.dump(out_arr, self)
def ajax_subcat_arr(self, pid)
Get the sub category. ToDo: The menu should display by order. Error fond in DRR. 根据父类ID(pid)获取子类,返回Json格式
13.567393
3.598679
3.770103
''' Get the sub category. 根据kind值(kind_sig)获取相应分类,返回Json格式 ''' out_arr = {} for catinfo in MCategory.query_kind_cat(kind_sig): out_arr[catinfo.uid] = catinfo.name json.dump(out_arr, self)
def ajax_kindcat_arr(self, kind_sig)
Get the sub category. 根据kind值(kind_sig)获取相应分类,返回Json格式
9.294114
4.369769
2.126912
''' listing the posts via category 根据分类(cat_slug)显示分类列表 ''' post_data = self.get_post_data() tag = post_data.get('tag', '') def get_pager_idx(): ''' Get the pager index. ''' cur_p = kwargs.get('cur_p') ...
def list_catalog(self, cat_slug, **kwargs)
listing the posts via category 根据分类(cat_slug)显示分类列表
4.130668
3.71139
1.112971
''' Sending email via Python. ''' sender = SMTP_CFG['name'] + "<" + SMTP_CFG['user'] + ">" msg = MIMEText(content, _subtype='html', _charset='utf-8') msg['Subject'] = sub msg['From'] = sender msg['To'] = ";".join(to_list) if cc: msg['cc'] = ';'.join(cc) try: # Usi...
def send_mail(to_list, sub, content, cc=None)
Sending email via Python.
3.47162
3.201575
1.084348
''' pager for searching results. ''' pager = '' if page_num == 1 or page_num == 0: pager = '' elif page_num > 1: pager_mid, pager_pre, pager_next, pager_last, pager_home = '', '', '', '', '' pager = '<ul class="pagination">' if current > 1: pager_hom...
def gen_pager_bootstrap_url(cat_slug, page_num, current)
pager for searching results.
2.311207
2.228062
1.037317
''' perform searching. ''' if p_index == '' or p_index == '-1': current_page_number = 1 else: current_page_number = int(p_index) res_all = self.ysearch.get_all_num(keyword) results = self.ysearch.search_pager( keyword, ...
def search(self, keyword, p_index='')
perform searching.
4.486898
4.267251
1.051473
''' Searching according the kind. ''' catid = 'sid' + catid logger.info('-' * 20) logger.info('search cat') logger.info('catid: {0}'.format(catid)) logger.info('keyword: {0}'.format(keyword)) # catid = '' if p_index == '' or p_index == '-1...
def search_cat(self, catid, keyword, p_index=1)
Searching according the kind.
3.990384
3.68111
1.084017
''' View the info ''' out_json = { 'uid': postinfo.uid, 'time_update': postinfo.time_update, 'title': postinfo.title, 'cnt_html': tornado.escape.xhtml_unescape(postinfo.cnt_html), } self.write(json.dumps(out_json))
def viewinfo(self, postinfo)
View the info
4.21724
3.896605
1.082286
''' Ajax request, that the view count will plus 1. ''' self.set_header("Content-Type", "application/json") output = { # ToDo: Test the following codes. # MPost.__update_view_count_by_uid(uid) else 0, 'status': 1 if MPost.update_misc(uid, count=...
def count_plus(self, uid)
Ajax request, that the view count will plus 1.
8.564591
6.045611
1.416663
''' List posts that recent edited, partially. ''' if cur_p == '': current_page_number = 1 else: current_page_number = int(cur_p) current_page_number = 1 if current_page_number < 1 else current_page_number pager_num = int(MPost.total_numbe...
def p_recent(self, kind, cur_p='', with_catalog=True, with_date=True)
List posts that recent edited, partially.
4.825654
4.052967
1.190647
''' Delete the post, but return the JSON. ''' uid = args[0] current_infor = MPost.get_by_uid(uid) tslug = MCategory.get_by_uid(current_infor.extinfo['def_cat_uid']) is_deleted = MPost.delete(uid) MCategory.update_count(current_infor.extinfo['def_cat_uid'...
def j_delete(self, *args)
Delete the post, but return the JSON.
4.757228
4.03017
1.180404
''' Run to init tables. ''' print('--') create_table(TabPost) create_table(TabTag) create_table(TabMember) create_table(TabWiki) create_table(TabLink) create_table(TabEntity) create_table(TabPostHist) create_table(TabWikiHist) create_table(TabCollect) create_tabl...
def run_init_tables(*args)
Run to init tables.
3.613254
3.295226
1.096512
''' List the entities of the user. ''' # ToDo: 代码与 entity_handler 中 list 方法有重复 current_page_number = int(cur_p) if cur_p else 1 current_page_number = 1 if current_page_number < 1 else current_page_number kwd = { 'current_page': current_page_number ...
def all_list(self, cur_p='')
List the entities of the user.
6.698614
5.852057
1.14466
''' List the entities of the user. ''' current_page_number = int(cur_p) if cur_p else 1 current_page_number = 1 if current_page_number < 1 else current_page_number kwd = { 'current_page': current_page_number } recs = MEntity2User.get_all_page...
def user_list(self, userid, cur_p='')
List the entities of the user.
5.28363
4.747028
1.11304
''' kind_arr, define the `type` except Post, Page, Wiki post_type, define the templates for different kind. ''' SITE_CFG['LANG'] = SITE_CFG.get('LANG', 'zh') # Using jieba lib for Chinese. if SITE_CFG['LANG'] == 'zh' and ChineseAnalyzer: schema = Schema(title=TEXT(stored=True, analy...
def gen_whoosh_database(kind_arr, post_type)
kind_arr, define the `type` except Post, Page, Wiki post_type, define the templates for different kind.
3.104087
2.53345
1.225241
''' 弹出的二级发布菜单 ''' fatherid = catstr[1:] self.write(self.format_class2(fatherid))
def echo_class2(self, catstr='')
弹出的二级发布菜单
22.993246
8.776815
2.619771
''' Publishing from 1st range category. ''' dbdata = MCategory.get_parent_list(kind=kind_sig) class1str = '' for rec in dbdata: class1str += ''' <a onclick="select_sub_tag('/publish/2{0}');" class="btn btn-primary" style="display: inl...
def view_class1(self, kind_sig)
Publishing from 1st range category.
7.42147
5.732425
1.294647
''' Publishing from 2ed range category. ''' if self.is_admin(): pass else: return False kwd = {'class1str': self.format_class2(fatherid), 'parentid': '0', 'parentlist': MCategory.get_parent_list()} if father...
def view_class2(self, fatherid='')
Publishing from 2ed range category.
9.584446
6.882307
1.392621
''' Get the Evalution sum. ''' return TabEvaluation.select().where( (TabEvaluation.post_id == app_id) & (TabEvaluation.value == value) ).count()
def app_evaluation_count(app_id, value=1)
Get the Evalution sum.
8.701231
4.921344
1.76806
''' get by user ID, and app ID. ''' try: return TabEvaluation.get( (TabEvaluation.user_id == user_id) & (TabEvaluation.post_id == app_id) ) except: return None
def get_by_signature(user_id, app_id)
get by user ID, and app ID.
5.482855
4.5132
1.214849
''' Editing evaluation. ''' rec = MEvaluation.get_by_signature(user_id, app_id) if rec: entry = TabEvaluation.update( value=value, ).where(TabEvaluation.uid == rec.uid) entry.execute() else: TabEvaluation.cre...
def add_or_update(user_id, app_id, value)
Editing evaluation.
4.83174
4.075119
1.185668
''' Index funtion. ''' self.render('ext_excel/index.html', userinfo=self.userinfo, cfg=CMS_CFG, kwd={}, )
def index(self)
Index funtion.
28.115395
19.301134
1.456671
''' view the post. ''' out_json = { 'uid': rec.uid, 'time_update': rec.time_update, 'title': rec.title, 'cnt_html': tornado.escape.xhtml_unescape(rec.cnt_html), } self.write(json.dumps(out_json))
def view(self, rec)
view the post.
4.857634
4.2371
1.146452
''' plus count via ajax. ''' output = {'status': 1 if MWiki.view_count_plus(slug) else 0} return json.dump(output, self)
def j_count_plus(self, slug)
plus count via ajax.
13.815969
9.120824
1.514772
''' List the post . ''' if cur_p == '': current_page_number = 1 else: current_page_number = int(cur_p) current_page_number = 1 if current_page_number < 1 else current_page_number pager_num = int(MWiki.total_number(kind) / CMS_CFG['list_nu...
def p_list(self, kind, cur_p='', )
List the post .
5.048178
4.390994
1.149666
''' Set the time that send E-mail to user. ''' entry = TabMember.update( time_email=tools.timestamp(), ).where(TabMember.uid == uid) entry.execute()
def set_sendemail_time(uid)
Set the time that send E-mail to user.
11.365427
7.812165
1.454837
''' Checking the password by user's ID. ''' user_count = TabMember.select().where(TabMember.uid == user_id).count() if user_count == 0: return -1 the_user = TabMember.get(uid=user_id) if the_user.user_pass == tools.md5(u_pass): return 1 ...
def check_user(user_id, u_pass)
Checking the password by user's ID.
4.150442
3.193217
1.299768
''' Checking the password by user's name. ''' the_query = TabMember.select().where(TabMember.user_name == user_name) if the_query.count() == 0: return -1 the_user = the_query.get() if the_user.user_pass == tools.md5(u_pass): return 1 ...
def check_user_by_name(user_name, u_pass)
Checking the password by user's name.
3.90567
3.104327
1.258137
''' Update the password of a user. ''' out_dic = {'success': False, 'code': '00'} entry = TabMember.update(user_pass=tools.md5(newpass)).where(TabMember.uid == user_id) entry.execute() out_dic['success'] = True return out_dic
def update_pass(user_id, newpass)
Update the password of a user.
5.967082
5.762827
1.035443
''' Query the users who do not login recently (90 days). and not send email (120 days). time_model: num * month * hours * minite * second time_login: 3 * 30 * 24 * 60 * 60 time_email: 4 * 30 * 24 * 60 * 60 ''' time_now = tools.timestamp() return Ta...
def query_nologin()
Query the users who do not login recently (90 days). and not send email (120 days). time_model: num * month * hours * minite * second time_login: 3 * 30 * 24 * 60 * 60 time_email: 4 * 30 * 24 * 60 * 60
5.31615
2.130036
2.495803
''' Update the user info by user_id. 21: standsfor invalide E-mail. 91: standsfor unkown reson. ''' if extinfo is None: extinfo = {} out_dic = {'success': False, 'code': '00'} if not tools.check_email_valid(newemail): out_dic['cod...
def update_info(user_id, newemail, extinfo=None)
Update the user info by user_id. 21: standsfor invalide E-mail. 91: standsfor unkown reson.
3.806482
2.458808
1.5481
''' Update the time when user reset passwd. ''' entry = TabMember.update( time_reset_passwd=the_time, ).where(TabMember.user_name == user_name) try: entry.execute() return True except: return False
def update_time_reset_passwd(user_name, the_time)
Update the time when user reset passwd.
4.218302
3.615652
1.166678
''' Update the role of the usr. ''' entry = TabMember.update( role=newprivilege ).where(TabMember.user_name == u_name) try: entry.execute() return True except: return False
def update_role(u_name, newprivilege)
Update the role of the usr.
5.614533
4.176754
1.344234
''' Update the login time for user. ''' entry = TabMember.update( time_login=tools.timestamp() ).where( TabMember.user_name == u_name ) entry.execute()
def update_time_login(u_name)
Update the login time for user.
6.529727
5.743523
1.136885
''' Create the user. The code used if `False`. 11: standsfor invalid username. 21: standsfor invalide E-mail. 91: standsfor unkown reson. ''' out_dic = {'success': False, 'code': '00'} if not tools.check_username_valid(post_data['user_name']): ...
def create_user(post_data)
Create the user. The code used if `False`. 11: standsfor invalid username. 21: standsfor invalide E-mail. 91: standsfor unkown reson.
3.55492
2.231326
1.593187