id
int32
0
252k
repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
51
19.8k
code_tokens
list
docstring
stringlengths
3
17.3k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
87
242
5,100
bukun/TorCMS
torcms/model/entity_model.py
MEntity.get_id_by_impath
def get_id_by_impath(path): ''' The the entity id by the path. ''' logger.info('Get Entiry, Path: {0}'.format(path)) entity_list = TabEntity.select().where(TabEntity.path == path) out_val = None if entity_list.count() == 1: out_val = entity_list.get() elif entity_list.count() > 1: for rec in entity_list: MEntity.delete(rec.uid) out_val = None else: pass return out_val
python
def get_id_by_impath(path): ''' The the entity id by the path. ''' logger.info('Get Entiry, Path: {0}'.format(path)) entity_list = TabEntity.select().where(TabEntity.path == path) out_val = None if entity_list.count() == 1: out_val = entity_list.get() elif entity_list.count() > 1: for rec in entity_list: MEntity.delete(rec.uid) out_val = None else: pass return out_val
[ "def", "get_id_by_impath", "(", "path", ")", ":", "logger", ".", "info", "(", "'Get Entiry, Path: {0}'", ".", "format", "(", "path", ")", ")", "entity_list", "=", "TabEntity", ".", "select", "(", ")", ".", "where", "(", "TabEntity", ".", "path", "==", "p...
The the entity id by the path.
[ "The", "the", "entity", "id", "by", "the", "path", "." ]
6567c7fe2604a1d646d4570c017840958630ed2b
https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/model/entity_model.py#L48-L64
5,101
bukun/TorCMS
torcms/model/entity_model.py
MEntity.create_entity
def create_entity(uid='', path='', desc='', kind='1'): ''' create entity record in the database. ''' if path: pass else: return False if uid: pass else: uid = get_uuid() try: TabEntity.create( uid=uid, path=path, desc=desc, time_create=time.time(), kind=kind ) return True except: return False
python
def create_entity(uid='', path='', desc='', kind='1'): ''' create entity record in the database. ''' if path: pass else: return False if uid: pass else: uid = get_uuid() try: TabEntity.create( uid=uid, path=path, desc=desc, time_create=time.time(), kind=kind ) return True except: return False
[ "def", "create_entity", "(", "uid", "=", "''", ",", "path", "=", "''", ",", "desc", "=", "''", ",", "kind", "=", "'1'", ")", ":", "if", "path", ":", "pass", "else", ":", "return", "False", "if", "uid", ":", "pass", "else", ":", "uid", "=", "get...
create entity record in the database.
[ "create", "entity", "record", "in", "the", "database", "." ]
6567c7fe2604a1d646d4570c017840958630ed2b
https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/model/entity_model.py#L67-L91
5,102
bukun/TorCMS
torcms/handlers/collect_handler.py
CollectHandler.add_or_update
def add_or_update(self, app_id): ''' Add or update the category. ''' logger.info('Collect info: user-{0}, uid-{1}'.format(self.userinfo.uid, app_id)) MCollect.add_or_update(self.userinfo.uid, app_id) out_dic = {'success': True} return json.dump(out_dic, self)
python
def add_or_update(self, app_id): ''' Add or update the category. ''' logger.info('Collect info: user-{0}, uid-{1}'.format(self.userinfo.uid, app_id)) MCollect.add_or_update(self.userinfo.uid, app_id) out_dic = {'success': True} return json.dump(out_dic, self)
[ "def", "add_or_update", "(", "self", ",", "app_id", ")", ":", "logger", ".", "info", "(", "'Collect info: user-{0}, uid-{1}'", ".", "format", "(", "self", ".", "userinfo", ".", "uid", ",", "app_id", ")", ")", "MCollect", ".", "add_or_update", "(", "self", ...
Add or update the category.
[ "Add", "or", "update", "the", "category", "." ]
6567c7fe2604a1d646d4570c017840958630ed2b
https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/handlers/collect_handler.py#L44-L51
5,103
bukun/TorCMS
torcms/handlers/collect_handler.py
CollectHandler.show_list
def show_list(self, the_list, cur_p=''): ''' List of the user collections. ''' current_page_num = int(cur_p) if cur_p else 1 current_page_num = 1 if current_page_num < 1 else current_page_num num_of_cat = MCollect.count_of_user(self.userinfo.uid) page_num = int(num_of_cat / CMS_CFG['list_num']) + 1 kwd = {'current_page': current_page_num} self.render('misc/collect/list.html', recs_collect=MCollect.query_pager_by_all(self.userinfo.uid, current_page_num).objects(), pager=tools.gen_pager_purecss('/collect/{0}'.format(the_list), page_num, current_page_num), userinfo=self.userinfo, cfg=CMS_CFG, kwd=kwd)
python
def show_list(self, the_list, cur_p=''): ''' List of the user collections. ''' current_page_num = int(cur_p) if cur_p else 1 current_page_num = 1 if current_page_num < 1 else current_page_num num_of_cat = MCollect.count_of_user(self.userinfo.uid) page_num = int(num_of_cat / CMS_CFG['list_num']) + 1 kwd = {'current_page': current_page_num} self.render('misc/collect/list.html', recs_collect=MCollect.query_pager_by_all(self.userinfo.uid, current_page_num).objects(), pager=tools.gen_pager_purecss('/collect/{0}'.format(the_list), page_num, current_page_num), userinfo=self.userinfo, cfg=CMS_CFG, kwd=kwd)
[ "def", "show_list", "(", "self", ",", "the_list", ",", "cur_p", "=", "''", ")", ":", "current_page_num", "=", "int", "(", "cur_p", ")", "if", "cur_p", "else", "1", "current_page_num", "=", "1", "if", "current_page_num", "<", "1", "else", "current_page_num"...
List of the user collections.
[ "List", "of", "the", "user", "collections", "." ]
6567c7fe2604a1d646d4570c017840958630ed2b
https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/handlers/collect_handler.py#L54-L76
5,104
bukun/TorCMS
torcms/model/wiki_model.py
MWiki.create_wiki
def create_wiki(post_data): ''' Create the wiki. ''' logger.info('Call create wiki') title = post_data['title'].strip() if len(title) < 2: logger.info(' ' * 4 + 'The title is too short.') return False the_wiki = MWiki.get_by_wiki(title) if the_wiki: logger.info(' ' * 4 + 'The title already exists.') MWiki.update(the_wiki.uid, post_data) return uid = '_' + tools.get_uu8d() return MWiki.__create_rec(uid, '1', post_data=post_data)
python
def create_wiki(post_data): ''' Create the wiki. ''' logger.info('Call create wiki') title = post_data['title'].strip() if len(title) < 2: logger.info(' ' * 4 + 'The title is too short.') return False the_wiki = MWiki.get_by_wiki(title) if the_wiki: logger.info(' ' * 4 + 'The title already exists.') MWiki.update(the_wiki.uid, post_data) return uid = '_' + tools.get_uu8d() return MWiki.__create_rec(uid, '1', post_data=post_data)
[ "def", "create_wiki", "(", "post_data", ")", ":", "logger", ".", "info", "(", "'Call create wiki'", ")", "title", "=", "post_data", "[", "'title'", "]", ".", "strip", "(", ")", "if", "len", "(", "title", ")", "<", "2", ":", "logger", ".", "info", "("...
Create the wiki.
[ "Create", "the", "wiki", "." ]
6567c7fe2604a1d646d4570c017840958630ed2b
https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/model/wiki_model.py#L80-L99
5,105
bukun/TorCMS
torcms/model/wiki_model.py
MWiki.create_page
def create_page(slug, post_data): ''' The page would be created with slug. ''' logger.info('Call create Page') if MWiki.get_by_uid(slug): return False title = post_data['title'].strip() if len(title) < 2: return False return MWiki.__create_rec(slug, '2', post_data=post_data)
python
def create_page(slug, post_data): ''' The page would be created with slug. ''' logger.info('Call create Page') if MWiki.get_by_uid(slug): return False title = post_data['title'].strip() if len(title) < 2: return False return MWiki.__create_rec(slug, '2', post_data=post_data)
[ "def", "create_page", "(", "slug", ",", "post_data", ")", ":", "logger", ".", "info", "(", "'Call create Page'", ")", "if", "MWiki", ".", "get_by_uid", "(", "slug", ")", ":", "return", "False", "title", "=", "post_data", "[", "'title'", "]", ".", "strip"...
The page would be created with slug.
[ "The", "page", "would", "be", "created", "with", "slug", "." ]
6567c7fe2604a1d646d4570c017840958630ed2b
https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/model/wiki_model.py#L102-L113
5,106
bukun/TorCMS
torcms/model/wiki_model.py
MWiki.__create_rec
def __create_rec(*args, **kwargs): ''' Create the record. ''' uid = args[0] kind = args[1] post_data = kwargs['post_data'] try: TabWiki.create( uid=uid, title=post_data['title'].strip(), date=datetime.datetime.now(), cnt_html=tools.markdown2html(post_data['cnt_md']), time_create=tools.timestamp(), user_name=post_data['user_name'], cnt_md=tornado.escape.xhtml_escape(post_data['cnt_md']), time_update=tools.timestamp(), view_count=1, kind=kind, # 1 for wiki, 2 for page ) return True except: return False
python
def __create_rec(*args, **kwargs): ''' Create the record. ''' uid = args[0] kind = args[1] post_data = kwargs['post_data'] try: TabWiki.create( uid=uid, title=post_data['title'].strip(), date=datetime.datetime.now(), cnt_html=tools.markdown2html(post_data['cnt_md']), time_create=tools.timestamp(), user_name=post_data['user_name'], cnt_md=tornado.escape.xhtml_escape(post_data['cnt_md']), time_update=tools.timestamp(), view_count=1, kind=kind, # 1 for wiki, 2 for page ) return True except: return False
[ "def", "__create_rec", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "uid", "=", "args", "[", "0", "]", "kind", "=", "args", "[", "1", "]", "post_data", "=", "kwargs", "[", "'post_data'", "]", "try", ":", "TabWiki", ".", "create", "(", "ui...
Create the record.
[ "Create", "the", "record", "." ]
6567c7fe2604a1d646d4570c017840958630ed2b
https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/model/wiki_model.py#L116-L139
5,107
bukun/TorCMS
torcms/model/wiki_model.py
MWiki.query_dated
def query_dated(num=10, kind='1'): ''' List the wiki of dated. ''' return TabWiki.select().where( TabWiki.kind == kind ).order_by( TabWiki.time_update.desc() ).limit(num)
python
def query_dated(num=10, kind='1'): ''' List the wiki of dated. ''' return TabWiki.select().where( TabWiki.kind == kind ).order_by( TabWiki.time_update.desc() ).limit(num)
[ "def", "query_dated", "(", "num", "=", "10", ",", "kind", "=", "'1'", ")", ":", "return", "TabWiki", ".", "select", "(", ")", ".", "where", "(", "TabWiki", ".", "kind", "==", "kind", ")", ".", "order_by", "(", "TabWiki", ".", "time_update", ".", "d...
List the wiki of dated.
[ "List", "the", "wiki", "of", "dated", "." ]
6567c7fe2604a1d646d4570c017840958630ed2b
https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/model/wiki_model.py#L142-L150
5,108
bukun/TorCMS
torcms/model/wiki_model.py
MWiki.query_most
def query_most(num=8, kind='1'): ''' List the most viewed wiki. ''' return TabWiki.select().where( TabWiki.kind == kind ).order_by( TabWiki.view_count.desc() ).limit(num)
python
def query_most(num=8, kind='1'): ''' List the most viewed wiki. ''' return TabWiki.select().where( TabWiki.kind == kind ).order_by( TabWiki.view_count.desc() ).limit(num)
[ "def", "query_most", "(", "num", "=", "8", ",", "kind", "=", "'1'", ")", ":", "return", "TabWiki", ".", "select", "(", ")", ".", "where", "(", "TabWiki", ".", "kind", "==", "kind", ")", ".", "order_by", "(", "TabWiki", ".", "view_count", ".", "desc...
List the most viewed wiki.
[ "List", "the", "most", "viewed", "wiki", "." ]
6567c7fe2604a1d646d4570c017840958630ed2b
https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/model/wiki_model.py#L153-L161
5,109
bukun/TorCMS
torcms/model/wiki_model.py
MWiki.update_view_count
def update_view_count(citiao): ''' view count of the wiki, plus 1. By wiki ''' entry = TabWiki.update( view_count=TabWiki.view_count + 1 ).where( TabWiki.title == citiao ) entry.execute()
python
def update_view_count(citiao): ''' view count of the wiki, plus 1. By wiki ''' entry = TabWiki.update( view_count=TabWiki.view_count + 1 ).where( TabWiki.title == citiao ) entry.execute()
[ "def", "update_view_count", "(", "citiao", ")", ":", "entry", "=", "TabWiki", ".", "update", "(", "view_count", "=", "TabWiki", ".", "view_count", "+", "1", ")", ".", "where", "(", "TabWiki", ".", "title", "==", "citiao", ")", "entry", ".", "execute", ...
view count of the wiki, plus 1. By wiki
[ "view", "count", "of", "the", "wiki", "plus", "1", ".", "By", "wiki" ]
6567c7fe2604a1d646d4570c017840958630ed2b
https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/model/wiki_model.py#L164-L173
5,110
bukun/TorCMS
torcms/model/wiki_model.py
MWiki.update_view_count_by_uid
def update_view_count_by_uid(uid): ''' update the count of wiki, by uid. ''' entry = TabWiki.update( view_count=TabWiki.view_count + 1 ).where( TabWiki.uid == uid ) entry.execute()
python
def update_view_count_by_uid(uid): ''' update the count of wiki, by uid. ''' entry = TabWiki.update( view_count=TabWiki.view_count + 1 ).where( TabWiki.uid == uid ) entry.execute()
[ "def", "update_view_count_by_uid", "(", "uid", ")", ":", "entry", "=", "TabWiki", ".", "update", "(", "view_count", "=", "TabWiki", ".", "view_count", "+", "1", ")", ".", "where", "(", "TabWiki", ".", "uid", "==", "uid", ")", "entry", ".", "execute", "...
update the count of wiki, by uid.
[ "update", "the", "count", "of", "wiki", "by", "uid", "." ]
6567c7fe2604a1d646d4570c017840958630ed2b
https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/model/wiki_model.py#L176-L185
5,111
bukun/TorCMS
torcms/model/wiki_model.py
MWiki.get_by_wiki
def get_by_wiki(citiao): ''' Get the wiki record by title. ''' q_res = TabWiki.select().where(TabWiki.title == citiao) the_count = q_res.count() if the_count == 0 or the_count > 1: return None else: MWiki.update_view_count(citiao) return q_res.get()
python
def get_by_wiki(citiao): ''' Get the wiki record by title. ''' q_res = TabWiki.select().where(TabWiki.title == citiao) the_count = q_res.count() if the_count == 0 or the_count > 1: return None else: MWiki.update_view_count(citiao) return q_res.get()
[ "def", "get_by_wiki", "(", "citiao", ")", ":", "q_res", "=", "TabWiki", ".", "select", "(", ")", ".", "where", "(", "TabWiki", ".", "title", "==", "citiao", ")", "the_count", "=", "q_res", ".", "count", "(", ")", "if", "the_count", "==", "0", "or", ...
Get the wiki record by title.
[ "Get", "the", "wiki", "record", "by", "title", "." ]
6567c7fe2604a1d646d4570c017840958630ed2b
https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/model/wiki_model.py#L188-L198
5,112
bukun/TorCMS
torcms/model/wiki_model.py
MWiki.view_count_plus
def view_count_plus(slug): ''' View count plus one. ''' entry = TabWiki.update( view_count=TabWiki.view_count + 1, ).where(TabWiki.uid == slug) entry.execute()
python
def view_count_plus(slug): ''' View count plus one. ''' entry = TabWiki.update( view_count=TabWiki.view_count + 1, ).where(TabWiki.uid == slug) entry.execute()
[ "def", "view_count_plus", "(", "slug", ")", ":", "entry", "=", "TabWiki", ".", "update", "(", "view_count", "=", "TabWiki", ".", "view_count", "+", "1", ",", ")", ".", "where", "(", "TabWiki", ".", "uid", "==", "slug", ")", "entry", ".", "execute", "...
View count plus one.
[ "View", "count", "plus", "one", "." ]
6567c7fe2604a1d646d4570c017840958630ed2b
https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/model/wiki_model.py#L208-L215
5,113
bukun/TorCMS
torcms/model/wiki_model.py
MWiki.query_all
def query_all(**kwargs): ''' Qeury recent wiki. ''' kind = kwargs.get('kind', '1') limit = kwargs.get('limit', 50) return TabWiki.select().where(TabWiki.kind == kind).limit(limit)
python
def query_all(**kwargs): ''' Qeury recent wiki. ''' kind = kwargs.get('kind', '1') limit = kwargs.get('limit', 50) return TabWiki.select().where(TabWiki.kind == kind).limit(limit)
[ "def", "query_all", "(", "*", "*", "kwargs", ")", ":", "kind", "=", "kwargs", ".", "get", "(", "'kind'", ",", "'1'", ")", "limit", "=", "kwargs", ".", "get", "(", "'limit'", ",", "50", ")", "return", "TabWiki", ".", "select", "(", ")", ".", "wher...
Qeury recent wiki.
[ "Qeury", "recent", "wiki", "." ]
6567c7fe2604a1d646d4570c017840958630ed2b
https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/model/wiki_model.py#L218-L225
5,114
bukun/TorCMS
torcms/model/wiki_model.py
MWiki.query_random
def query_random(num=6, kind='1'): ''' Query wikis randomly. ''' return TabWiki.select().where( TabWiki.kind == kind ).order_by( peewee.fn.Random() ).limit(num)
python
def query_random(num=6, kind='1'): ''' Query wikis randomly. ''' return TabWiki.select().where( TabWiki.kind == kind ).order_by( peewee.fn.Random() ).limit(num)
[ "def", "query_random", "(", "num", "=", "6", ",", "kind", "=", "'1'", ")", ":", "return", "TabWiki", ".", "select", "(", ")", ".", "where", "(", "TabWiki", ".", "kind", "==", "kind", ")", ".", "order_by", "(", "peewee", ".", "fn", ".", "Random", ...
Query wikis randomly.
[ "Query", "wikis", "randomly", "." ]
6567c7fe2604a1d646d4570c017840958630ed2b
https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/model/wiki_model.py#L228-L236
5,115
bukun/TorCMS
torcms/model/label_model.py
MLabel.get_id_by_name
def get_id_by_name(tag_name, kind='z'): ''' Get ID by tag_name of the label. ''' recs = TabTag.select().where( (TabTag.name == tag_name) & (TabTag.kind == kind) ) logger.info('tag count of {0}: {1} '.format(tag_name, recs.count())) # the_id = '' if recs.count() == 1: the_id = recs.get().uid elif recs.count() > 1: rec0 = None for rec in recs: # Only keep one. if rec0: TabPost2Tag.delete().where(TabPost2Tag.tag_id == rec.uid).execute() TabTag.delete().where(TabTag.uid == rec.uid).execute() else: rec0 = rec the_id = rec0.uid else: the_id = MLabel.create_tag(tag_name) return the_id
python
def get_id_by_name(tag_name, kind='z'): ''' Get ID by tag_name of the label. ''' recs = TabTag.select().where( (TabTag.name == tag_name) & (TabTag.kind == kind) ) logger.info('tag count of {0}: {1} '.format(tag_name, recs.count())) # the_id = '' if recs.count() == 1: the_id = recs.get().uid elif recs.count() > 1: rec0 = None for rec in recs: # Only keep one. if rec0: TabPost2Tag.delete().where(TabPost2Tag.tag_id == rec.uid).execute() TabTag.delete().where(TabTag.uid == rec.uid).execute() else: rec0 = rec the_id = rec0.uid else: the_id = MLabel.create_tag(tag_name) return the_id
[ "def", "get_id_by_name", "(", "tag_name", ",", "kind", "=", "'z'", ")", ":", "recs", "=", "TabTag", ".", "select", "(", ")", ".", "where", "(", "(", "TabTag", ".", "name", "==", "tag_name", ")", "&", "(", "TabTag", ".", "kind", "==", "kind", ")", ...
Get ID by tag_name of the label.
[ "Get", "ID", "by", "tag_name", "of", "the", "label", "." ]
6567c7fe2604a1d646d4570c017840958630ed2b
https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/model/label_model.py#L22-L46
5,116
bukun/TorCMS
torcms/model/label_model.py
MLabel.get_by_slug
def get_by_slug(tag_slug): ''' Get label by slug. ''' label_recs = TabTag.select().where(TabTag.slug == tag_slug) return label_recs.get() if label_recs else False
python
def get_by_slug(tag_slug): ''' Get label by slug. ''' label_recs = TabTag.select().where(TabTag.slug == tag_slug) return label_recs.get() if label_recs else False
[ "def", "get_by_slug", "(", "tag_slug", ")", ":", "label_recs", "=", "TabTag", ".", "select", "(", ")", ".", "where", "(", "TabTag", ".", "slug", "==", "tag_slug", ")", "return", "label_recs", ".", "get", "(", ")", "if", "label_recs", "else", "False" ]
Get label by slug.
[ "Get", "label", "by", "slug", "." ]
6567c7fe2604a1d646d4570c017840958630ed2b
https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/model/label_model.py#L53-L58
5,117
bukun/TorCMS
torcms/model/label_model.py
MLabel.create_tag
def create_tag(tag_name, kind='z'): ''' Create tag record by tag_name ''' cur_recs = TabTag.select().where( (TabTag.name == tag_name) & (TabTag.kind == kind) ) if cur_recs.count(): uid = cur_recs.get().uid # TabTag.delete().where( # (TabTag.name == tag_name) & # (TabTag.kind == kind) # ).execute() else: uid = tools.get_uu4d_v2() # Label with the ID of v2. while TabTag.select().where(TabTag.uid == uid).count() > 0: uid = tools.get_uu4d_v2() TabTag.create( uid=uid, slug=uid, name=tag_name, order=1, count=0, kind='z', tmpl=9, pid='zzzz', ) return uid
python
def create_tag(tag_name, kind='z'): ''' Create tag record by tag_name ''' cur_recs = TabTag.select().where( (TabTag.name == tag_name) & (TabTag.kind == kind) ) if cur_recs.count(): uid = cur_recs.get().uid # TabTag.delete().where( # (TabTag.name == tag_name) & # (TabTag.kind == kind) # ).execute() else: uid = tools.get_uu4d_v2() # Label with the ID of v2. while TabTag.select().where(TabTag.uid == uid).count() > 0: uid = tools.get_uu4d_v2() TabTag.create( uid=uid, slug=uid, name=tag_name, order=1, count=0, kind='z', tmpl=9, pid='zzzz', ) return uid
[ "def", "create_tag", "(", "tag_name", ",", "kind", "=", "'z'", ")", ":", "cur_recs", "=", "TabTag", ".", "select", "(", ")", ".", "where", "(", "(", "TabTag", ".", "name", "==", "tag_name", ")", "&", "(", "TabTag", ".", "kind", "==", "kind", ")", ...
Create tag record by tag_name
[ "Create", "tag", "record", "by", "tag_name" ]
6567c7fe2604a1d646d4570c017840958630ed2b
https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/model/label_model.py#L61-L91
5,118
bukun/TorCMS
torcms/model/label_model.py
MPost2Label.get_by_uid
def get_by_uid(post_id): ''' Get records by post id. ''' return TabPost2Tag.select( TabPost2Tag, TabTag.name.alias('tag_name'), TabTag.uid.alias('tag_uid') ).join( TabTag, on=(TabPost2Tag.tag_id == TabTag.uid) ).where( (TabPost2Tag.post_id == post_id) & (TabTag.kind == 'z') )
python
def get_by_uid(post_id): ''' Get records by post id. ''' return TabPost2Tag.select( TabPost2Tag, TabTag.name.alias('tag_name'), TabTag.uid.alias('tag_uid') ).join( TabTag, on=(TabPost2Tag.tag_id == TabTag.uid) ).where( (TabPost2Tag.post_id == post_id) & (TabTag.kind == 'z') )
[ "def", "get_by_uid", "(", "post_id", ")", ":", "return", "TabPost2Tag", ".", "select", "(", "TabPost2Tag", ",", "TabTag", ".", "name", ".", "alias", "(", "'tag_name'", ")", ",", "TabTag", ".", "uid", ".", "alias", "(", "'tag_uid'", ")", ")", ".", "join...
Get records by post id.
[ "Get", "records", "by", "post", "id", "." ]
6567c7fe2604a1d646d4570c017840958630ed2b
https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/model/label_model.py#L147-L159
5,119
bukun/TorCMS
torcms/model/label_model.py
MPost2Label.add_record
def add_record(post_id, tag_name, order=1, kind='z'): ''' Add the record. ''' logger.info('Add label kind: {0}'.format(kind)) tag_id = MLabel.get_id_by_name(tag_name, 'z') labelinfo = MPost2Label.get_by_info(post_id, tag_id) if labelinfo: entry = TabPost2Tag.update( order=order, ).where(TabPost2Tag.uid == labelinfo.uid) entry.execute() else: entry = TabPost2Tag.create( uid=tools.get_uuid(), post_id=post_id, tag_id=tag_id, order=order, kind='z') return entry.uid
python
def add_record(post_id, tag_name, order=1, kind='z'): ''' Add the record. ''' logger.info('Add label kind: {0}'.format(kind)) tag_id = MLabel.get_id_by_name(tag_name, 'z') labelinfo = MPost2Label.get_by_info(post_id, tag_id) if labelinfo: entry = TabPost2Tag.update( order=order, ).where(TabPost2Tag.uid == labelinfo.uid) entry.execute() else: entry = TabPost2Tag.create( uid=tools.get_uuid(), post_id=post_id, tag_id=tag_id, order=order, kind='z') return entry.uid
[ "def", "add_record", "(", "post_id", ",", "tag_name", ",", "order", "=", "1", ",", "kind", "=", "'z'", ")", ":", "logger", ".", "info", "(", "'Add label kind: {0}'", ".", "format", "(", "kind", ")", ")", "tag_id", "=", "MLabel", ".", "get_id_by_name", ...
Add the record.
[ "Add", "the", "record", "." ]
6567c7fe2604a1d646d4570c017840958630ed2b
https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/model/label_model.py#L190-L209
5,120
bukun/TorCMS
torcms/model/label_model.py
MPost2Label.total_number
def total_number(slug, kind='1'): ''' Return the number of certian slug. ''' return TabPost.select().join( TabPost2Tag, on=(TabPost.uid == TabPost2Tag.post_id) ).where( (TabPost2Tag.tag_id == slug) & (TabPost.kind == kind) ).count()
python
def total_number(slug, kind='1'): ''' Return the number of certian slug. ''' return TabPost.select().join( TabPost2Tag, on=(TabPost.uid == TabPost2Tag.post_id) ).where( (TabPost2Tag.tag_id == slug) & (TabPost.kind == kind) ).count()
[ "def", "total_number", "(", "slug", ",", "kind", "=", "'1'", ")", ":", "return", "TabPost", ".", "select", "(", ")", ".", "join", "(", "TabPost2Tag", ",", "on", "=", "(", "TabPost", ".", "uid", "==", "TabPost2Tag", ".", "post_id", ")", ")", ".", "w...
Return the number of certian slug.
[ "Return", "the", "number", "of", "certian", "slug", "." ]
6567c7fe2604a1d646d4570c017840958630ed2b
https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/model/label_model.py#L212-L221
5,121
bukun/TorCMS
torcms/model/entity2user_model.py
MEntity2User.create_entity2user
def create_entity2user(enti_uid, user_id): ''' create entity2user record in the database. ''' record = TabEntity2User.select().where( (TabEntity2User.entity_id == enti_uid) & (TabEntity2User.user_id == user_id) ) if record.count() > 0: record = record.get() MEntity2User.count_increate(record.uid, record.count) else: TabEntity2User.create( uid=tools.get_uuid(), entity_id=enti_uid, user_id=user_id, count=1, timestamp=time.time() )
python
def create_entity2user(enti_uid, user_id): ''' create entity2user record in the database. ''' record = TabEntity2User.select().where( (TabEntity2User.entity_id == enti_uid) & (TabEntity2User.user_id == user_id) ) if record.count() > 0: record = record.get() MEntity2User.count_increate(record.uid, record.count) else: TabEntity2User.create( uid=tools.get_uuid(), entity_id=enti_uid, user_id=user_id, count=1, timestamp=time.time() )
[ "def", "create_entity2user", "(", "enti_uid", ",", "user_id", ")", ":", "record", "=", "TabEntity2User", ".", "select", "(", ")", ".", "where", "(", "(", "TabEntity2User", ".", "entity_id", "==", "enti_uid", ")", "&", "(", "TabEntity2User", ".", "user_id", ...
create entity2user record in the database.
[ "create", "entity2user", "record", "in", "the", "database", "." ]
6567c7fe2604a1d646d4570c017840958630ed2b
https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/model/entity2user_model.py#L66-L84
5,122
bukun/TorCMS
torcms/script/tmplchecker/__init__.py
check_html
def check_html(html_file, begin): ''' Checking the HTML ''' sig = False for html_line in open(html_file).readlines(): # uu = x.find('{% extends') uuu = pack_str(html_line).find('%extends') # print(pack_str(x)) if uuu > 0: f_tmpl = html_line.strip().split()[-2].strip('"') curpath, curfile = os.path.split(html_file) ff_tmpl = os.path.abspath(os.path.join(curpath, f_tmpl)) if os.path.isfile(ff_tmpl): # print(os.path.abspath(ff_tmpl)) pass else: print('=' *10 + 'ERROR' + '=' *10) print('The file:') print(' ' * 4 + html_file) print('needs:') print(' ' * 4 +ff_tmpl) print('Error, tmpl not find.') # continue sys.exit(1) sig = True if sig: pass else: continue vvv = pack_str(html_line).find('%block') if vvv > 0: test_fig = False for the_line in open(ff_tmpl).readlines(): if the_line.find(pack_str(html_line)) > 0: test_fig = True # fff = sim_filename(ff_tmpl) # sss = sim_filename(html_file) fff = ff_tmpl[begin:] sss = html_file[begin:] tmplsig = [fff, sss] if tmplsig in RELS_UNIQ_ARR: pass else: RELS_UNIQ_ARR.append(tmplsig) DOT_OBJ.edge(fff, sss) if test_fig: # G.add_edge(ff_tmpl[begin], html_file[begin]) pass else: pass
python
def check_html(html_file, begin): ''' Checking the HTML ''' sig = False for html_line in open(html_file).readlines(): # uu = x.find('{% extends') uuu = pack_str(html_line).find('%extends') # print(pack_str(x)) if uuu > 0: f_tmpl = html_line.strip().split()[-2].strip('"') curpath, curfile = os.path.split(html_file) ff_tmpl = os.path.abspath(os.path.join(curpath, f_tmpl)) if os.path.isfile(ff_tmpl): # print(os.path.abspath(ff_tmpl)) pass else: print('=' *10 + 'ERROR' + '=' *10) print('The file:') print(' ' * 4 + html_file) print('needs:') print(' ' * 4 +ff_tmpl) print('Error, tmpl not find.') # continue sys.exit(1) sig = True if sig: pass else: continue vvv = pack_str(html_line).find('%block') if vvv > 0: test_fig = False for the_line in open(ff_tmpl).readlines(): if the_line.find(pack_str(html_line)) > 0: test_fig = True # fff = sim_filename(ff_tmpl) # sss = sim_filename(html_file) fff = ff_tmpl[begin:] sss = html_file[begin:] tmplsig = [fff, sss] if tmplsig in RELS_UNIQ_ARR: pass else: RELS_UNIQ_ARR.append(tmplsig) DOT_OBJ.edge(fff, sss) if test_fig: # G.add_edge(ff_tmpl[begin], html_file[begin]) pass else: pass
[ "def", "check_html", "(", "html_file", ",", "begin", ")", ":", "sig", "=", "False", "for", "html_line", "in", "open", "(", "html_file", ")", ".", "readlines", "(", ")", ":", "# uu = x.find('{% extends')", "uuu", "=", "pack_str", "(", "html_line", ")", ".",...
Checking the HTML
[ "Checking", "the", "HTML" ]
6567c7fe2604a1d646d4570c017840958630ed2b
https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/script/tmplchecker/__init__.py#L39-L94
5,123
bukun/TorCMS
torcms/script/tmplchecker/__init__.py
do_for_dir
def do_for_dir(inws, begin): ''' do something in the directory. ''' inws = os.path.abspath(inws) for wroot, wdirs, wfiles in os.walk(inws): for wfile in wfiles: if wfile.endswith('.html'): if 'autogen' in wroot: continue check_html(os.path.abspath(os.path.join(wroot, wfile)), begin)
python
def do_for_dir(inws, begin): ''' do something in the directory. ''' inws = os.path.abspath(inws) for wroot, wdirs, wfiles in os.walk(inws): for wfile in wfiles: if wfile.endswith('.html'): if 'autogen' in wroot: continue check_html(os.path.abspath(os.path.join(wroot, wfile)), begin)
[ "def", "do_for_dir", "(", "inws", ",", "begin", ")", ":", "inws", "=", "os", ".", "path", ".", "abspath", "(", "inws", ")", "for", "wroot", ",", "wdirs", ",", "wfiles", "in", "os", ".", "walk", "(", "inws", ")", ":", "for", "wfile", "in", "wfiles...
do something in the directory.
[ "do", "something", "in", "the", "directory", "." ]
6567c7fe2604a1d646d4570c017840958630ed2b
https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/script/tmplchecker/__init__.py#L99-L109
5,124
bukun/TorCMS
torcms/script/tmplchecker/__init__.py
run_checkit
def run_checkit(srws=None): ''' do check it. ''' begin = len(os.path.abspath('templates')) + 1 inws = os.path.abspath(os.getcwd()) if srws: do_for_dir(srws[0], begin) else: do_for_dir(os.path.join(inws, 'templates'), begin) DOT_OBJ.render('xxtmpl', view=True)
python
def run_checkit(srws=None): ''' do check it. ''' begin = len(os.path.abspath('templates')) + 1 inws = os.path.abspath(os.getcwd()) if srws: do_for_dir(srws[0], begin) else: do_for_dir(os.path.join(inws, 'templates'), begin) DOT_OBJ.render('xxtmpl', view=True)
[ "def", "run_checkit", "(", "srws", "=", "None", ")", ":", "begin", "=", "len", "(", "os", ".", "path", ".", "abspath", "(", "'templates'", ")", ")", "+", "1", "inws", "=", "os", ".", "path", ".", "abspath", "(", "os", ".", "getcwd", "(", ")", "...
do check it.
[ "do", "check", "it", "." ]
6567c7fe2604a1d646d4570c017840958630ed2b
https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/script/tmplchecker/__init__.py#L112-L123
5,125
bukun/TorCMS
torcms/model/post2catalog_model.py
MPost2Catalog.query_all
def query_all(): ''' Query all the records from TabPost2Tag. ''' recs = TabPost2Tag.select( TabPost2Tag, TabTag.kind.alias('tag_kind'), ).join( TabTag, on=(TabPost2Tag.tag_id == TabTag.uid) ) return recs
python
def query_all(): ''' Query all the records from TabPost2Tag. ''' recs = TabPost2Tag.select( TabPost2Tag, TabTag.kind.alias('tag_kind'), ).join( TabTag, on=(TabPost2Tag.tag_id == TabTag.uid) ) return recs
[ "def", "query_all", "(", ")", ":", "recs", "=", "TabPost2Tag", ".", "select", "(", "TabPost2Tag", ",", "TabTag", ".", "kind", ".", "alias", "(", "'tag_kind'", ")", ",", ")", ".", "join", "(", "TabTag", ",", "on", "=", "(", "TabPost2Tag", ".", "tag_id...
Query all the records from TabPost2Tag.
[ "Query", "all", "the", "records", "from", "TabPost2Tag", "." ]
6567c7fe2604a1d646d4570c017840958630ed2b
https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/model/post2catalog_model.py#L21-L32
5,126
bukun/TorCMS
torcms/model/post2catalog_model.py
MPost2Catalog.remove_relation
def remove_relation(post_id, tag_id): ''' Delete the record of post 2 tag. ''' entry = TabPost2Tag.delete().where( (TabPost2Tag.post_id == post_id) & (TabPost2Tag.tag_id == tag_id) ) entry.execute() MCategory.update_count(tag_id)
python
def remove_relation(post_id, tag_id): ''' Delete the record of post 2 tag. ''' entry = TabPost2Tag.delete().where( (TabPost2Tag.post_id == post_id) & (TabPost2Tag.tag_id == tag_id) ) entry.execute() MCategory.update_count(tag_id)
[ "def", "remove_relation", "(", "post_id", ",", "tag_id", ")", ":", "entry", "=", "TabPost2Tag", ".", "delete", "(", ")", ".", "where", "(", "(", "TabPost2Tag", ".", "post_id", "==", "post_id", ")", "&", "(", "TabPost2Tag", ".", "tag_id", "==", "tag_id", ...
Delete the record of post 2 tag.
[ "Delete", "the", "record", "of", "post", "2", "tag", "." ]
6567c7fe2604a1d646d4570c017840958630ed2b
https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/model/post2catalog_model.py#L35-L44
5,127
bukun/TorCMS
torcms/model/post2catalog_model.py
MPost2Catalog.remove_tag
def remove_tag(tag_id): ''' Delete the records of certain tag. ''' entry = TabPost2Tag.delete().where( TabPost2Tag.tag_id == tag_id ) entry.execute()
python
def remove_tag(tag_id): ''' Delete the records of certain tag. ''' entry = TabPost2Tag.delete().where( TabPost2Tag.tag_id == tag_id ) entry.execute()
[ "def", "remove_tag", "(", "tag_id", ")", ":", "entry", "=", "TabPost2Tag", ".", "delete", "(", ")", ".", "where", "(", "TabPost2Tag", ".", "tag_id", "==", "tag_id", ")", "entry", ".", "execute", "(", ")" ]
Delete the records of certain tag.
[ "Delete", "the", "records", "of", "certain", "tag", "." ]
6567c7fe2604a1d646d4570c017840958630ed2b
https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/model/post2catalog_model.py#L47-L54
5,128
bukun/TorCMS
torcms/model/post2catalog_model.py
MPost2Catalog.query_by_post
def query_by_post(postid): ''' Query records by post. ''' return TabPost2Tag.select().where( TabPost2Tag.post_id == postid ).order_by(TabPost2Tag.order)
python
def query_by_post(postid): ''' Query records by post. ''' return TabPost2Tag.select().where( TabPost2Tag.post_id == postid ).order_by(TabPost2Tag.order)
[ "def", "query_by_post", "(", "postid", ")", ":", "return", "TabPost2Tag", ".", "select", "(", ")", ".", "where", "(", "TabPost2Tag", ".", "post_id", "==", "postid", ")", ".", "order_by", "(", "TabPost2Tag", ".", "order", ")" ]
Query records by post.
[ "Query", "records", "by", "post", "." ]
6567c7fe2604a1d646d4570c017840958630ed2b
https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/model/post2catalog_model.py#L78-L84
5,129
bukun/TorCMS
torcms/model/post2catalog_model.py
MPost2Catalog.__get_by_info
def __get_by_info(post_id, catalog_id): ''' Geo the record by post and catalog. ''' recs = TabPost2Tag.select().where( (TabPost2Tag.post_id == post_id) & (TabPost2Tag.tag_id == catalog_id) ) if recs.count() == 1: return recs.get() elif recs.count() > 1: # return the first one, and delete others. out_rec = None for rec in recs: if out_rec: entry = TabPost2Tag.delete().where( TabPost2Tag.uid == rec.uid ) entry.execute() else: out_rec = rec return out_rec return None
python
def __get_by_info(post_id, catalog_id): ''' Geo the record by post and catalog. ''' recs = TabPost2Tag.select().where( (TabPost2Tag.post_id == post_id) & (TabPost2Tag.tag_id == catalog_id) ) if recs.count() == 1: return recs.get() elif recs.count() > 1: # return the first one, and delete others. out_rec = None for rec in recs: if out_rec: entry = TabPost2Tag.delete().where( TabPost2Tag.uid == rec.uid ) entry.execute() else: out_rec = rec return out_rec return None
[ "def", "__get_by_info", "(", "post_id", ",", "catalog_id", ")", ":", "recs", "=", "TabPost2Tag", ".", "select", "(", ")", ".", "where", "(", "(", "TabPost2Tag", ".", "post_id", "==", "post_id", ")", "&", "(", "TabPost2Tag", ".", "tag_id", "==", "catalog_...
Geo the record by post and catalog.
[ "Geo", "the", "record", "by", "post", "and", "catalog", "." ]
6567c7fe2604a1d646d4570c017840958630ed2b
https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/model/post2catalog_model.py#L87-L110
5,130
bukun/TorCMS
torcms/model/post2catalog_model.py
MPost2Catalog.query_count
def query_count(): ''' The count of post2tag. ''' recs = TabPost2Tag.select( TabPost2Tag.tag_id, peewee.fn.COUNT(TabPost2Tag.tag_id).alias('num') ).group_by( TabPost2Tag.tag_id ) return recs
python
def query_count(): ''' The count of post2tag. ''' recs = TabPost2Tag.select( TabPost2Tag.tag_id, peewee.fn.COUNT(TabPost2Tag.tag_id).alias('num') ).group_by( TabPost2Tag.tag_id ) return recs
[ "def", "query_count", "(", ")", ":", "recs", "=", "TabPost2Tag", ".", "select", "(", "TabPost2Tag", ".", "tag_id", ",", "peewee", ".", "fn", ".", "COUNT", "(", "TabPost2Tag", ".", "tag_id", ")", ".", "alias", "(", "'num'", ")", ")", ".", "group_by", ...
The count of post2tag.
[ "The", "count", "of", "post2tag", "." ]
6567c7fe2604a1d646d4570c017840958630ed2b
https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/model/post2catalog_model.py#L113-L123
5,131
bukun/TorCMS
torcms/model/post2catalog_model.py
MPost2Catalog.update_field
def update_field(uid, post_id=None, tag_id=None, par_id=None): ''' Update the field of post2tag. ''' if post_id: entry = TabPost2Tag.update( post_id=post_id ).where(TabPost2Tag.uid == uid) entry.execute() if tag_id: entry2 = TabPost2Tag.update( par_id=tag_id[:2] + '00', tag_id=tag_id, ).where(TabPost2Tag.uid == uid) entry2.execute() if par_id: entry2 = TabPost2Tag.update( par_id=par_id ).where(TabPost2Tag.uid == uid) entry2.execute()
python
def update_field(uid, post_id=None, tag_id=None, par_id=None): ''' Update the field of post2tag. ''' if post_id: entry = TabPost2Tag.update( post_id=post_id ).where(TabPost2Tag.uid == uid) entry.execute() if tag_id: entry2 = TabPost2Tag.update( par_id=tag_id[:2] + '00', tag_id=tag_id, ).where(TabPost2Tag.uid == uid) entry2.execute() if par_id: entry2 = TabPost2Tag.update( par_id=par_id ).where(TabPost2Tag.uid == uid) entry2.execute()
[ "def", "update_field", "(", "uid", ",", "post_id", "=", "None", ",", "tag_id", "=", "None", ",", "par_id", "=", "None", ")", ":", "if", "post_id", ":", "entry", "=", "TabPost2Tag", ".", "update", "(", "post_id", "=", "post_id", ")", ".", "where", "("...
Update the field of post2tag.
[ "Update", "the", "field", "of", "post2tag", "." ]
6567c7fe2604a1d646d4570c017840958630ed2b
https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/model/post2catalog_model.py#L126-L146
5,132
bukun/TorCMS
torcms/model/post2catalog_model.py
MPost2Catalog.add_record
def add_record(post_id, catalog_id, order=0): ''' Create the record of post 2 tag, and update the count in g_tag. ''' rec = MPost2Catalog.__get_by_info(post_id, catalog_id) if rec: entry = TabPost2Tag.update( order=order, # For migration. the value should be added when created. par_id=rec.tag_id[:2] + '00', ).where(TabPost2Tag.uid == rec.uid) entry.execute() else: TabPost2Tag.create( uid=tools.get_uuid(), par_id=catalog_id[:2] + '00', post_id=post_id, tag_id=catalog_id, order=order, ) MCategory.update_count(catalog_id)
python
def add_record(post_id, catalog_id, order=0): ''' Create the record of post 2 tag, and update the count in g_tag. ''' rec = MPost2Catalog.__get_by_info(post_id, catalog_id) if rec: entry = TabPost2Tag.update( order=order, # For migration. the value should be added when created. par_id=rec.tag_id[:2] + '00', ).where(TabPost2Tag.uid == rec.uid) entry.execute() else: TabPost2Tag.create( uid=tools.get_uuid(), par_id=catalog_id[:2] + '00', post_id=post_id, tag_id=catalog_id, order=order, ) MCategory.update_count(catalog_id)
[ "def", "add_record", "(", "post_id", ",", "catalog_id", ",", "order", "=", "0", ")", ":", "rec", "=", "MPost2Catalog", ".", "__get_by_info", "(", "post_id", ",", "catalog_id", ")", "if", "rec", ":", "entry", "=", "TabPost2Tag", ".", "update", "(", "order...
Create the record of post 2 tag, and update the count in g_tag.
[ "Create", "the", "record", "of", "post", "2", "tag", "and", "update", "the", "count", "in", "g_tag", "." ]
6567c7fe2604a1d646d4570c017840958630ed2b
https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/model/post2catalog_model.py#L149-L171
5,133
bukun/TorCMS
torcms/model/post2catalog_model.py
MPost2Catalog.count_of_certain_category
def count_of_certain_category(cat_id, tag=''): ''' Get the count of certain category. ''' if cat_id.endswith('00'): # The first level category, using the code bellow. cat_con = TabPost2Tag.par_id == cat_id else: cat_con = TabPost2Tag.tag_id == cat_id if tag: condition = { 'def_tag_arr': [tag] } recs = TabPost2Tag.select().join( TabPost, on=((TabPost2Tag.post_id == TabPost.uid) & (TabPost.valid == 1)) ).where( cat_con & TabPost.extinfo.contains(condition) ) else: recs = TabPost2Tag.select().where( cat_con ) return recs.count()
python
def count_of_certain_category(cat_id, tag=''): ''' Get the count of certain category. ''' if cat_id.endswith('00'): # The first level category, using the code bellow. cat_con = TabPost2Tag.par_id == cat_id else: cat_con = TabPost2Tag.tag_id == cat_id if tag: condition = { 'def_tag_arr': [tag] } recs = TabPost2Tag.select().join( TabPost, on=((TabPost2Tag.post_id == TabPost.uid) & (TabPost.valid == 1)) ).where( cat_con & TabPost.extinfo.contains(condition) ) else: recs = TabPost2Tag.select().where( cat_con ) return recs.count()
[ "def", "count_of_certain_category", "(", "cat_id", ",", "tag", "=", "''", ")", ":", "if", "cat_id", ".", "endswith", "(", "'00'", ")", ":", "# The first level category, using the code bellow.", "cat_con", "=", "TabPost2Tag", ".", "par_id", "==", "cat_id", "else", ...
Get the count of certain category.
[ "Get", "the", "count", "of", "certain", "category", "." ]
6567c7fe2604a1d646d4570c017840958630ed2b
https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/model/post2catalog_model.py#L174-L200
5,134
bukun/TorCMS
torcms/model/post2catalog_model.py
MPost2Catalog.query_pager_by_slug
def query_pager_by_slug(slug, current_page_num=1, tag='', order=False): ''' Query pager via category slug. ''' cat_rec = MCategory.get_by_slug(slug) if cat_rec: cat_id = cat_rec.uid else: return None # The flowing code is valid. if cat_id.endswith('00'): # The first level category, using the code bellow. cat_con = TabPost2Tag.par_id == cat_id else: cat_con = TabPost2Tag.tag_id == cat_id if tag: condition = { 'def_tag_arr': [tag] } recs = TabPost.select().join( TabPost2Tag, on=((TabPost.uid == TabPost2Tag.post_id) & (TabPost.valid == 1)) ).where( cat_con & TabPost.extinfo.contains(condition) ).order_by( TabPost.time_update.desc() ).paginate(current_page_num, CMS_CFG['list_num']) elif order: recs = TabPost.select().join( TabPost2Tag, on=((TabPost.uid == TabPost2Tag.post_id) & (TabPost.valid == 1)) ).where( cat_con ).order_by( TabPost.order.asc() ) else: recs = TabPost.select().join( TabPost2Tag, on=((TabPost.uid == TabPost2Tag.post_id) & (TabPost.valid == 1)) ).where( cat_con ).order_by( TabPost.time_update.desc() ).paginate(current_page_num, CMS_CFG['list_num']) return recs
python
def query_pager_by_slug(slug, current_page_num=1, tag='', order=False): ''' Query pager via category slug. ''' cat_rec = MCategory.get_by_slug(slug) if cat_rec: cat_id = cat_rec.uid else: return None # The flowing code is valid. if cat_id.endswith('00'): # The first level category, using the code bellow. cat_con = TabPost2Tag.par_id == cat_id else: cat_con = TabPost2Tag.tag_id == cat_id if tag: condition = { 'def_tag_arr': [tag] } recs = TabPost.select().join( TabPost2Tag, on=((TabPost.uid == TabPost2Tag.post_id) & (TabPost.valid == 1)) ).where( cat_con & TabPost.extinfo.contains(condition) ).order_by( TabPost.time_update.desc() ).paginate(current_page_num, CMS_CFG['list_num']) elif order: recs = TabPost.select().join( TabPost2Tag, on=((TabPost.uid == TabPost2Tag.post_id) & (TabPost.valid == 1)) ).where( cat_con ).order_by( TabPost.order.asc() ) else: recs = TabPost.select().join( TabPost2Tag, on=((TabPost.uid == TabPost2Tag.post_id) & (TabPost.valid == 1)) ).where( cat_con ).order_by( TabPost.time_update.desc() ).paginate(current_page_num, CMS_CFG['list_num']) return recs
[ "def", "query_pager_by_slug", "(", "slug", ",", "current_page_num", "=", "1", ",", "tag", "=", "''", ",", "order", "=", "False", ")", ":", "cat_rec", "=", "MCategory", ".", "get_by_slug", "(", "slug", ")", "if", "cat_rec", ":", "cat_id", "=", "cat_rec", ...
Query pager via category slug.
[ "Query", "pager", "via", "category", "slug", "." ]
6567c7fe2604a1d646d4570c017840958630ed2b
https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/model/post2catalog_model.py#L203-L251
5,135
bukun/TorCMS
torcms/model/post2catalog_model.py
MPost2Catalog.query_by_entity_uid
def query_by_entity_uid(idd, kind=''): ''' Query post2tag by certain post. ''' if kind == '': return TabPost2Tag.select( TabPost2Tag, TabTag.slug.alias('tag_slug'), TabTag.name.alias('tag_name') ).join( TabTag, on=(TabPost2Tag.tag_id == TabTag.uid) ).where( (TabPost2Tag.post_id == idd) & (TabTag.kind != 'z') ).order_by( TabPost2Tag.order ) return TabPost2Tag.select( TabPost2Tag, TabTag.slug.alias('tag_slug'), TabTag.name.alias('tag_name') ).join(TabTag, on=(TabPost2Tag.tag_id == TabTag.uid)).where( (TabTag.kind == kind) & (TabPost2Tag.post_id == idd) ).order_by( TabPost2Tag.order )
python
def query_by_entity_uid(idd, kind=''): ''' Query post2tag by certain post. ''' if kind == '': return TabPost2Tag.select( TabPost2Tag, TabTag.slug.alias('tag_slug'), TabTag.name.alias('tag_name') ).join( TabTag, on=(TabPost2Tag.tag_id == TabTag.uid) ).where( (TabPost2Tag.post_id == idd) & (TabTag.kind != 'z') ).order_by( TabPost2Tag.order ) return TabPost2Tag.select( TabPost2Tag, TabTag.slug.alias('tag_slug'), TabTag.name.alias('tag_name') ).join(TabTag, on=(TabPost2Tag.tag_id == TabTag.uid)).where( (TabTag.kind == kind) & (TabPost2Tag.post_id == idd) ).order_by( TabPost2Tag.order )
[ "def", "query_by_entity_uid", "(", "idd", ",", "kind", "=", "''", ")", ":", "if", "kind", "==", "''", ":", "return", "TabPost2Tag", ".", "select", "(", "TabPost2Tag", ",", "TabTag", ".", "slug", ".", "alias", "(", "'tag_slug'", ")", ",", "TabTag", ".",...
Query post2tag by certain post.
[ "Query", "post2tag", "by", "certain", "post", "." ]
6567c7fe2604a1d646d4570c017840958630ed2b
https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/model/post2catalog_model.py#L254-L281
5,136
bukun/TorCMS
torcms/model/post2catalog_model.py
MPost2Catalog.get_first_category
def get_first_category(app_uid): ''' Get the first, as the uniqe category of post. ''' recs = MPost2Catalog.query_by_entity_uid(app_uid).objects() if recs.count() > 0: return recs.get() return None
python
def get_first_category(app_uid): ''' Get the first, as the uniqe category of post. ''' recs = MPost2Catalog.query_by_entity_uid(app_uid).objects() if recs.count() > 0: return recs.get() return None
[ "def", "get_first_category", "(", "app_uid", ")", ":", "recs", "=", "MPost2Catalog", ".", "query_by_entity_uid", "(", "app_uid", ")", ".", "objects", "(", ")", "if", "recs", ".", "count", "(", ")", ">", "0", ":", "return", "recs", ".", "get", "(", ")",...
Get the first, as the uniqe category of post.
[ "Get", "the", "first", "as", "the", "uniqe", "category", "of", "post", "." ]
6567c7fe2604a1d646d4570c017840958630ed2b
https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/model/post2catalog_model.py#L291-L299
5,137
bukun/TorCMS
torcms/modules/info_modules.py
InfoRecentUsed.render_it
def render_it(self, kind, num, with_tag=False, glyph=''): ''' render, no user logged in ''' all_cats = MPost.query_recent(num, kind=kind) kwd = { 'with_tag': with_tag, 'router': router_post[kind], 'glyph': glyph } return self.render_string('modules/info/list_equation.html', recs=all_cats, kwd=kwd)
python
def render_it(self, kind, num, with_tag=False, glyph=''): ''' render, no user logged in ''' all_cats = MPost.query_recent(num, kind=kind) kwd = { 'with_tag': with_tag, 'router': router_post[kind], 'glyph': glyph } return self.render_string('modules/info/list_equation.html', recs=all_cats, kwd=kwd)
[ "def", "render_it", "(", "self", ",", "kind", ",", "num", ",", "with_tag", "=", "False", ",", "glyph", "=", "''", ")", ":", "all_cats", "=", "MPost", ".", "query_recent", "(", "num", ",", "kind", "=", "kind", ")", "kwd", "=", "{", "'with_tag'", ":"...
render, no user logged in
[ "render", "no", "user", "logged", "in" ]
6567c7fe2604a1d646d4570c017840958630ed2b
https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/modules/info_modules.py#L185-L197
5,138
bukun/TorCMS
torcms/handlers/link_handler.py
LinkHandler.to_add_link
def to_add_link(self, ): ''' To add link ''' if self.check_post_role()['ADD']: pass else: return False kwd = { 'pager': '', 'uid': '', } self.render('misc/link/link_add.html', topmenu='', kwd=kwd, userinfo=self.userinfo, )
python
def to_add_link(self, ): ''' To add link ''' if self.check_post_role()['ADD']: pass else: return False kwd = { 'pager': '', 'uid': '', } self.render('misc/link/link_add.html', topmenu='', kwd=kwd, userinfo=self.userinfo, )
[ "def", "to_add_link", "(", "self", ",", ")", ":", "if", "self", ".", "check_post_role", "(", ")", "[", "'ADD'", "]", ":", "pass", "else", ":", "return", "False", "kwd", "=", "{", "'pager'", ":", "''", ",", "'uid'", ":", "''", ",", "}", "self", "....
To add link
[ "To", "add", "link" ]
6567c7fe2604a1d646d4570c017840958630ed2b
https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/handlers/link_handler.py#L80-L95
5,139
bukun/TorCMS
torcms/handlers/link_handler.py
LinkHandler.update
def update(self, uid): ''' Update the link. ''' if self.userinfo.role[1] >= '3': pass else: return False post_data = self.get_post_data() post_data['user_name'] = self.get_current_user() if self.is_p: if MLink.update(uid, post_data): output = { 'addinfo ': 1, } else: output = { 'addinfo ': 0, } return json.dump(output, self) else: if MLink.update(uid, post_data): self.redirect('/link/list')
python
def update(self, uid): ''' Update the link. ''' if self.userinfo.role[1] >= '3': pass else: return False post_data = self.get_post_data() post_data['user_name'] = self.get_current_user() if self.is_p: if MLink.update(uid, post_data): output = { 'addinfo ': 1, } else: output = { 'addinfo ': 0, } return json.dump(output, self) else: if MLink.update(uid, post_data): self.redirect('/link/list')
[ "def", "update", "(", "self", ",", "uid", ")", ":", "if", "self", ".", "userinfo", ".", "role", "[", "1", "]", ">=", "'3'", ":", "pass", "else", ":", "return", "False", "post_data", "=", "self", ".", "get_post_data", "(", ")", "post_data", "[", "'u...
Update the link.
[ "Update", "the", "link", "." ]
6567c7fe2604a1d646d4570c017840958630ed2b
https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/handlers/link_handler.py#L98-L122
5,140
bukun/TorCMS
torcms/handlers/link_handler.py
LinkHandler.to_modify
def to_modify(self, uid): ''' Try to edit the link. ''' if self.userinfo.role[1] >= '3': pass else: return False self.render('misc/link/link_edit.html', kwd={}, postinfo=MLink.get_by_uid(uid), userinfo=self.userinfo)
python
def to_modify(self, uid): ''' Try to edit the link. ''' if self.userinfo.role[1] >= '3': pass else: return False self.render('misc/link/link_edit.html', kwd={}, postinfo=MLink.get_by_uid(uid), userinfo=self.userinfo)
[ "def", "to_modify", "(", "self", ",", "uid", ")", ":", "if", "self", ".", "userinfo", ".", "role", "[", "1", "]", ">=", "'3'", ":", "pass", "else", ":", "return", "False", "self", ".", "render", "(", "'misc/link/link_edit.html'", ",", "kwd", "=", "{"...
Try to edit the link.
[ "Try", "to", "edit", "the", "link", "." ]
6567c7fe2604a1d646d4570c017840958630ed2b
https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/handlers/link_handler.py#L125-L137
5,141
bukun/TorCMS
torcms/handlers/link_handler.py
LinkHandler.p_user_add_link
def p_user_add_link(self): ''' user add link. ''' if self.check_post_role()['ADD']: pass else: return False post_data = self.get_post_data() post_data['user_name'] = self.get_current_user() cur_uid = tools.get_uudd(2) while MLink.get_by_uid(cur_uid): cur_uid = tools.get_uudd(2) if MLink.create_link(cur_uid, post_data): output = { 'addinfo ': 1, } else: output = { 'addinfo ': 0, } return json.dump(output, self)
python
def p_user_add_link(self): ''' user add link. ''' if self.check_post_role()['ADD']: pass else: return False post_data = self.get_post_data() post_data['user_name'] = self.get_current_user() cur_uid = tools.get_uudd(2) while MLink.get_by_uid(cur_uid): cur_uid = tools.get_uudd(2) if MLink.create_link(cur_uid, post_data): output = { 'addinfo ': 1, } else: output = { 'addinfo ': 0, } return json.dump(output, self)
[ "def", "p_user_add_link", "(", "self", ")", ":", "if", "self", ".", "check_post_role", "(", ")", "[", "'ADD'", "]", ":", "pass", "else", ":", "return", "False", "post_data", "=", "self", ".", "get_post_data", "(", ")", "post_data", "[", "'user_name'", "]...
user add link.
[ "user", "add", "link", "." ]
6567c7fe2604a1d646d4570c017840958630ed2b
https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/handlers/link_handler.py#L164-L188
5,142
bukun/TorCMS
torcms/handlers/link_handler.py
LinkHandler.user_add_link
def user_add_link(self): ''' Create link by user. ''' if self.check_post_role()['ADD']: pass else: return False post_data = self.get_post_data() post_data['user_name'] = self.get_current_user() cur_uid = tools.get_uudd(2) while MLink.get_by_uid(cur_uid): cur_uid = tools.get_uudd(2) MLink.create_link(cur_uid, post_data) self.redirect('/link/list')
python
def user_add_link(self): ''' Create link by user. ''' if self.check_post_role()['ADD']: pass else: return False post_data = self.get_post_data() post_data['user_name'] = self.get_current_user() cur_uid = tools.get_uudd(2) while MLink.get_by_uid(cur_uid): cur_uid = tools.get_uudd(2) MLink.create_link(cur_uid, post_data) self.redirect('/link/list')
[ "def", "user_add_link", "(", "self", ")", ":", "if", "self", ".", "check_post_role", "(", ")", "[", "'ADD'", "]", ":", "pass", "else", ":", "return", "False", "post_data", "=", "self", ".", "get_post_data", "(", ")", "post_data", "[", "'user_name'", "]",...
Create link by user.
[ "Create", "link", "by", "user", "." ]
6567c7fe2604a1d646d4570c017840958630ed2b
https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/handlers/link_handler.py#L191-L209
5,143
bukun/TorCMS
torcms/handlers/link_handler.py
LinkHandler.delete_by_id
def delete_by_id(self, del_id): ''' Delete a link by id. ''' if self.check_post_role()['DELETE']: pass else: return False if self.is_p: if MLink.delete(del_id): output = {'del_link': 1} else: output = {'del_link': 0} return json.dump(output, self) else: is_deleted = MLink.delete(del_id) if is_deleted: self.redirect('/link/list')
python
def delete_by_id(self, del_id): ''' Delete a link by id. ''' if self.check_post_role()['DELETE']: pass else: return False if self.is_p: if MLink.delete(del_id): output = {'del_link': 1} else: output = {'del_link': 0} return json.dump(output, self) else: is_deleted = MLink.delete(del_id) if is_deleted: self.redirect('/link/list')
[ "def", "delete_by_id", "(", "self", ",", "del_id", ")", ":", "if", "self", ".", "check_post_role", "(", ")", "[", "'DELETE'", "]", ":", "pass", "else", ":", "return", "False", "if", "self", ".", "is_p", ":", "if", "MLink", ".", "delete", "(", "del_id...
Delete a link by id.
[ "Delete", "a", "link", "by", "id", "." ]
6567c7fe2604a1d646d4570c017840958630ed2b
https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/handlers/link_handler.py#L212-L229
5,144
bukun/TorCMS
torcms/model/rating_model.py
MRating.get_rating
def get_rating(postid, userid): ''' Get the rating of certain post and user. ''' try: recs = TabRating.select().where( (TabRating.post_id == postid) & (TabRating.user_id == userid) ) except: return False if recs.count() > 0: return recs.get().rating else: return False
python
def get_rating(postid, userid): ''' Get the rating of certain post and user. ''' try: recs = TabRating.select().where( (TabRating.post_id == postid) & (TabRating.user_id == userid) ) except: return False if recs.count() > 0: return recs.get().rating else: return False
[ "def", "get_rating", "(", "postid", ",", "userid", ")", ":", "try", ":", "recs", "=", "TabRating", ".", "select", "(", ")", ".", "where", "(", "(", "TabRating", ".", "post_id", "==", "postid", ")", "&", "(", "TabRating", ".", "user_id", "==", "userid...
Get the rating of certain post and user.
[ "Get", "the", "rating", "of", "certain", "post", "and", "user", "." ]
6567c7fe2604a1d646d4570c017840958630ed2b
https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/model/rating_model.py#L31-L44
5,145
bukun/TorCMS
torcms/model/rating_model.py
MRating.update
def update(postid, userid, rating): ''' Update the rating of certain post and user. The record will be created if no record exists. ''' rating_recs = TabRating.select().where( (TabRating.post_id == postid) & (TabRating.user_id == userid) ) if rating_recs.count() > 0: MRating.__update_rating(rating_recs.get().uid, rating) else: MRating.__insert_data(postid, userid, rating)
python
def update(postid, userid, rating): ''' Update the rating of certain post and user. The record will be created if no record exists. ''' rating_recs = TabRating.select().where( (TabRating.post_id == postid) & (TabRating.user_id == userid) ) if rating_recs.count() > 0: MRating.__update_rating(rating_recs.get().uid, rating) else: MRating.__insert_data(postid, userid, rating)
[ "def", "update", "(", "postid", ",", "userid", ",", "rating", ")", ":", "rating_recs", "=", "TabRating", ".", "select", "(", ")", ".", "where", "(", "(", "TabRating", ".", "post_id", "==", "postid", ")", "&", "(", "TabRating", ".", "user_id", "==", "...
Update the rating of certain post and user. The record will be created if no record exists.
[ "Update", "the", "rating", "of", "certain", "post", "and", "user", ".", "The", "record", "will", "be", "created", "if", "no", "record", "exists", "." ]
6567c7fe2604a1d646d4570c017840958630ed2b
https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/model/rating_model.py#L47-L58
5,146
bukun/TorCMS
torcms/model/rating_model.py
MRating.__update_rating
def __update_rating(uid, rating): ''' Update rating. ''' entry = TabRating.update( rating=rating ).where(TabRating.uid == uid) entry.execute()
python
def __update_rating(uid, rating): ''' Update rating. ''' entry = TabRating.update( rating=rating ).where(TabRating.uid == uid) entry.execute()
[ "def", "__update_rating", "(", "uid", ",", "rating", ")", ":", "entry", "=", "TabRating", ".", "update", "(", "rating", "=", "rating", ")", ".", "where", "(", "TabRating", ".", "uid", "==", "uid", ")", "entry", ".", "execute", "(", ")" ]
Update rating.
[ "Update", "rating", "." ]
6567c7fe2604a1d646d4570c017840958630ed2b
https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/model/rating_model.py#L61-L68
5,147
bukun/TorCMS
torcms/model/rating_model.py
MRating.__insert_data
def __insert_data(postid, userid, rating): ''' Inert new record. ''' uid = tools.get_uuid() TabRating.create( uid=uid, post_id=postid, user_id=userid, rating=rating, timestamp=tools.timestamp(), ) return uid
python
def __insert_data(postid, userid, rating): ''' Inert new record. ''' uid = tools.get_uuid() TabRating.create( uid=uid, post_id=postid, user_id=userid, rating=rating, timestamp=tools.timestamp(), ) return uid
[ "def", "__insert_data", "(", "postid", ",", "userid", ",", "rating", ")", ":", "uid", "=", "tools", ".", "get_uuid", "(", ")", "TabRating", ".", "create", "(", "uid", "=", "uid", ",", "post_id", "=", "postid", ",", "user_id", "=", "userid", ",", "rat...
Inert new record.
[ "Inert", "new", "record", "." ]
6567c7fe2604a1d646d4570c017840958630ed2b
https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/model/rating_model.py#L71-L83
5,148
bukun/TorCMS
helper_scripts/script_meta_xlsx_import.py
update_category
def update_category(uid, postdata, kwargs): ''' Update the category of the post. ''' catid = kwargs['catid'] if ('catid' in kwargs and MCategory.get_by_uid(kwargs['catid'])) else None post_data = postdata current_infos = MPost2Catalog.query_by_entity_uid(uid, kind='').objects() new_category_arr = [] # Used to update post2category, to keep order. def_cate_arr = ['gcat{0}'.format(x) for x in range(10)] # for old page. def_cate_arr.append('def_cat_uid') # Used to update post extinfo. cat_dic = {} for key in def_cate_arr: if key not in post_data: continue if post_data[key] == '' or post_data[key] == '0': continue # 有可能选重复了。保留前面的 if post_data[key] in new_category_arr: continue new_category_arr.append(post_data[key] + ' ' * (4 - len(post_data[key]))) cat_dic[key] = post_data[key] + ' ' * (4 - len(post_data[key])) if catid: def_cat_id = catid elif new_category_arr: def_cat_id = new_category_arr[0] else: def_cat_id = None if def_cat_id: cat_dic['def_cat_uid'] = def_cat_id cat_dic['def_cat_pid'] = MCategory.get_by_uid(def_cat_id).pid print('=' * 40) print(uid) print(cat_dic) MPost.update_jsonb(uid, cat_dic) for index, catid in enumerate(new_category_arr): MPost2Catalog.add_record(uid, catid, index) # Delete the old category if not in post requests. for cur_info in current_infos: if cur_info.tag_id not in new_category_arr: MPost2Catalog.remove_relation(uid, cur_info.tag_id)
python
def update_category(uid, postdata, kwargs): ''' Update the category of the post. ''' catid = kwargs['catid'] if ('catid' in kwargs and MCategory.get_by_uid(kwargs['catid'])) else None post_data = postdata current_infos = MPost2Catalog.query_by_entity_uid(uid, kind='').objects() new_category_arr = [] # Used to update post2category, to keep order. def_cate_arr = ['gcat{0}'.format(x) for x in range(10)] # for old page. def_cate_arr.append('def_cat_uid') # Used to update post extinfo. cat_dic = {} for key in def_cate_arr: if key not in post_data: continue if post_data[key] == '' or post_data[key] == '0': continue # 有可能选重复了。保留前面的 if post_data[key] in new_category_arr: continue new_category_arr.append(post_data[key] + ' ' * (4 - len(post_data[key]))) cat_dic[key] = post_data[key] + ' ' * (4 - len(post_data[key])) if catid: def_cat_id = catid elif new_category_arr: def_cat_id = new_category_arr[0] else: def_cat_id = None if def_cat_id: cat_dic['def_cat_uid'] = def_cat_id cat_dic['def_cat_pid'] = MCategory.get_by_uid(def_cat_id).pid print('=' * 40) print(uid) print(cat_dic) MPost.update_jsonb(uid, cat_dic) for index, catid in enumerate(new_category_arr): MPost2Catalog.add_record(uid, catid, index) # Delete the old category if not in post requests. for cur_info in current_infos: if cur_info.tag_id not in new_category_arr: MPost2Catalog.remove_relation(uid, cur_info.tag_id)
[ "def", "update_category", "(", "uid", ",", "postdata", ",", "kwargs", ")", ":", "catid", "=", "kwargs", "[", "'catid'", "]", "if", "(", "'catid'", "in", "kwargs", "and", "MCategory", ".", "get_by_uid", "(", "kwargs", "[", "'catid'", "]", ")", ")", "els...
Update the category of the post.
[ "Update", "the", "category", "of", "the", "post", "." ]
6567c7fe2604a1d646d4570c017840958630ed2b
https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/helper_scripts/script_meta_xlsx_import.py#L19-L72
5,149
bukun/TorCMS
torcms/model/relation_model.py
MRelation.add_relation
def add_relation(app_f, app_t, weight=1): ''' Adding relation between two posts. ''' recs = TabRel.select().where( (TabRel.post_f_id == app_f) & (TabRel.post_t_id == app_t) ) if recs.count() > 1: for record in recs: MRelation.delete(record.uid) if recs.count() == 0: uid = tools.get_uuid() entry = TabRel.create( uid=uid, post_f_id=app_f, post_t_id=app_t, count=1, ) return entry.uid elif recs.count() == 1: MRelation.update_relation(app_f, app_t, weight) else: return False
python
def add_relation(app_f, app_t, weight=1): ''' Adding relation between two posts. ''' recs = TabRel.select().where( (TabRel.post_f_id == app_f) & (TabRel.post_t_id == app_t) ) if recs.count() > 1: for record in recs: MRelation.delete(record.uid) if recs.count() == 0: uid = tools.get_uuid() entry = TabRel.create( uid=uid, post_f_id=app_f, post_t_id=app_t, count=1, ) return entry.uid elif recs.count() == 1: MRelation.update_relation(app_f, app_t, weight) else: return False
[ "def", "add_relation", "(", "app_f", ",", "app_t", ",", "weight", "=", "1", ")", ":", "recs", "=", "TabRel", ".", "select", "(", ")", ".", "where", "(", "(", "TabRel", ".", "post_f_id", "==", "app_f", ")", "&", "(", "TabRel", ".", "post_t_id", "=="...
Adding relation between two posts.
[ "Adding", "relation", "between", "two", "posts", "." ]
6567c7fe2604a1d646d4570c017840958630ed2b
https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/model/relation_model.py#L15-L38
5,150
bukun/TorCMS
torcms/model/relation_model.py
MRelation.get_app_relations
def get_app_relations(app_id, num=20, kind='1'): ''' The the related infors. ''' info_tag = MInfor2Catalog.get_first_category(app_id) if info_tag: return TabPost2Tag.select( TabPost2Tag, TabPost.title.alias('post_title'), TabPost.valid.alias('post_valid') ).join( TabPost, on=(TabPost2Tag.post_id == TabPost.uid) ).where( (TabPost2Tag.tag_id == info_tag.tag_id) & (TabPost.kind == kind) ).order_by( peewee.fn.Random() ).limit(num) return TabPost2Tag.select( TabPost2Tag, TabPost.title.alias('post_title'), TabPost.valid.alias('post_valid') ).join( TabPost, on=(TabPost2Tag.post_id == TabPost.uid) ).where( TabPost.kind == kind ).order_by(peewee.fn.Random()).limit(num)
python
def get_app_relations(app_id, num=20, kind='1'): ''' The the related infors. ''' info_tag = MInfor2Catalog.get_first_category(app_id) if info_tag: return TabPost2Tag.select( TabPost2Tag, TabPost.title.alias('post_title'), TabPost.valid.alias('post_valid') ).join( TabPost, on=(TabPost2Tag.post_id == TabPost.uid) ).where( (TabPost2Tag.tag_id == info_tag.tag_id) & (TabPost.kind == kind) ).order_by( peewee.fn.Random() ).limit(num) return TabPost2Tag.select( TabPost2Tag, TabPost.title.alias('post_title'), TabPost.valid.alias('post_valid') ).join( TabPost, on=(TabPost2Tag.post_id == TabPost.uid) ).where( TabPost.kind == kind ).order_by(peewee.fn.Random()).limit(num)
[ "def", "get_app_relations", "(", "app_id", ",", "num", "=", "20", ",", "kind", "=", "'1'", ")", ":", "info_tag", "=", "MInfor2Catalog", ".", "get_first_category", "(", "app_id", ")", "if", "info_tag", ":", "return", "TabPost2Tag", ".", "select", "(", "TabP...
The the related infors.
[ "The", "the", "related", "infors", "." ]
6567c7fe2604a1d646d4570c017840958630ed2b
https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/model/relation_model.py#L63-L89
5,151
bukun/TorCMS
torcms/handlers/label_handler.py
LabelHandler.remove_redis_keyword
def remove_redis_keyword(self, keyword): ''' Remove the keyword for redis. ''' redisvr.srem(CMS_CFG['redis_kw'] + self.userinfo.user_name, keyword) return json.dump({}, self)
python
def remove_redis_keyword(self, keyword): ''' Remove the keyword for redis. ''' redisvr.srem(CMS_CFG['redis_kw'] + self.userinfo.user_name, keyword) return json.dump({}, self)
[ "def", "remove_redis_keyword", "(", "self", ",", "keyword", ")", ":", "redisvr", ".", "srem", "(", "CMS_CFG", "[", "'redis_kw'", "]", "+", "self", ".", "userinfo", ".", "user_name", ",", "keyword", ")", "return", "json", ".", "dump", "(", "{", "}", ","...
Remove the keyword for redis.
[ "Remove", "the", "keyword", "for", "redis", "." ]
6567c7fe2604a1d646d4570c017840958630ed2b
https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/handlers/label_handler.py#L44-L49
5,152
bukun/TorCMS
torcms/script/script_funcs.py
build_directory
def build_directory(): ''' Build the directory for Whoosh database, and locale. ''' if os.path.exists('locale'): pass else: os.mkdir('locale') if os.path.exists(WHOOSH_DB_DIR): pass else: os.makedirs(WHOOSH_DB_DIR)
python
def build_directory(): ''' Build the directory for Whoosh database, and locale. ''' if os.path.exists('locale'): pass else: os.mkdir('locale') if os.path.exists(WHOOSH_DB_DIR): pass else: os.makedirs(WHOOSH_DB_DIR)
[ "def", "build_directory", "(", ")", ":", "if", "os", ".", "path", ".", "exists", "(", "'locale'", ")", ":", "pass", "else", ":", "os", ".", "mkdir", "(", "'locale'", ")", "if", "os", ".", "path", ".", "exists", "(", "WHOOSH_DB_DIR", ")", ":", "pass...
Build the directory for Whoosh database, and locale.
[ "Build", "the", "directory", "for", "Whoosh", "database", "and", "locale", "." ]
6567c7fe2604a1d646d4570c017840958630ed2b
https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/script/script_funcs.py#L22-L33
5,153
bukun/TorCMS
torcms/script/script_funcs.py
run_create_admin
def run_create_admin(*args): ''' creating the default administrator. ''' post_data = { 'user_name': 'giser', 'user_email': 'giser@osgeo.cn', 'user_pass': '131322', 'role': '3300', } if MUser.get_by_name(post_data['user_name']): print('User {user_name} already exists.'.format(user_name='giser')) else: MUser.create_user(post_data)
python
def run_create_admin(*args): ''' creating the default administrator. ''' post_data = { 'user_name': 'giser', 'user_email': 'giser@osgeo.cn', 'user_pass': '131322', 'role': '3300', } if MUser.get_by_name(post_data['user_name']): print('User {user_name} already exists.'.format(user_name='giser')) else: MUser.create_user(post_data)
[ "def", "run_create_admin", "(", "*", "args", ")", ":", "post_data", "=", "{", "'user_name'", ":", "'giser'", ",", "'user_email'", ":", "'giser@osgeo.cn'", ",", "'user_pass'", ":", "'131322'", ",", "'role'", ":", "'3300'", ",", "}", "if", "MUser", ".", "get...
creating the default administrator.
[ "creating", "the", "default", "administrator", "." ]
6567c7fe2604a1d646d4570c017840958630ed2b
https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/script/script_funcs.py#L52-L65
5,154
bukun/TorCMS
torcms/script/script_funcs.py
run_update_cat
def run_update_cat(_): ''' Update the catagery. ''' recs = MPost2Catalog.query_all().objects() for rec in recs: if rec.tag_kind != 'z': print('-' * 40) print(rec.uid) print(rec.tag_id) print(rec.par_id) MPost2Catalog.update_field(rec.uid, par_id=rec.tag_id[:2] + "00")
python
def run_update_cat(_): ''' Update the catagery. ''' recs = MPost2Catalog.query_all().objects() for rec in recs: if rec.tag_kind != 'z': print('-' * 40) print(rec.uid) print(rec.tag_id) print(rec.par_id) MPost2Catalog.update_field(rec.uid, par_id=rec.tag_id[:2] + "00")
[ "def", "run_update_cat", "(", "_", ")", ":", "recs", "=", "MPost2Catalog", ".", "query_all", "(", ")", ".", "objects", "(", ")", "for", "rec", "in", "recs", ":", "if", "rec", ".", "tag_kind", "!=", "'z'", ":", "print", "(", "'-'", "*", "40", ")", ...
Update the catagery.
[ "Update", "the", "catagery", "." ]
6567c7fe2604a1d646d4570c017840958630ed2b
https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/script/script_funcs.py#L75-L87
5,155
bukun/TorCMS
torcms/handlers/rating_handler.py
RatingHandler.update_post
def update_post(self, postid): ''' The rating of Post should be updaed if the count is greater than 10 ''' voted_recs = MRating.query_by_post(postid) if voted_recs.count() > 10: rating = MRating.query_average_rating(postid) else: rating = 5 logger.info('Get post rating: {rating}'.format(rating=rating)) # MPost.__update_rating(postid, rating) MPost.update_misc(postid, rating=rating)
python
def update_post(self, postid): ''' The rating of Post should be updaed if the count is greater than 10 ''' voted_recs = MRating.query_by_post(postid) if voted_recs.count() > 10: rating = MRating.query_average_rating(postid) else: rating = 5 logger.info('Get post rating: {rating}'.format(rating=rating)) # MPost.__update_rating(postid, rating) MPost.update_misc(postid, rating=rating)
[ "def", "update_post", "(", "self", ",", "postid", ")", ":", "voted_recs", "=", "MRating", ".", "query_by_post", "(", "postid", ")", "if", "voted_recs", ".", "count", "(", ")", ">", "10", ":", "rating", "=", "MRating", ".", "query_average_rating", "(", "p...
The rating of Post should be updaed if the count is greater than 10
[ "The", "rating", "of", "Post", "should", "be", "updaed", "if", "the", "count", "is", "greater", "than", "10" ]
6567c7fe2604a1d646d4570c017840958630ed2b
https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/handlers/rating_handler.py#L35-L49
5,156
bukun/TorCMS
torcms/handlers/rating_handler.py
RatingHandler.update_rating
def update_rating(self, postid): ''' only the used who logged in would voting. ''' post_data = self.get_post_data() rating = float(post_data['rating']) postinfo = MPost.get_by_uid(postid) if postinfo and self.userinfo: MRating.update(postinfo.uid, self.userinfo.uid, rating=rating) self.update_post(postid) else: return False
python
def update_rating(self, postid): ''' only the used who logged in would voting. ''' post_data = self.get_post_data() rating = float(post_data['rating']) postinfo = MPost.get_by_uid(postid) if postinfo and self.userinfo: MRating.update(postinfo.uid, self.userinfo.uid, rating=rating) self.update_post(postid) else: return False
[ "def", "update_rating", "(", "self", ",", "postid", ")", ":", "post_data", "=", "self", ".", "get_post_data", "(", ")", "rating", "=", "float", "(", "post_data", "[", "'rating'", "]", ")", "postinfo", "=", "MPost", ".", "get_by_uid", "(", "postid", ")", ...
only the used who logged in would voting.
[ "only", "the", "used", "who", "logged", "in", "would", "voting", "." ]
6567c7fe2604a1d646d4570c017840958630ed2b
https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/handlers/rating_handler.py#L52-L63
5,157
bukun/TorCMS
torcms/model/category_model.py
MCategory.query_all
def query_all(kind='1', by_count=False, by_order=True): ''' Qeury all the categories, order by count or defined order. ''' if by_count: recs = TabTag.select().where(TabTag.kind == kind).order_by(TabTag.count.desc()) elif by_order: recs = TabTag.select().where(TabTag.kind == kind).order_by(TabTag.order) else: recs = TabTag.select().where(TabTag.kind == kind).order_by(TabTag.uid) return recs
python
def query_all(kind='1', by_count=False, by_order=True): ''' Qeury all the categories, order by count or defined order. ''' if by_count: recs = TabTag.select().where(TabTag.kind == kind).order_by(TabTag.count.desc()) elif by_order: recs = TabTag.select().where(TabTag.kind == kind).order_by(TabTag.order) else: recs = TabTag.select().where(TabTag.kind == kind).order_by(TabTag.uid) return recs
[ "def", "query_all", "(", "kind", "=", "'1'", ",", "by_count", "=", "False", ",", "by_order", "=", "True", ")", ":", "if", "by_count", ":", "recs", "=", "TabTag", ".", "select", "(", ")", ".", "where", "(", "TabTag", ".", "kind", "==", "kind", ")", ...
Qeury all the categories, order by count or defined order.
[ "Qeury", "all", "the", "categories", "order", "by", "count", "or", "defined", "order", "." ]
6567c7fe2604a1d646d4570c017840958630ed2b
https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/model/category_model.py#L69-L79
5,158
bukun/TorCMS
torcms/model/category_model.py
MCategory.query_field_count
def query_field_count(limit_num, kind='1'): ''' Query the posts count of certain category. ''' return TabTag.select().where( TabTag.kind == kind ).order_by( TabTag.count.desc() ).limit(limit_num)
python
def query_field_count(limit_num, kind='1'): ''' Query the posts count of certain category. ''' return TabTag.select().where( TabTag.kind == kind ).order_by( TabTag.count.desc() ).limit(limit_num)
[ "def", "query_field_count", "(", "limit_num", ",", "kind", "=", "'1'", ")", ":", "return", "TabTag", ".", "select", "(", ")", ".", "where", "(", "TabTag", ".", "kind", "==", "kind", ")", ".", "order_by", "(", "TabTag", ".", "count", ".", "desc", "(",...
Query the posts count of certain category.
[ "Query", "the", "posts", "count", "of", "certain", "category", "." ]
6567c7fe2604a1d646d4570c017840958630ed2b
https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/model/category_model.py#L82-L90
5,159
bukun/TorCMS
torcms/model/category_model.py
MCategory.get_by_slug
def get_by_slug(slug): ''' return the category record . ''' rec = TabTag.select().where(TabTag.slug == slug) if rec.count() > 0: return rec.get() return None
python
def get_by_slug(slug): ''' return the category record . ''' rec = TabTag.select().where(TabTag.slug == slug) if rec.count() > 0: return rec.get() return None
[ "def", "get_by_slug", "(", "slug", ")", ":", "rec", "=", "TabTag", ".", "select", "(", ")", ".", "where", "(", "TabTag", ".", "slug", "==", "slug", ")", "if", "rec", ".", "count", "(", ")", ">", "0", ":", "return", "rec", ".", "get", "(", ")", ...
return the category record .
[ "return", "the", "category", "record", "." ]
6567c7fe2604a1d646d4570c017840958630ed2b
https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/model/category_model.py#L93-L100
5,160
bukun/TorCMS
torcms/model/category_model.py
MCategory.update_count
def update_count(cat_id): ''' Update the count of certain category. ''' # Todo: the record not valid should not be counted. entry2 = TabTag.update( count=TabPost2Tag.select().where( TabPost2Tag.tag_id == cat_id ).count() ).where(TabTag.uid == cat_id) entry2.execute()
python
def update_count(cat_id): ''' Update the count of certain category. ''' # Todo: the record not valid should not be counted. entry2 = TabTag.update( count=TabPost2Tag.select().where( TabPost2Tag.tag_id == cat_id ).count() ).where(TabTag.uid == cat_id) entry2.execute()
[ "def", "update_count", "(", "cat_id", ")", ":", "# Todo: the record not valid should not be counted.", "entry2", "=", "TabTag", ".", "update", "(", "count", "=", "TabPost2Tag", ".", "select", "(", ")", ".", "where", "(", "TabPost2Tag", ".", "tag_id", "==", "cat_...
Update the count of certain category.
[ "Update", "the", "count", "of", "certain", "category", "." ]
6567c7fe2604a1d646d4570c017840958630ed2b
https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/model/category_model.py#L103-L113
5,161
bukun/TorCMS
torcms/model/category_model.py
MCategory.update
def update(uid, post_data): ''' Update the category. ''' raw_rec = TabTag.get(TabTag.uid == uid) entry = TabTag.update( name=post_data['name'] if 'name' in post_data else raw_rec.name, slug=post_data['slug'] if 'slug' in post_data else raw_rec.slug, order=post_data['order'] if 'order' in post_data else raw_rec.order, kind=post_data['kind'] if 'kind' in post_data else raw_rec.kind, pid=post_data['pid'], ).where(TabTag.uid == uid) entry.execute()
python
def update(uid, post_data): ''' Update the category. ''' raw_rec = TabTag.get(TabTag.uid == uid) entry = TabTag.update( name=post_data['name'] if 'name' in post_data else raw_rec.name, slug=post_data['slug'] if 'slug' in post_data else raw_rec.slug, order=post_data['order'] if 'order' in post_data else raw_rec.order, kind=post_data['kind'] if 'kind' in post_data else raw_rec.kind, pid=post_data['pid'], ).where(TabTag.uid == uid) entry.execute()
[ "def", "update", "(", "uid", ",", "post_data", ")", ":", "raw_rec", "=", "TabTag", ".", "get", "(", "TabTag", ".", "uid", "==", "uid", ")", "entry", "=", "TabTag", ".", "update", "(", "name", "=", "post_data", "[", "'name'", "]", "if", "'name'", "i...
Update the category.
[ "Update", "the", "category", "." ]
6567c7fe2604a1d646d4570c017840958630ed2b
https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/model/category_model.py#L116-L128
5,162
bukun/TorCMS
torcms/model/category_model.py
MCategory.add_or_update
def add_or_update(uid, post_data): ''' Add or update the data by the given ID of post. ''' catinfo = MCategory.get_by_uid(uid) if catinfo: MCategory.update(uid, post_data) else: TabTag.create( uid=uid, name=post_data['name'], slug=post_data['slug'], order=post_data['order'], kind=post_data['kind'] if 'kind' in post_data else '1', pid=post_data['pid'], ) return uid
python
def add_or_update(uid, post_data): ''' Add or update the data by the given ID of post. ''' catinfo = MCategory.get_by_uid(uid) if catinfo: MCategory.update(uid, post_data) else: TabTag.create( uid=uid, name=post_data['name'], slug=post_data['slug'], order=post_data['order'], kind=post_data['kind'] if 'kind' in post_data else '1', pid=post_data['pid'], ) return uid
[ "def", "add_or_update", "(", "uid", ",", "post_data", ")", ":", "catinfo", "=", "MCategory", ".", "get_by_uid", "(", "uid", ")", "if", "catinfo", ":", "MCategory", ".", "update", "(", "uid", ",", "post_data", ")", "else", ":", "TabTag", ".", "create", ...
Add or update the data by the given ID of post.
[ "Add", "or", "update", "the", "data", "by", "the", "given", "ID", "of", "post", "." ]
6567c7fe2604a1d646d4570c017840958630ed2b
https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/model/category_model.py#L131-L147
5,163
bukun/TorCMS
torcms/handlers/post_list_handler.py
PostListHandler.recent
def recent(self, with_catalog=True, with_date=True): ''' List posts that recent edited. ''' kwd = { 'pager': '', 'title': 'Recent posts.', 'with_catalog': with_catalog, 'with_date': with_date, } self.render('list/post_list.html', kwd=kwd, view=MPost.query_recent(num=20), postrecs=MPost.query_recent(num=2), format_date=tools.format_date, userinfo=self.userinfo, cfg=CMS_CFG, )
python
def recent(self, with_catalog=True, with_date=True): ''' List posts that recent edited. ''' kwd = { 'pager': '', 'title': 'Recent posts.', 'with_catalog': with_catalog, 'with_date': with_date, } self.render('list/post_list.html', kwd=kwd, view=MPost.query_recent(num=20), postrecs=MPost.query_recent(num=2), format_date=tools.format_date, userinfo=self.userinfo, cfg=CMS_CFG, )
[ "def", "recent", "(", "self", ",", "with_catalog", "=", "True", ",", "with_date", "=", "True", ")", ":", "kwd", "=", "{", "'pager'", ":", "''", ",", "'title'", ":", "'Recent posts.'", ",", "'with_catalog'", ":", "with_catalog", ",", "'with_date'", ":", "...
List posts that recent edited.
[ "List", "posts", "that", "recent", "edited", "." ]
6567c7fe2604a1d646d4570c017840958630ed2b
https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/handlers/post_list_handler.py#L40-L56
5,164
bukun/TorCMS
torcms/handlers/post_list_handler.py
PostListHandler.errcat
def errcat(self): ''' List the posts to be modified. ''' post_recs = MPost.query_random(limit=1000) outrecs = [] errrecs = [] idx = 0 for postinfo in post_recs: if idx > 16: break cat = MPost2Catalog.get_first_category(postinfo.uid) if cat: if 'def_cat_uid' in postinfo.extinfo: if postinfo.extinfo['def_cat_uid'] == cat.tag_id: pass else: errrecs.append(postinfo) idx += 1 else: errrecs.append(postinfo) idx += 1 else: outrecs.append(postinfo) idx += 1 self.render('list/errcat.html', kwd={}, norecs=outrecs, errrecs=errrecs, userinfo=self.userinfo)
python
def errcat(self): ''' List the posts to be modified. ''' post_recs = MPost.query_random(limit=1000) outrecs = [] errrecs = [] idx = 0 for postinfo in post_recs: if idx > 16: break cat = MPost2Catalog.get_first_category(postinfo.uid) if cat: if 'def_cat_uid' in postinfo.extinfo: if postinfo.extinfo['def_cat_uid'] == cat.tag_id: pass else: errrecs.append(postinfo) idx += 1 else: errrecs.append(postinfo) idx += 1 else: outrecs.append(postinfo) idx += 1 self.render('list/errcat.html', kwd={}, norecs=outrecs, errrecs=errrecs, userinfo=self.userinfo)
[ "def", "errcat", "(", "self", ")", ":", "post_recs", "=", "MPost", ".", "query_random", "(", "limit", "=", "1000", ")", "outrecs", "=", "[", "]", "errrecs", "=", "[", "]", "idx", "=", "0", "for", "postinfo", "in", "post_recs", ":", "if", "idx", ">"...
List the posts to be modified.
[ "List", "the", "posts", "to", "be", "modified", "." ]
6567c7fe2604a1d646d4570c017840958630ed2b
https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/handlers/post_list_handler.py#L58-L87
5,165
bukun/TorCMS
torcms/handlers/post_list_handler.py
PostListHandler.refresh
def refresh(self): ''' List the post of dated. ''' kwd = { 'pager': '', 'title': '', } self.render('list/post_list.html', kwd=kwd, userinfo=self.userinfo, view=MPost.query_dated(10), postrecs=MPost.query_dated(10), format_date=tools.format_date, cfg=CMS_CFG)
python
def refresh(self): ''' List the post of dated. ''' kwd = { 'pager': '', 'title': '', } self.render('list/post_list.html', kwd=kwd, userinfo=self.userinfo, view=MPost.query_dated(10), postrecs=MPost.query_dated(10), format_date=tools.format_date, cfg=CMS_CFG)
[ "def", "refresh", "(", "self", ")", ":", "kwd", "=", "{", "'pager'", ":", "''", ",", "'title'", ":", "''", ",", "}", "self", ".", "render", "(", "'list/post_list.html'", ",", "kwd", "=", "kwd", ",", "userinfo", "=", "self", ".", "userinfo", ",", "v...
List the post of dated.
[ "List", "the", "post", "of", "dated", "." ]
6567c7fe2604a1d646d4570c017840958630ed2b
https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/handlers/post_list_handler.py#L89-L103
5,166
bukun/TorCMS
torcms/script/autocrud/base_crud.py
build_dir
def build_dir(): ''' Build the directory used for templates. ''' tag_arr = ['add', 'edit', 'view', 'list', 'infolist'] path_arr = [os.path.join(CRUD_PATH, x) for x in tag_arr] for wpath in path_arr: if os.path.exists(wpath): continue os.makedirs(wpath)
python
def build_dir(): ''' Build the directory used for templates. ''' tag_arr = ['add', 'edit', 'view', 'list', 'infolist'] path_arr = [os.path.join(CRUD_PATH, x) for x in tag_arr] for wpath in path_arr: if os.path.exists(wpath): continue os.makedirs(wpath)
[ "def", "build_dir", "(", ")", ":", "tag_arr", "=", "[", "'add'", ",", "'edit'", ",", "'view'", ",", "'list'", ",", "'infolist'", "]", "path_arr", "=", "[", "os", ".", "path", ".", "join", "(", "CRUD_PATH", ",", "x", ")", "for", "x", "in", "tag_arr"...
Build the directory used for templates.
[ "Build", "the", "directory", "used", "for", "templates", "." ]
6567c7fe2604a1d646d4570c017840958630ed2b
https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/script/autocrud/base_crud.py#L31-L40
5,167
bukun/TorCMS
torcms/model/reply_model.py
MReply.create_reply
def create_reply(post_data): ''' Create the reply. ''' uid = tools.get_uuid() TabReply.create( uid=uid, post_id=post_data['post_id'], user_name=post_data['user_name'], user_id=post_data['user_id'], timestamp=tools.timestamp(), date=datetime.datetime.now(), cnt_md=tornado.escape.xhtml_escape(post_data['cnt_reply']), cnt_html=tools.markdown2html(post_data['cnt_reply']), vote=0 ) return uid
python
def create_reply(post_data): ''' Create the reply. ''' uid = tools.get_uuid() TabReply.create( uid=uid, post_id=post_data['post_id'], user_name=post_data['user_name'], user_id=post_data['user_id'], timestamp=tools.timestamp(), date=datetime.datetime.now(), cnt_md=tornado.escape.xhtml_escape(post_data['cnt_reply']), cnt_html=tools.markdown2html(post_data['cnt_reply']), vote=0 ) return uid
[ "def", "create_reply", "(", "post_data", ")", ":", "uid", "=", "tools", ".", "get_uuid", "(", ")", "TabReply", ".", "create", "(", "uid", "=", "uid", ",", "post_id", "=", "post_data", "[", "'post_id'", "]", ",", "user_name", "=", "post_data", "[", "'us...
Create the reply.
[ "Create", "the", "reply", "." ]
6567c7fe2604a1d646d4570c017840958630ed2b
https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/model/reply_model.py#L33-L49
5,168
bukun/TorCMS
torcms/model/reply_model.py
MReply.query_by_post
def query_by_post(postid): ''' Get reply list of certain post. ''' return TabReply.select().where( TabReply.post_id == postid ).order_by(TabReply.timestamp.desc())
python
def query_by_post(postid): ''' Get reply list of certain post. ''' return TabReply.select().where( TabReply.post_id == postid ).order_by(TabReply.timestamp.desc())
[ "def", "query_by_post", "(", "postid", ")", ":", "return", "TabReply", ".", "select", "(", ")", ".", "where", "(", "TabReply", ".", "post_id", "==", "postid", ")", ".", "order_by", "(", "TabReply", ".", "timestamp", ".", "desc", "(", ")", ")" ]
Get reply list of certain post.
[ "Get", "reply", "list", "of", "certain", "post", "." ]
6567c7fe2604a1d646d4570c017840958630ed2b
https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/model/reply_model.py#L52-L58
5,169
bukun/TorCMS
ext_script/autocrud/fetch_html_dic.py
__write_filter_dic
def __write_filter_dic(wk_sheet, column): ''' return filter dic for certain column ''' row1_val = wk_sheet['{0}1'.format(column)].value row2_val = wk_sheet['{0}2'.format(column)].value row3_val = wk_sheet['{0}3'.format(column)].value row4_val = wk_sheet['{0}4'.format(column)].value if row1_val and row1_val.strip() != '': row2_val = row2_val.strip() slug_name = row1_val.strip() c_name = row2_val.strip() tags1 = [x.strip() for x in row3_val.split(',')] tags_dic = {} # if only one tag, if len(tags1) == 1: xx_1 = row2_val.split(':') # 'text' # HTML text input control. if xx_1[0].lower() in INPUT_ARR: xx_1[0] = xx_1[0].lower() else: xx_1[0] = 'text' if len(xx_1) == 2: ctr_type, unit = xx_1 else: ctr_type = xx_1[0] unit = '' tags_dic[1] = unit else: ctr_type = 'select' # HTML selectiom control. for index, tag_val in enumerate(tags1): # the index of tags_dic starts from 1. tags_dic[index + 1] = tag_val.strip() outkey = 'html_{0}'.format(slug_name) outval = { 'en': slug_name, 'zh': c_name, 'dic': tags_dic, 'type': ctr_type, 'display': row4_val, } return (outkey, outval) else: return (None, None)
python
def __write_filter_dic(wk_sheet, column): ''' return filter dic for certain column ''' row1_val = wk_sheet['{0}1'.format(column)].value row2_val = wk_sheet['{0}2'.format(column)].value row3_val = wk_sheet['{0}3'.format(column)].value row4_val = wk_sheet['{0}4'.format(column)].value if row1_val and row1_val.strip() != '': row2_val = row2_val.strip() slug_name = row1_val.strip() c_name = row2_val.strip() tags1 = [x.strip() for x in row3_val.split(',')] tags_dic = {} # if only one tag, if len(tags1) == 1: xx_1 = row2_val.split(':') # 'text' # HTML text input control. if xx_1[0].lower() in INPUT_ARR: xx_1[0] = xx_1[0].lower() else: xx_1[0] = 'text' if len(xx_1) == 2: ctr_type, unit = xx_1 else: ctr_type = xx_1[0] unit = '' tags_dic[1] = unit else: ctr_type = 'select' # HTML selectiom control. for index, tag_val in enumerate(tags1): # the index of tags_dic starts from 1. tags_dic[index + 1] = tag_val.strip() outkey = 'html_{0}'.format(slug_name) outval = { 'en': slug_name, 'zh': c_name, 'dic': tags_dic, 'type': ctr_type, 'display': row4_val, } return (outkey, outval) else: return (None, None)
[ "def", "__write_filter_dic", "(", "wk_sheet", ",", "column", ")", ":", "row1_val", "=", "wk_sheet", "[", "'{0}1'", ".", "format", "(", "column", ")", "]", ".", "value", "row2_val", "=", "wk_sheet", "[", "'{0}2'", ".", "format", "(", "column", ")", "]", ...
return filter dic for certain column
[ "return", "filter", "dic", "for", "certain", "column" ]
6567c7fe2604a1d646d4570c017840958630ed2b
https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/ext_script/autocrud/fetch_html_dic.py#L17-L67
5,170
bukun/TorCMS
torcms/model/wiki_hist_model.py
MWikiHist.get_last
def get_last(postid): ''' Get the last wiki in history. ''' recs = TabWikiHist.select().where( TabWikiHist.wiki_id == postid ).order_by(TabWikiHist.time_update.desc()) return None if recs.count() == 0 else recs.get()
python
def get_last(postid): ''' Get the last wiki in history. ''' recs = TabWikiHist.select().where( TabWikiHist.wiki_id == postid ).order_by(TabWikiHist.time_update.desc()) return None if recs.count() == 0 else recs.get()
[ "def", "get_last", "(", "postid", ")", ":", "recs", "=", "TabWikiHist", ".", "select", "(", ")", ".", "where", "(", "TabWikiHist", ".", "wiki_id", "==", "postid", ")", ".", "order_by", "(", "TabWikiHist", ".", "time_update", ".", "desc", "(", ")", ")",...
Get the last wiki in history.
[ "Get", "the", "last", "wiki", "in", "history", "." ]
6567c7fe2604a1d646d4570c017840958630ed2b
https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/model/wiki_hist_model.py#L11-L19
5,171
bukun/TorCMS
torcms/core/privilege.py
is_prived
def is_prived(usr_rule, def_rule): ''' Compare between two role string. ''' for iii in range(4): if def_rule[iii] == '0': continue if usr_rule[iii] >= def_rule[iii]: return True return False
python
def is_prived(usr_rule, def_rule): ''' Compare between two role string. ''' for iii in range(4): if def_rule[iii] == '0': continue if usr_rule[iii] >= def_rule[iii]: return True return False
[ "def", "is_prived", "(", "usr_rule", ",", "def_rule", ")", ":", "for", "iii", "in", "range", "(", "4", ")", ":", "if", "def_rule", "[", "iii", "]", "==", "'0'", ":", "continue", "if", "usr_rule", "[", "iii", "]", ">=", "def_rule", "[", "iii", "]", ...
Compare between two role string.
[ "Compare", "between", "two", "role", "string", "." ]
6567c7fe2604a1d646d4570c017840958630ed2b
https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/core/privilege.py#L10-L20
5,172
bukun/TorCMS
torcms/core/privilege.py
auth_view
def auth_view(method): ''' role for view. ''' def wrapper(self, *args, **kwargs): ''' wrapper. ''' if ROLE_CFG['view'] == '': return method(self, *args, **kwargs) elif self.current_user: if is_prived(self.userinfo.role, ROLE_CFG['view']): return method(self, *args, **kwargs) else: kwd = { 'info': 'No role', } self.render('misc/html/404.html', kwd=kwd, userinfo=self.userinfo) else: kwd = { 'info': 'No role', } self.render('misc/html/404.html', kwd=kwd, userinfo=self.userinfo) return wrapper
python
def auth_view(method): ''' role for view. ''' def wrapper(self, *args, **kwargs): ''' wrapper. ''' if ROLE_CFG['view'] == '': return method(self, *args, **kwargs) elif self.current_user: if is_prived(self.userinfo.role, ROLE_CFG['view']): return method(self, *args, **kwargs) else: kwd = { 'info': 'No role', } self.render('misc/html/404.html', kwd=kwd, userinfo=self.userinfo) else: kwd = { 'info': 'No role', } self.render('misc/html/404.html', kwd=kwd, userinfo=self.userinfo) return wrapper
[ "def", "auth_view", "(", "method", ")", ":", "def", "wrapper", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "'''\n wrapper.\n '''", "if", "ROLE_CFG", "[", "'view'", "]", "==", "''", ":", "return", "method", "(", "self",...
role for view.
[ "role", "for", "view", "." ]
6567c7fe2604a1d646d4570c017840958630ed2b
https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/core/privilege.py#L23-L54
5,173
xieqihui/pandas-multiprocess
pandas_multiprocess/multiprocess.py
multi_process
def multi_process(func, data, num_process=None, verbose=True, **args): '''Function to use multiprocessing to process pandas Dataframe. This function applies a function on each row of the input DataFrame by multiprocessing. Args: func (function): The function to apply on each row of the input Dataframe. The func must accept pandas.Series as the first positional argument and return a pandas.Series. data (pandas.DataFrame): A DataFrame to be processed. num_process (int, optional): The number of processes to run in parallel. Defaults to be the number of CPUs of the computer. verbose (bool, optional): Set to False to disable verbose output. args (dict): Keyword arguments to pass as keywords arguments to `func` return: A dataframe containing the results ''' # Check arguments value assert isinstance(data, pd.DataFrame), \ 'Input data must be a pandas.DataFrame instance' if num_process is None: num_process = multiprocessing.cpu_count() # Establish communication queues tasks = multiprocessing.JoinableQueue() results = multiprocessing.Queue() error_queue = multiprocessing.Queue() start_time = time.time() # Enqueue tasks num_task = len(data) for i in range(num_task): tasks.put(data.iloc[i, :]) # Add a poison pill for each consumer for i in range(num_process): tasks.put(None) logger.info('Create {} processes'.format(num_process)) consumers = [Consumer(func, tasks, results, error_queue, **args) for i in range(num_process)] for w in consumers: w.start() # Add a task tracking process task_tracker = TaskTracker(tasks, verbose) task_tracker.start() # Wait for all input data to be processed tasks.join() # If there is any error in any process, output the error messages num_error = error_queue.qsize() if num_error > 0: for i in range(num_error): logger.error(error_queue.get()) raise RuntimeError('Multi process jobs failed') else: # Collect results result_table = [] while num_task: result_table.append(results.get()) num_task -= 1 df_results = pd.DataFrame(result_table) logger.info("Jobs finished in {0:.2f}s".format( time.time()-start_time)) return df_results
python
def multi_process(func, data, num_process=None, verbose=True, **args): '''Function to use multiprocessing to process pandas Dataframe. This function applies a function on each row of the input DataFrame by multiprocessing. Args: func (function): The function to apply on each row of the input Dataframe. The func must accept pandas.Series as the first positional argument and return a pandas.Series. data (pandas.DataFrame): A DataFrame to be processed. num_process (int, optional): The number of processes to run in parallel. Defaults to be the number of CPUs of the computer. verbose (bool, optional): Set to False to disable verbose output. args (dict): Keyword arguments to pass as keywords arguments to `func` return: A dataframe containing the results ''' # Check arguments value assert isinstance(data, pd.DataFrame), \ 'Input data must be a pandas.DataFrame instance' if num_process is None: num_process = multiprocessing.cpu_count() # Establish communication queues tasks = multiprocessing.JoinableQueue() results = multiprocessing.Queue() error_queue = multiprocessing.Queue() start_time = time.time() # Enqueue tasks num_task = len(data) for i in range(num_task): tasks.put(data.iloc[i, :]) # Add a poison pill for each consumer for i in range(num_process): tasks.put(None) logger.info('Create {} processes'.format(num_process)) consumers = [Consumer(func, tasks, results, error_queue, **args) for i in range(num_process)] for w in consumers: w.start() # Add a task tracking process task_tracker = TaskTracker(tasks, verbose) task_tracker.start() # Wait for all input data to be processed tasks.join() # If there is any error in any process, output the error messages num_error = error_queue.qsize() if num_error > 0: for i in range(num_error): logger.error(error_queue.get()) raise RuntimeError('Multi process jobs failed') else: # Collect results result_table = [] while num_task: result_table.append(results.get()) num_task -= 1 df_results = pd.DataFrame(result_table) logger.info("Jobs finished in {0:.2f}s".format( time.time()-start_time)) return df_results
[ "def", "multi_process", "(", "func", ",", "data", ",", "num_process", "=", "None", ",", "verbose", "=", "True", ",", "*", "*", "args", ")", ":", "# Check arguments value", "assert", "isinstance", "(", "data", ",", "pd", ".", "DataFrame", ")", ",", "'Inpu...
Function to use multiprocessing to process pandas Dataframe. This function applies a function on each row of the input DataFrame by multiprocessing. Args: func (function): The function to apply on each row of the input Dataframe. The func must accept pandas.Series as the first positional argument and return a pandas.Series. data (pandas.DataFrame): A DataFrame to be processed. num_process (int, optional): The number of processes to run in parallel. Defaults to be the number of CPUs of the computer. verbose (bool, optional): Set to False to disable verbose output. args (dict): Keyword arguments to pass as keywords arguments to `func` return: A dataframe containing the results
[ "Function", "to", "use", "multiprocessing", "to", "process", "pandas", "Dataframe", "." ]
b4d1b7357a446ded93183fb7b3e0d464ac7cc784
https://github.com/xieqihui/pandas-multiprocess/blob/b4d1b7357a446ded93183fb7b3e0d464ac7cc784/pandas_multiprocess/multiprocess.py#L125-L186
5,174
xieqihui/pandas-multiprocess
examples/example.py
func
def func(data_row, wait): ''' A sample function It takes 'wait' seconds to calculate the sum of each row ''' time.sleep(wait) data_row['sum'] = data_row['col_1'] + data_row['col_2'] return data_row
python
def func(data_row, wait): ''' A sample function It takes 'wait' seconds to calculate the sum of each row ''' time.sleep(wait) data_row['sum'] = data_row['col_1'] + data_row['col_2'] return data_row
[ "def", "func", "(", "data_row", ",", "wait", ")", ":", "time", ".", "sleep", "(", "wait", ")", "data_row", "[", "'sum'", "]", "=", "data_row", "[", "'col_1'", "]", "+", "data_row", "[", "'col_2'", "]", "return", "data_row" ]
A sample function It takes 'wait' seconds to calculate the sum of each row
[ "A", "sample", "function", "It", "takes", "wait", "seconds", "to", "calculate", "the", "sum", "of", "each", "row" ]
b4d1b7357a446ded93183fb7b3e0d464ac7cc784
https://github.com/xieqihui/pandas-multiprocess/blob/b4d1b7357a446ded93183fb7b3e0d464ac7cc784/examples/example.py#L7-L13
5,175
BYU-Hydroinformatics/HydroErr
HydroErr/HydroErr.py
me
def me(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False, remove_zero=False): """Compute the mean error of the simulated and observed data. .. image:: /pictures/ME.png **Range:** -inf < MAE < inf, data units, closer to zero is better, indicates bias. **Notes:** The mean error (ME) measures the difference between the simulated data and the observed data. For the mean error, a smaller number indicates a better fit to the original data. Note that if the error is in the form of random noise, the mean error will be very small, which can skew the accuracy of this metric. ME is cumulative and will be small even if there are large positive and negative errors that balance. Parameters ---------- simulated_array: one dimensional ndarray An array of simulated data from the time series. observed_array: one dimensional ndarray An array of observed data from the time series. replace_nan: float, optional If given, indicates which value to replace NaN values with in the two arrays. If None, when a NaN value is found at the i-th position in the observed OR simulated array, the i-th value of the observed and simulated array are removed before the computation. replace_inf: float, optional If given, indicates which value to replace Inf values with in the two arrays. If None, when an inf value is found at the i-th position in the observed OR simulated array, the i-th value of the observed and simulated array are removed before the computation. remove_neg: boolean, optional If True, when a negative value is found at the i-th position in the observed OR simulated array, the i-th value of the observed AND simulated array are removed before the computation. remove_zero: boolean, optional If true, when a zero value is found at the i-th position in the observed OR simulated array, the i-th value of the observed AND simulated array are removed before the computation. Returns ------- float The mean error value. Examples -------- Note that in this example the random noise cancels, leaving a very small ME. >>> import HydroErr as he >>> import numpy as np >>> # Seed for reproducibility >>> np.random.seed(54839) >>> x = np.arange(100) / 20 >>> sim = np.sin(x) + 2 >>> obs = sim * (((np.random.rand(100) - 0.5) / 10) + 1) >>> he.me(sim, obs) -0.006832220968967168 References ---------- - Fisher, R.A., 1920. A Mathematical Examination of the Methods of Determining the Accuracy of an Observation by the Mean Error, and by the Mean Square Error. Monthly Notices of the Royal Astronomical Society 80 758 - 770. """ # Treating missing values simulated_array, observed_array = treat_values(simulated_array, observed_array, replace_nan=replace_nan, replace_inf=replace_inf, remove_neg=remove_neg, remove_zero=remove_zero) return np.mean(simulated_array - observed_array)
python
def me(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False, remove_zero=False): # Treating missing values simulated_array, observed_array = treat_values(simulated_array, observed_array, replace_nan=replace_nan, replace_inf=replace_inf, remove_neg=remove_neg, remove_zero=remove_zero) return np.mean(simulated_array - observed_array)
[ "def", "me", "(", "simulated_array", ",", "observed_array", ",", "replace_nan", "=", "None", ",", "replace_inf", "=", "None", ",", "remove_neg", "=", "False", ",", "remove_zero", "=", "False", ")", ":", "# Treating missing values", "simulated_array", ",", "obser...
Compute the mean error of the simulated and observed data. .. image:: /pictures/ME.png **Range:** -inf < MAE < inf, data units, closer to zero is better, indicates bias. **Notes:** The mean error (ME) measures the difference between the simulated data and the observed data. For the mean error, a smaller number indicates a better fit to the original data. Note that if the error is in the form of random noise, the mean error will be very small, which can skew the accuracy of this metric. ME is cumulative and will be small even if there are large positive and negative errors that balance. Parameters ---------- simulated_array: one dimensional ndarray An array of simulated data from the time series. observed_array: one dimensional ndarray An array of observed data from the time series. replace_nan: float, optional If given, indicates which value to replace NaN values with in the two arrays. If None, when a NaN value is found at the i-th position in the observed OR simulated array, the i-th value of the observed and simulated array are removed before the computation. replace_inf: float, optional If given, indicates which value to replace Inf values with in the two arrays. If None, when an inf value is found at the i-th position in the observed OR simulated array, the i-th value of the observed and simulated array are removed before the computation. remove_neg: boolean, optional If True, when a negative value is found at the i-th position in the observed OR simulated array, the i-th value of the observed AND simulated array are removed before the computation. remove_zero: boolean, optional If true, when a zero value is found at the i-th position in the observed OR simulated array, the i-th value of the observed AND simulated array are removed before the computation. Returns ------- float The mean error value. Examples -------- Note that in this example the random noise cancels, leaving a very small ME. >>> import HydroErr as he >>> import numpy as np >>> # Seed for reproducibility >>> np.random.seed(54839) >>> x = np.arange(100) / 20 >>> sim = np.sin(x) + 2 >>> obs = sim * (((np.random.rand(100) - 0.5) / 10) + 1) >>> he.me(sim, obs) -0.006832220968967168 References ---------- - Fisher, R.A., 1920. A Mathematical Examination of the Methods of Determining the Accuracy of an Observation by the Mean Error, and by the Mean Square Error. Monthly Notices of the Royal Astronomical Society 80 758 - 770.
[ "Compute", "the", "mean", "error", "of", "the", "simulated", "and", "observed", "data", "." ]
42a84f3e006044f450edc7393ed54d59f27ef35b
https://github.com/BYU-Hydroinformatics/HydroErr/blob/42a84f3e006044f450edc7393ed54d59f27ef35b/HydroErr/HydroErr.py#L39-L114
5,176
BYU-Hydroinformatics/HydroErr
HydroErr/HydroErr.py
mae
def mae(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False, remove_zero=False): """Compute the mean absolute error of the simulated and observed data. .. image:: /pictures/MAE.png **Range:** 0 ≤ MAE < inf, data units, smaller is better. **Notes:** The ME measures the absolute difference between the simulated data and the observed data. For the mean abolute error, a smaller number indicates a better fit to the original data. Also note that random errors do not cancel. Also referred to as an L1-norm. Parameters ---------- simulated_array: one dimensional ndarray An array of simulated data from the time series. observed_array: one dimensional ndarray An array of observed data from the time series. replace_nan: float, optional If given, indicates which value to replace NaN values with in the two arrays. If None, when a NaN value is found at the i-th position in the observed OR simulated array, the i-th value of the observed and simulated array are removed before the computation. replace_inf: float, optional If given, indicates which value to replace Inf values with in the two arrays. If None, when an inf value is found at the i-th position in the observed OR simulated array, the i-th value of the observed and simulated array are removed before the computation. remove_neg: boolean, optional If True, when a negative value is found at the i-th position in the observed OR simulated array, the i-th value of the observed AND simulated array are removed before the computation. remove_zero: boolean, optional If true, when a zero value is found at the i-th position in the observed OR simulated array, the i-th value of the observed AND simulated array are removed before the computation. Returns ------- float The mean absolute error value. References ---------- - Willmott, Cort J., and Kenji Matsuura. “Advantages of the Mean Absolute Error (MAE) over the Root Mean Square Error (RMSE) in Assessing Average Model Performance.” Climate Research 30, no. 1 (2005): 79–82. - Willmott, Cort J., and Kenji Matsuura. “On the Use of Dimensioned Measures of Error to Evaluate the Performance of Spatial Interpolators.” International Journal of Geographical Information Science 20, no. 1 (2006): 89–102. Examples -------- >>> import HydroErr as he >>> import numpy as np >>> sim = np.array([5, 7, 9, 2, 4.5, 6.7]) >>> obs = np.array([4.7, 6, 10, 2.5, 4, 6.8]) >>> he.mae(sim, obs) 0.5666666666666665 """ # Checking and cleaning the data simulated_array, observed_array = treat_values( simulated_array, observed_array, replace_nan=replace_nan, replace_inf=replace_inf, remove_neg=remove_neg, remove_zero=remove_zero ) return np.mean(np.absolute(simulated_array - observed_array))
python
def mae(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False, remove_zero=False): # Checking and cleaning the data simulated_array, observed_array = treat_values( simulated_array, observed_array, replace_nan=replace_nan, replace_inf=replace_inf, remove_neg=remove_neg, remove_zero=remove_zero ) return np.mean(np.absolute(simulated_array - observed_array))
[ "def", "mae", "(", "simulated_array", ",", "observed_array", ",", "replace_nan", "=", "None", ",", "replace_inf", "=", "None", ",", "remove_neg", "=", "False", ",", "remove_zero", "=", "False", ")", ":", "# Checking and cleaning the data", "simulated_array", ",", ...
Compute the mean absolute error of the simulated and observed data. .. image:: /pictures/MAE.png **Range:** 0 ≤ MAE < inf, data units, smaller is better. **Notes:** The ME measures the absolute difference between the simulated data and the observed data. For the mean abolute error, a smaller number indicates a better fit to the original data. Also note that random errors do not cancel. Also referred to as an L1-norm. Parameters ---------- simulated_array: one dimensional ndarray An array of simulated data from the time series. observed_array: one dimensional ndarray An array of observed data from the time series. replace_nan: float, optional If given, indicates which value to replace NaN values with in the two arrays. If None, when a NaN value is found at the i-th position in the observed OR simulated array, the i-th value of the observed and simulated array are removed before the computation. replace_inf: float, optional If given, indicates which value to replace Inf values with in the two arrays. If None, when an inf value is found at the i-th position in the observed OR simulated array, the i-th value of the observed and simulated array are removed before the computation. remove_neg: boolean, optional If True, when a negative value is found at the i-th position in the observed OR simulated array, the i-th value of the observed AND simulated array are removed before the computation. remove_zero: boolean, optional If true, when a zero value is found at the i-th position in the observed OR simulated array, the i-th value of the observed AND simulated array are removed before the computation. Returns ------- float The mean absolute error value. References ---------- - Willmott, Cort J., and Kenji Matsuura. “Advantages of the Mean Absolute Error (MAE) over the Root Mean Square Error (RMSE) in Assessing Average Model Performance.” Climate Research 30, no. 1 (2005): 79–82. - Willmott, Cort J., and Kenji Matsuura. “On the Use of Dimensioned Measures of Error to Evaluate the Performance of Spatial Interpolators.” International Journal of Geographical Information Science 20, no. 1 (2006): 89–102. Examples -------- >>> import HydroErr as he >>> import numpy as np >>> sim = np.array([5, 7, 9, 2, 4.5, 6.7]) >>> obs = np.array([4.7, 6, 10, 2.5, 4, 6.8]) >>> he.mae(sim, obs) 0.5666666666666665
[ "Compute", "the", "mean", "absolute", "error", "of", "the", "simulated", "and", "observed", "data", "." ]
42a84f3e006044f450edc7393ed54d59f27ef35b
https://github.com/BYU-Hydroinformatics/HydroErr/blob/42a84f3e006044f450edc7393ed54d59f27ef35b/HydroErr/HydroErr.py#L117-L193
5,177
BYU-Hydroinformatics/HydroErr
HydroErr/HydroErr.py
mle
def mle(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False, remove_zero=False): """ Compute the mean log error of the simulated and observed data. .. image:: /pictures/MLE.png **Range:** -inf < MLE < inf, data units, closer to zero is better. **Notes** Same as the mean erro (ME) only use log ratios as the error term. Limits the impact of outliers, more evenly weights high and low data values. Parameters ---------- simulated_array: one dimensional ndarray An array of simulated data from the time series. observed_array: one dimensional ndarray An array of observed data from the time series. replace_nan: float, optional If given, indicates which value to replace NaN values with in the two arrays. If None, when a NaN value is found at the i-th position in the observed OR simulated array, the i-th value of the observed and simulated array are removed before the computation. replace_inf: float, optional If given, indicates which value to replace Inf values with in the two arrays. If None, when an inf value is found at the i-th position in the observed OR simulated array, the i-th value of the observed and simulated array are removed before the computation. remove_neg: boolean, optional If True, when a negative value is found at the i-th position in the observed OR simulated array, the i-th value of the observed AND simulated array are removed before the computation. remove_zero: boolean, optional If true, when a zero value is found at the i-th position in the observed OR simulated array, the i-th value of the observed AND simulated array are removed before the computation. Returns ------- float The mean log error value. Examples -------- Note that the value is very small because it is in log space. >>> import HydroErr as he >>> import numpy as np >>> sim = np.array([5, 7, 9, 2, 4.5, 6.7]) >>> obs = np.array([4.7, 6, 10, 2.5, 4, 6.8]) >>> he.mle(sim, obs) 0.002961767058151136 References ---------- - Törnqvist, Leo, Pentti Vartia, and Yrjö O. Vartia. “How Should Relative Changes Be Measured?” The American Statistician 39, no. 1 (1985): 43–46. """ # Checking and cleaning the data simulated_array, observed_array = treat_values( simulated_array, observed_array, replace_nan=replace_nan, replace_inf=replace_inf, remove_neg=remove_neg, remove_zero=remove_zero ) sim_log = np.log1p(simulated_array) obs_log = np.log1p(observed_array) return np.mean(sim_log - obs_log)
python
def mle(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False, remove_zero=False): # Checking and cleaning the data simulated_array, observed_array = treat_values( simulated_array, observed_array, replace_nan=replace_nan, replace_inf=replace_inf, remove_neg=remove_neg, remove_zero=remove_zero ) sim_log = np.log1p(simulated_array) obs_log = np.log1p(observed_array) return np.mean(sim_log - obs_log)
[ "def", "mle", "(", "simulated_array", ",", "observed_array", ",", "replace_nan", "=", "None", ",", "replace_inf", "=", "None", ",", "remove_neg", "=", "False", ",", "remove_zero", "=", "False", ")", ":", "# Checking and cleaning the data", "simulated_array", ",", ...
Compute the mean log error of the simulated and observed data. .. image:: /pictures/MLE.png **Range:** -inf < MLE < inf, data units, closer to zero is better. **Notes** Same as the mean erro (ME) only use log ratios as the error term. Limits the impact of outliers, more evenly weights high and low data values. Parameters ---------- simulated_array: one dimensional ndarray An array of simulated data from the time series. observed_array: one dimensional ndarray An array of observed data from the time series. replace_nan: float, optional If given, indicates which value to replace NaN values with in the two arrays. If None, when a NaN value is found at the i-th position in the observed OR simulated array, the i-th value of the observed and simulated array are removed before the computation. replace_inf: float, optional If given, indicates which value to replace Inf values with in the two arrays. If None, when an inf value is found at the i-th position in the observed OR simulated array, the i-th value of the observed and simulated array are removed before the computation. remove_neg: boolean, optional If True, when a negative value is found at the i-th position in the observed OR simulated array, the i-th value of the observed AND simulated array are removed before the computation. remove_zero: boolean, optional If true, when a zero value is found at the i-th position in the observed OR simulated array, the i-th value of the observed AND simulated array are removed before the computation. Returns ------- float The mean log error value. Examples -------- Note that the value is very small because it is in log space. >>> import HydroErr as he >>> import numpy as np >>> sim = np.array([5, 7, 9, 2, 4.5, 6.7]) >>> obs = np.array([4.7, 6, 10, 2.5, 4, 6.8]) >>> he.mle(sim, obs) 0.002961767058151136 References ---------- - Törnqvist, Leo, Pentti Vartia, and Yrjö O. Vartia. “How Should Relative Changes Be Measured?” The American Statistician 39, no. 1 (1985): 43–46.
[ "Compute", "the", "mean", "log", "error", "of", "the", "simulated", "and", "observed", "data", "." ]
42a84f3e006044f450edc7393ed54d59f27ef35b
https://github.com/BYU-Hydroinformatics/HydroErr/blob/42a84f3e006044f450edc7393ed54d59f27ef35b/HydroErr/HydroErr.py#L271-L348
5,178
BYU-Hydroinformatics/HydroErr
HydroErr/HydroErr.py
ed
def ed(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False, remove_zero=False): """ Compute the Euclidean distance between predicted and observed values in vector space. .. image:: /pictures/ED.png **Range** 0 ≤ ED < inf, smaller is better. **Notes** Also sometimes referred to as the L2-norm. Parameters ---------- simulated_array: one dimensional ndarray An array of simulated data from the time series. observed_array: one dimensional ndarray An array of observed data from the time series. replace_nan: float, optional If given, indicates which value to replace NaN values with in the two arrays. If None, when a NaN value is found at the i-th position in the observed OR simulated array, the i-th value of the observed and simulated array are removed before the computation. replace_inf: float, optional If given, indicates which value to replace Inf values with in the two arrays. If None, when an inf value is found at the i-th position in the observed OR simulated array, the i-th value of the observed and simulated array are removed before the computation. remove_neg: boolean, optional If True, when a negative value is found at the i-th position in the observed OR simulated array, the i-th value of the observed AND simulated array are removed before the computation. remove_zero: boolean, optional If true, when a zero value is found at the i-th position in the observed OR simulated array, the i-th value of the observed AND simulated array are removed before the computation. Examples -------- >>> import HydroErr as he >>> import numpy as np >>> sim = np.array([5, 7, 9, 2, 4.5, 6.7]) >>> obs = np.array([4.7, 6, 10, 2.5, 4, 7]) >>> he.ed(sim, obs) 1.63707055437449 Returns ------- float The euclidean distance error value. References ---------- - Kennard, M. J., Mackay, S. J., Pusey, B. J., Olden, J. D., & Marsh, N. (2010). Quantifying uncertainty in estimation of hydrologic metrics for ecohydrological studies. River Research and Applications, 26(2), 137-156. """ # Checking and cleaning the data simulated_array, observed_array = treat_values( simulated_array, observed_array, replace_nan=replace_nan, replace_inf=replace_inf, remove_neg=remove_neg, remove_zero=remove_zero ) return np.linalg.norm(observed_array - simulated_array)
python
def ed(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False, remove_zero=False): # Checking and cleaning the data simulated_array, observed_array = treat_values( simulated_array, observed_array, replace_nan=replace_nan, replace_inf=replace_inf, remove_neg=remove_neg, remove_zero=remove_zero ) return np.linalg.norm(observed_array - simulated_array)
[ "def", "ed", "(", "simulated_array", ",", "observed_array", ",", "replace_nan", "=", "None", ",", "replace_inf", "=", "None", ",", "remove_neg", "=", "False", ",", "remove_zero", "=", "False", ")", ":", "# Checking and cleaning the data", "simulated_array", ",", ...
Compute the Euclidean distance between predicted and observed values in vector space. .. image:: /pictures/ED.png **Range** 0 ≤ ED < inf, smaller is better. **Notes** Also sometimes referred to as the L2-norm. Parameters ---------- simulated_array: one dimensional ndarray An array of simulated data from the time series. observed_array: one dimensional ndarray An array of observed data from the time series. replace_nan: float, optional If given, indicates which value to replace NaN values with in the two arrays. If None, when a NaN value is found at the i-th position in the observed OR simulated array, the i-th value of the observed and simulated array are removed before the computation. replace_inf: float, optional If given, indicates which value to replace Inf values with in the two arrays. If None, when an inf value is found at the i-th position in the observed OR simulated array, the i-th value of the observed and simulated array are removed before the computation. remove_neg: boolean, optional If True, when a negative value is found at the i-th position in the observed OR simulated array, the i-th value of the observed AND simulated array are removed before the computation. remove_zero: boolean, optional If true, when a zero value is found at the i-th position in the observed OR simulated array, the i-th value of the observed AND simulated array are removed before the computation. Examples -------- >>> import HydroErr as he >>> import numpy as np >>> sim = np.array([5, 7, 9, 2, 4.5, 6.7]) >>> obs = np.array([4.7, 6, 10, 2.5, 4, 7]) >>> he.ed(sim, obs) 1.63707055437449 Returns ------- float The euclidean distance error value. References ---------- - Kennard, M. J., Mackay, S. J., Pusey, B. J., Olden, J. D., & Marsh, N. (2010). Quantifying uncertainty in estimation of hydrologic metrics for ecohydrological studies. River Research and Applications, 26(2), 137-156.
[ "Compute", "the", "Euclidean", "distance", "between", "predicted", "and", "observed", "values", "in", "vector", "space", "." ]
42a84f3e006044f450edc7393ed54d59f27ef35b
https://github.com/BYU-Hydroinformatics/HydroErr/blob/42a84f3e006044f450edc7393ed54d59f27ef35b/HydroErr/HydroErr.py#L733-L805
5,179
BYU-Hydroinformatics/HydroErr
HydroErr/HydroErr.py
ned
def ned(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False, remove_zero=False): """ Compute the normalized Euclidian distance between the simulated and observed data in vector space. .. image:: /pictures/NED.png **Range** 0 ≤ NED < inf, smaller is better. **Notes** Also sometimes referred to as the squared L2-norm. Parameters ---------- simulated_array: one dimensional ndarray An array of simulated data from the time series. observed_array: one dimensional ndarray An array of observed data from the time series. replace_nan: float, optional If given, indicates which value to replace NaN values with in the two arrays. If None, when a NaN value is found at the i-th position in the observed OR simulated array, the i-th value of the observed and simulated array are removed before the computation. replace_inf: float, optional If given, indicates which value to replace Inf values with in the two arrays. If None, when an inf value is found at the i-th position in the observed OR simulated array, the i-th value of the observed and simulated array are removed before the computation. remove_neg: boolean, optional If True, when a negative value is found at the i-th position in the observed OR simulated array, the i-th value of the observed AND simulated array are removed before the computation. remove_zero: boolean, optional If true, when a zero value is found at the i-th position in the observed OR simulated array, the i-th value of the observed AND simulated array are removed before the computation. Returns ------- float The normalized euclidean distance value. Examples -------- >>> import HydroErr as he >>> import numpy as np >>> sim = np.array([5, 7, 9, 2, 4.5, 6.7]) >>> obs = np.array([4.7, 6, 10, 2.5, 4, 7]) >>> he.ned(sim, obs) 0.2872053604165771 References ---------- - Kennard, M. J., Mackay, S. J., Pusey, B. J., Olden, J. D., & Marsh, N. (2010). Quantifying uncertainty in estimation of hydrologic metrics for ecohydrological studies. River Research and Applications, 26(2), 137-156. """ # Checking and cleaning the data simulated_array, observed_array = treat_values( simulated_array, observed_array, replace_nan=replace_nan, replace_inf=replace_inf, remove_neg=remove_neg, remove_zero=remove_zero ) a = observed_array / np.mean(observed_array) b = simulated_array / np.mean(simulated_array) return np.linalg.norm(a - b)
python
def ned(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False, remove_zero=False): # Checking and cleaning the data simulated_array, observed_array = treat_values( simulated_array, observed_array, replace_nan=replace_nan, replace_inf=replace_inf, remove_neg=remove_neg, remove_zero=remove_zero ) a = observed_array / np.mean(observed_array) b = simulated_array / np.mean(simulated_array) return np.linalg.norm(a - b)
[ "def", "ned", "(", "simulated_array", ",", "observed_array", ",", "replace_nan", "=", "None", ",", "replace_inf", "=", "None", ",", "remove_neg", "=", "False", ",", "remove_zero", "=", "False", ")", ":", "# Checking and cleaning the data", "simulated_array", ",", ...
Compute the normalized Euclidian distance between the simulated and observed data in vector space. .. image:: /pictures/NED.png **Range** 0 ≤ NED < inf, smaller is better. **Notes** Also sometimes referred to as the squared L2-norm. Parameters ---------- simulated_array: one dimensional ndarray An array of simulated data from the time series. observed_array: one dimensional ndarray An array of observed data from the time series. replace_nan: float, optional If given, indicates which value to replace NaN values with in the two arrays. If None, when a NaN value is found at the i-th position in the observed OR simulated array, the i-th value of the observed and simulated array are removed before the computation. replace_inf: float, optional If given, indicates which value to replace Inf values with in the two arrays. If None, when an inf value is found at the i-th position in the observed OR simulated array, the i-th value of the observed and simulated array are removed before the computation. remove_neg: boolean, optional If True, when a negative value is found at the i-th position in the observed OR simulated array, the i-th value of the observed AND simulated array are removed before the computation. remove_zero: boolean, optional If true, when a zero value is found at the i-th position in the observed OR simulated array, the i-th value of the observed AND simulated array are removed before the computation. Returns ------- float The normalized euclidean distance value. Examples -------- >>> import HydroErr as he >>> import numpy as np >>> sim = np.array([5, 7, 9, 2, 4.5, 6.7]) >>> obs = np.array([4.7, 6, 10, 2.5, 4, 7]) >>> he.ned(sim, obs) 0.2872053604165771 References ---------- - Kennard, M. J., Mackay, S. J., Pusey, B. J., Olden, J. D., & Marsh, N. (2010). Quantifying uncertainty in estimation of hydrologic metrics for ecohydrological studies. River Research and Applications, 26(2), 137-156.
[ "Compute", "the", "normalized", "Euclidian", "distance", "between", "the", "simulated", "and", "observed", "data", "in", "vector", "space", "." ]
42a84f3e006044f450edc7393ed54d59f27ef35b
https://github.com/BYU-Hydroinformatics/HydroErr/blob/42a84f3e006044f450edc7393ed54d59f27ef35b/HydroErr/HydroErr.py#L808-L883
5,180
BYU-Hydroinformatics/HydroErr
HydroErr/HydroErr.py
nrmse_range
def nrmse_range(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False, remove_zero=False): """Compute the range normalized root mean square error between the simulated and observed data. .. image:: /pictures/NRMSE_Range.png **Range:** 0 ≤ NRMSE < inf. **Notes:** This metric is the RMSE normalized by the range of the observed time series (x). Normalizing allows comparison between data sets with different scales. The NRMSErange is the most sensitive to outliers of the three normalized rmse metrics. Parameters ---------- simulated_array: one dimensional ndarray An array of simulated data from the time series. observed_array: one dimensional ndarray An array of observed data from the time series. replace_nan: float, optional If given, indicates which value to replace NaN values with in the two arrays. If None, when a NaN value is found at the i-th position in the observed OR simulated array, the i-th value of the observed and simulated array are removed before the computation. replace_inf: float, optional If given, indicates which value to replace Inf values with in the two arrays. If None, when an inf value is found at the i-th position in the observed OR simulated array, the i-th value of the observed and simulated array are removed before the computation. remove_neg: boolean, optional If True, when a negative value is found at the i-th position in the observed OR simulated array, the i-th value of the observed AND simulated array are removed before the computation. remove_zero: boolean, optional If true, when a zero value is found at the i-th position in the observed OR simulated array, the i-th value of the observed AND simulated array are removed before the computation. Returns ------- float The range normalized root mean square error value. Examples -------- >>> import HydroErr as he >>> import numpy as np >>> sim = np.array([5, 7, 9, 2, 4.5, 6.7]) >>> obs = np.array([4.7, 6, 10, 2.5, 4, 7]) >>> he.nrmse_range(sim, obs) 0.0891108340256152 References ---------- - Pontius, R.G., Thontteh, O., Chen, H., 2008. Components of information for multiple resolution comparison between maps that share a real variable. Environmental and Ecological Statistics 15(2) 111-142. """ # Checking and cleaning the data simulated_array, observed_array = treat_values( simulated_array, observed_array, replace_nan=replace_nan, replace_inf=replace_inf, remove_neg=remove_neg, remove_zero=remove_zero ) rmse_value = np.sqrt(np.mean((simulated_array - observed_array) ** 2)) obs_max = np.max(observed_array) obs_min = np.min(observed_array) return rmse_value / (obs_max - obs_min)
python
def nrmse_range(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False, remove_zero=False): # Checking and cleaning the data simulated_array, observed_array = treat_values( simulated_array, observed_array, replace_nan=replace_nan, replace_inf=replace_inf, remove_neg=remove_neg, remove_zero=remove_zero ) rmse_value = np.sqrt(np.mean((simulated_array - observed_array) ** 2)) obs_max = np.max(observed_array) obs_min = np.min(observed_array) return rmse_value / (obs_max - obs_min)
[ "def", "nrmse_range", "(", "simulated_array", ",", "observed_array", ",", "replace_nan", "=", "None", ",", "replace_inf", "=", "None", ",", "remove_neg", "=", "False", ",", "remove_zero", "=", "False", ")", ":", "# Checking and cleaning the data", "simulated_array",...
Compute the range normalized root mean square error between the simulated and observed data. .. image:: /pictures/NRMSE_Range.png **Range:** 0 ≤ NRMSE < inf. **Notes:** This metric is the RMSE normalized by the range of the observed time series (x). Normalizing allows comparison between data sets with different scales. The NRMSErange is the most sensitive to outliers of the three normalized rmse metrics. Parameters ---------- simulated_array: one dimensional ndarray An array of simulated data from the time series. observed_array: one dimensional ndarray An array of observed data from the time series. replace_nan: float, optional If given, indicates which value to replace NaN values with in the two arrays. If None, when a NaN value is found at the i-th position in the observed OR simulated array, the i-th value of the observed and simulated array are removed before the computation. replace_inf: float, optional If given, indicates which value to replace Inf values with in the two arrays. If None, when an inf value is found at the i-th position in the observed OR simulated array, the i-th value of the observed and simulated array are removed before the computation. remove_neg: boolean, optional If True, when a negative value is found at the i-th position in the observed OR simulated array, the i-th value of the observed AND simulated array are removed before the computation. remove_zero: boolean, optional If true, when a zero value is found at the i-th position in the observed OR simulated array, the i-th value of the observed AND simulated array are removed before the computation. Returns ------- float The range normalized root mean square error value. Examples -------- >>> import HydroErr as he >>> import numpy as np >>> sim = np.array([5, 7, 9, 2, 4.5, 6.7]) >>> obs = np.array([4.7, 6, 10, 2.5, 4, 7]) >>> he.nrmse_range(sim, obs) 0.0891108340256152 References ---------- - Pontius, R.G., Thontteh, O., Chen, H., 2008. Components of information for multiple resolution comparison between maps that share a real variable. Environmental and Ecological Statistics 15(2) 111-142.
[ "Compute", "the", "range", "normalized", "root", "mean", "square", "error", "between", "the", "simulated", "and", "observed", "data", "." ]
42a84f3e006044f450edc7393ed54d59f27ef35b
https://github.com/BYU-Hydroinformatics/HydroErr/blob/42a84f3e006044f450edc7393ed54d59f27ef35b/HydroErr/HydroErr.py#L1044-L1121
5,181
BYU-Hydroinformatics/HydroErr
HydroErr/HydroErr.py
nrmse_mean
def nrmse_mean(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False, remove_zero=False): """Compute the mean normalized root mean square error between the simulated and observed data. .. image:: /pictures/NRMSE_Mean.png **Range:** 0 ≤ NRMSE < inf. **Notes:** This metric is the RMSE normalized by the mean of the observed time series (x). Normalizing allows comparison between data sets with different scales. Parameters ---------- simulated_array: one dimensional ndarray An array of simulated data from the time series. observed_array: one dimensional ndarray An array of observed data from the time series. replace_nan: float, optional If given, indicates which value to replace NaN values with in the two arrays. If None, when a NaN value is found at the i-th position in the observed OR simulated array, the i-th value of the observed and simulated array are removed before the computation. replace_inf: float, optional If given, indicates which value to replace Inf values with in the two arrays. If None, when an inf value is found at the i-th position in the observed OR simulated array, the i-th value of the observed and simulated array are removed before the computation. remove_neg: boolean, optional If True, when a negative value is found at the i-th position in the observed OR simulated array, the i-th value of the observed AND simulated array are removed before the computation. remove_zero: boolean, optional If true, when a zero value is found at the i-th position in the observed OR simulated array, the i-th value of the observed AND simulated array are removed before the computation. Returns ------- float The mean normalized root mean square error. Examples -------- >>> import HydroErr as he >>> import numpy as np >>> sim = np.array([5, 7, 9, 2, 4.5, 6.7]) >>> obs = np.array([4.7, 6, 10, 2.5, 4, 7]) >>> he.nrmse_mean(sim, obs) 0.11725109740212526 References ---------- - Pontius, R.G., Thontteh, O., Chen, H., 2008. Components of information for multiple resolution comparison between maps that share a real variable. Environmental and Ecological Statistics 15(2) 111-142. """ # Checking and cleaning the data simulated_array, observed_array = treat_values( simulated_array, observed_array, replace_nan=replace_nan, replace_inf=replace_inf, remove_neg=remove_neg, remove_zero=remove_zero ) rmse_value = np.sqrt(np.mean((simulated_array - observed_array) ** 2)) obs_mean = np.mean(observed_array) return rmse_value / obs_mean
python
def nrmse_mean(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False, remove_zero=False): # Checking and cleaning the data simulated_array, observed_array = treat_values( simulated_array, observed_array, replace_nan=replace_nan, replace_inf=replace_inf, remove_neg=remove_neg, remove_zero=remove_zero ) rmse_value = np.sqrt(np.mean((simulated_array - observed_array) ** 2)) obs_mean = np.mean(observed_array) return rmse_value / obs_mean
[ "def", "nrmse_mean", "(", "simulated_array", ",", "observed_array", ",", "replace_nan", "=", "None", ",", "replace_inf", "=", "None", ",", "remove_neg", "=", "False", ",", "remove_zero", "=", "False", ")", ":", "# Checking and cleaning the data", "simulated_array", ...
Compute the mean normalized root mean square error between the simulated and observed data. .. image:: /pictures/NRMSE_Mean.png **Range:** 0 ≤ NRMSE < inf. **Notes:** This metric is the RMSE normalized by the mean of the observed time series (x). Normalizing allows comparison between data sets with different scales. Parameters ---------- simulated_array: one dimensional ndarray An array of simulated data from the time series. observed_array: one dimensional ndarray An array of observed data from the time series. replace_nan: float, optional If given, indicates which value to replace NaN values with in the two arrays. If None, when a NaN value is found at the i-th position in the observed OR simulated array, the i-th value of the observed and simulated array are removed before the computation. replace_inf: float, optional If given, indicates which value to replace Inf values with in the two arrays. If None, when an inf value is found at the i-th position in the observed OR simulated array, the i-th value of the observed and simulated array are removed before the computation. remove_neg: boolean, optional If True, when a negative value is found at the i-th position in the observed OR simulated array, the i-th value of the observed AND simulated array are removed before the computation. remove_zero: boolean, optional If true, when a zero value is found at the i-th position in the observed OR simulated array, the i-th value of the observed AND simulated array are removed before the computation. Returns ------- float The mean normalized root mean square error. Examples -------- >>> import HydroErr as he >>> import numpy as np >>> sim = np.array([5, 7, 9, 2, 4.5, 6.7]) >>> obs = np.array([4.7, 6, 10, 2.5, 4, 7]) >>> he.nrmse_mean(sim, obs) 0.11725109740212526 References ---------- - Pontius, R.G., Thontteh, O., Chen, H., 2008. Components of information for multiple resolution comparison between maps that share a real variable. Environmental and Ecological Statistics 15(2) 111-142.
[ "Compute", "the", "mean", "normalized", "root", "mean", "square", "error", "between", "the", "simulated", "and", "observed", "data", "." ]
42a84f3e006044f450edc7393ed54d59f27ef35b
https://github.com/BYU-Hydroinformatics/HydroErr/blob/42a84f3e006044f450edc7393ed54d59f27ef35b/HydroErr/HydroErr.py#L1124-L1200
5,182
BYU-Hydroinformatics/HydroErr
HydroErr/HydroErr.py
nrmse_iqr
def nrmse_iqr(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False, remove_zero=False): """Compute the IQR normalized root mean square error between the simulated and observed data. .. image:: /pictures/NRMSE_IQR.png **Range:** 0 ≤ NRMSE < inf. **Notes:** This metric is the RMSE normalized by the interquartile range of the observed time series (x). Normalizing allows comparison between data sets with different scales. The NRMSEquartile is the least sensitive to outliers of the three normalized rmse metrics. Parameters ---------- simulated_array: one dimensional ndarray An array of simulated data from the time series. observed_array: one dimensional ndarray An array of observed data from the time series. replace_nan: float, optional If given, indicates which value to replace NaN values with in the two arrays. If None, when a NaN value is found at the i-th position in the observed OR simulated array, the i-th value of the observed and simulated array are removed before the computation. replace_inf: float, optional If given, indicates which value to replace Inf values with in the two arrays. If None, when an inf value is found at the i-th position in the observed OR simulated array, the i-th value of the observed and simulated array are removed before the computation. remove_neg: boolean, optional If True, when a negative value is found at the i-th position in the observed OR simulated array, the i-th value of the observed AND simulated array are removed before the computation. remove_zero: boolean, optional If true, when a zero value is found at the i-th position in the observed OR simulated array, the i-th value of the observed AND simulated array are removed before the computation. Returns ------- float The IQR normalized root mean square error. Examples -------- >>> import HydroErr as he >>> import numpy as np >>> sim = np.array([5, 7, 9, 2, 4.5, 6.7]) >>> obs = np.array([4.7, 6, 10, 2.5, 4, 7]) >>> he.nrmse_iqr(sim, obs) 0.2595461185212093 References ---------- - Pontius, R.G., Thontteh, O., Chen, H., 2008. Components of information for multiple resolution comparison between maps that share a real variable. Environmental and Ecological Statistics 15(2) 111-142. """ # Checking and cleaning the data simulated_array, observed_array = treat_values( simulated_array, observed_array, replace_nan=replace_nan, replace_inf=replace_inf, remove_neg=remove_neg, remove_zero=remove_zero ) rmse_value = np.sqrt(np.mean((simulated_array - observed_array) ** 2)) q1 = np.percentile(observed_array, 25) q3 = np.percentile(observed_array, 75) iqr = q3 - q1 return rmse_value / iqr
python
def nrmse_iqr(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False, remove_zero=False): # Checking and cleaning the data simulated_array, observed_array = treat_values( simulated_array, observed_array, replace_nan=replace_nan, replace_inf=replace_inf, remove_neg=remove_neg, remove_zero=remove_zero ) rmse_value = np.sqrt(np.mean((simulated_array - observed_array) ** 2)) q1 = np.percentile(observed_array, 25) q3 = np.percentile(observed_array, 75) iqr = q3 - q1 return rmse_value / iqr
[ "def", "nrmse_iqr", "(", "simulated_array", ",", "observed_array", ",", "replace_nan", "=", "None", ",", "replace_inf", "=", "None", ",", "remove_neg", "=", "False", ",", "remove_zero", "=", "False", ")", ":", "# Checking and cleaning the data", "simulated_array", ...
Compute the IQR normalized root mean square error between the simulated and observed data. .. image:: /pictures/NRMSE_IQR.png **Range:** 0 ≤ NRMSE < inf. **Notes:** This metric is the RMSE normalized by the interquartile range of the observed time series (x). Normalizing allows comparison between data sets with different scales. The NRMSEquartile is the least sensitive to outliers of the three normalized rmse metrics. Parameters ---------- simulated_array: one dimensional ndarray An array of simulated data from the time series. observed_array: one dimensional ndarray An array of observed data from the time series. replace_nan: float, optional If given, indicates which value to replace NaN values with in the two arrays. If None, when a NaN value is found at the i-th position in the observed OR simulated array, the i-th value of the observed and simulated array are removed before the computation. replace_inf: float, optional If given, indicates which value to replace Inf values with in the two arrays. If None, when an inf value is found at the i-th position in the observed OR simulated array, the i-th value of the observed and simulated array are removed before the computation. remove_neg: boolean, optional If True, when a negative value is found at the i-th position in the observed OR simulated array, the i-th value of the observed AND simulated array are removed before the computation. remove_zero: boolean, optional If true, when a zero value is found at the i-th position in the observed OR simulated array, the i-th value of the observed AND simulated array are removed before the computation. Returns ------- float The IQR normalized root mean square error. Examples -------- >>> import HydroErr as he >>> import numpy as np >>> sim = np.array([5, 7, 9, 2, 4.5, 6.7]) >>> obs = np.array([4.7, 6, 10, 2.5, 4, 7]) >>> he.nrmse_iqr(sim, obs) 0.2595461185212093 References ---------- - Pontius, R.G., Thontteh, O., Chen, H., 2008. Components of information for multiple resolution comparison between maps that share a real variable. Environmental and Ecological Statistics 15(2) 111-142.
[ "Compute", "the", "IQR", "normalized", "root", "mean", "square", "error", "between", "the", "simulated", "and", "observed", "data", "." ]
42a84f3e006044f450edc7393ed54d59f27ef35b
https://github.com/BYU-Hydroinformatics/HydroErr/blob/42a84f3e006044f450edc7393ed54d59f27ef35b/HydroErr/HydroErr.py#L1203-L1282
5,183
BYU-Hydroinformatics/HydroErr
HydroErr/HydroErr.py
mase
def mase(simulated_array, observed_array, m=1, replace_nan=None, replace_inf=None, remove_neg=False, remove_zero=False): """Compute the mean absolute scaled error between the simulated and observed data. .. image:: /pictures/MASE.png **Range:** **Notes:** Parameters ---------- simulated_array: one dimensional ndarray An array of simulated data from the time series. observed_array: one dimensional ndarray An array of observed data from the time series. m: int If given, indicates the seasonal period m. If not given, the default is 1. replace_nan: float, optional If given, indicates which value to replace NaN values with in the two arrays. If None, when a NaN value is found at the i-th position in the observed OR simulated array, the i-th value of the observed and simulated array are removed before the computation. replace_inf: float, optional If given, indicates which value to replace Inf values with in the two arrays. If None, when an inf value is found at the i-th position in the observed OR simulated array, the i-th value of the observed and simulated array are removed before the computation. remove_neg: boolean, optional If True, when a negative value is found at the i-th position in the observed OR simulated array, the i-th value of the observed AND simulated array are removed before the computation. remove_zero: boolean, optional If true, when a zero value is found at the i-th position in the observed OR simulated array, the i-th value of the observed AND simulated array are removed before the computation. Returns ------- float The mean absolute scaled error. Examples -------- >>> import HydroErr as he >>> import numpy as np >>> sim = np.array([5, 7, 9, 2, 4.5, 6.7]) >>> obs = np.array([4.7, 6, 10, 2.5, 4, 7]) >>> he.mase(sim, obs) 0.17341040462427745 References ---------- - Hyndman, R.J., Koehler, A.B., 2006. Another look at measures of forecast accuracy. International Journal of Forecasting 22(4) 679-688. """ # Checking and cleaning the data simulated_array, observed_array = treat_values( simulated_array, observed_array, replace_nan=replace_nan, replace_inf=replace_inf, remove_neg=remove_neg, remove_zero=remove_zero ) start = m end = simulated_array.size - m a = np.mean(np.abs(simulated_array - observed_array)) b = np.abs(observed_array[start:observed_array.size] - observed_array[:end]) return a / (np.sum(b) / end)
python
def mase(simulated_array, observed_array, m=1, replace_nan=None, replace_inf=None, remove_neg=False, remove_zero=False): # Checking and cleaning the data simulated_array, observed_array = treat_values( simulated_array, observed_array, replace_nan=replace_nan, replace_inf=replace_inf, remove_neg=remove_neg, remove_zero=remove_zero ) start = m end = simulated_array.size - m a = np.mean(np.abs(simulated_array - observed_array)) b = np.abs(observed_array[start:observed_array.size] - observed_array[:end]) return a / (np.sum(b) / end)
[ "def", "mase", "(", "simulated_array", ",", "observed_array", ",", "m", "=", "1", ",", "replace_nan", "=", "None", ",", "replace_inf", "=", "None", ",", "remove_neg", "=", "False", ",", "remove_zero", "=", "False", ")", ":", "# Checking and cleaning the data",...
Compute the mean absolute scaled error between the simulated and observed data. .. image:: /pictures/MASE.png **Range:** **Notes:** Parameters ---------- simulated_array: one dimensional ndarray An array of simulated data from the time series. observed_array: one dimensional ndarray An array of observed data from the time series. m: int If given, indicates the seasonal period m. If not given, the default is 1. replace_nan: float, optional If given, indicates which value to replace NaN values with in the two arrays. If None, when a NaN value is found at the i-th position in the observed OR simulated array, the i-th value of the observed and simulated array are removed before the computation. replace_inf: float, optional If given, indicates which value to replace Inf values with in the two arrays. If None, when an inf value is found at the i-th position in the observed OR simulated array, the i-th value of the observed and simulated array are removed before the computation. remove_neg: boolean, optional If True, when a negative value is found at the i-th position in the observed OR simulated array, the i-th value of the observed AND simulated array are removed before the computation. remove_zero: boolean, optional If true, when a zero value is found at the i-th position in the observed OR simulated array, the i-th value of the observed AND simulated array are removed before the computation. Returns ------- float The mean absolute scaled error. Examples -------- >>> import HydroErr as he >>> import numpy as np >>> sim = np.array([5, 7, 9, 2, 4.5, 6.7]) >>> obs = np.array([4.7, 6, 10, 2.5, 4, 7]) >>> he.mase(sim, obs) 0.17341040462427745 References ---------- - Hyndman, R.J., Koehler, A.B., 2006. Another look at measures of forecast accuracy. International Journal of Forecasting 22(4) 679-688.
[ "Compute", "the", "mean", "absolute", "scaled", "error", "between", "the", "simulated", "and", "observed", "data", "." ]
42a84f3e006044f450edc7393ed54d59f27ef35b
https://github.com/BYU-Hydroinformatics/HydroErr/blob/42a84f3e006044f450edc7393ed54d59f27ef35b/HydroErr/HydroErr.py#L1372-L1450
5,184
BYU-Hydroinformatics/HydroErr
HydroErr/HydroErr.py
h1_mhe
def h1_mhe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False, remove_zero=False): """Compute the H1 mean error. .. image:: /pictures/H1.png .. image:: /pictures/MHE.png **Range:** **Notes:** Parameters ---------- simulated_array: one dimensional ndarray An array of simulated data from the time series. observed_array: one dimensional ndarray An array of observed data from the time series. replace_nan: float, optional If given, indicates which value to replace NaN values with in the two arrays. If None, when a NaN value is found at the i-th position in the observed OR simulated array, the i-th value of the observed and simulated array are removed before the computation. replace_inf: float, optional If given, indicates which value to replace Inf values with in the two arrays. If None, when an inf value is found at the i-th position in the observed OR simulated array, the i-th value of the observed and simulated array are removed before the computation. remove_neg: boolean, optional If True, when a negative value is found at the i-th position in the observed OR simulated array, the i-th value of the observed AND simulated array are removed before the computation. remove_zero: boolean, optional If true, when a zero value is found at the i-th position in the observed OR simulated array, the i-th value of the observed AND simulated array are removed before the computation. Returns ------- float The mean H1 error. Examples -------- >>> import HydroErr as he >>> import numpy as np >>> sim = np.array([5, 7, 9, 2, 4.5, 6.7]) >>> obs = np.array([4.7, 6, 10, 2.5, 4, 7]) >>> he.h1_mhe(sim, obs) 0.002106551840594386 References ---------- - Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured? The American Statistician 43-46. """ # Treats data simulated_array, observed_array = treat_values( simulated_array, observed_array, replace_nan=replace_nan, replace_inf=replace_inf, remove_neg=remove_neg, remove_zero=remove_zero ) h = (simulated_array - observed_array) / observed_array return np.mean(h)
python
def h1_mhe(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False, remove_zero=False): # Treats data simulated_array, observed_array = treat_values( simulated_array, observed_array, replace_nan=replace_nan, replace_inf=replace_inf, remove_neg=remove_neg, remove_zero=remove_zero ) h = (simulated_array - observed_array) / observed_array return np.mean(h)
[ "def", "h1_mhe", "(", "simulated_array", ",", "observed_array", ",", "replace_nan", "=", "None", ",", "replace_inf", "=", "None", ",", "remove_neg", "=", "False", ",", "remove_zero", "=", "False", ")", ":", "# Treats data", "simulated_array", ",", "observed_arra...
Compute the H1 mean error. .. image:: /pictures/H1.png .. image:: /pictures/MHE.png **Range:** **Notes:** Parameters ---------- simulated_array: one dimensional ndarray An array of simulated data from the time series. observed_array: one dimensional ndarray An array of observed data from the time series. replace_nan: float, optional If given, indicates which value to replace NaN values with in the two arrays. If None, when a NaN value is found at the i-th position in the observed OR simulated array, the i-th value of the observed and simulated array are removed before the computation. replace_inf: float, optional If given, indicates which value to replace Inf values with in the two arrays. If None, when an inf value is found at the i-th position in the observed OR simulated array, the i-th value of the observed and simulated array are removed before the computation. remove_neg: boolean, optional If True, when a negative value is found at the i-th position in the observed OR simulated array, the i-th value of the observed AND simulated array are removed before the computation. remove_zero: boolean, optional If true, when a zero value is found at the i-th position in the observed OR simulated array, the i-th value of the observed AND simulated array are removed before the computation. Returns ------- float The mean H1 error. Examples -------- >>> import HydroErr as he >>> import numpy as np >>> sim = np.array([5, 7, 9, 2, 4.5, 6.7]) >>> obs = np.array([4.7, 6, 10, 2.5, 4, 7]) >>> he.h1_mhe(sim, obs) 0.002106551840594386 References ---------- - Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured? The American Statistician 43-46.
[ "Compute", "the", "H1", "mean", "error", "." ]
42a84f3e006044f450edc7393ed54d59f27ef35b
https://github.com/BYU-Hydroinformatics/HydroErr/blob/42a84f3e006044f450edc7393ed54d59f27ef35b/HydroErr/HydroErr.py#L3858-L3930
5,185
BYU-Hydroinformatics/HydroErr
HydroErr/HydroErr.py
h6_mahe
def h6_mahe(simulated_array, observed_array, k=1, replace_nan=None, replace_inf=None, remove_neg=False, remove_zero=False): """Compute the H6 mean absolute error. .. image:: /pictures/H6.png .. image:: /pictures/AHE.png **Range:** **Notes:** Parameters ---------- simulated_array: one dimensional ndarray An array of simulated data from the time series. observed_array: one dimensional ndarray An array of observed data from the time series. k: int or float If given, sets the value of k. If None, k=1. replace_nan: float, optional If given, indicates which value to replace NaN values with in the two arrays. If None, when a NaN value is found at the i-th position in the observed OR simulated array, the i-th value of the observed and simulated array are removed before the computation. replace_inf: float, optional If given, indicates which value to replace Inf values with in the two arrays. If None, when an inf value is found at the i-th position in the observed OR simulated array, the i-th value of the observed and simulated array are removed before the computation. remove_neg: boolean, optional If True, when a negative value is found at the i-th position in the observed OR simulated array, the i-th value of the observed AND simulated array are removed before the computation. remove_zero: boolean, optional If true, when a zero value is found at the i-th position in the observed OR simulated array, the i-th value of the observed AND simulated array are removed before the computation. Returns ------- float The mean absolute H6 error. Examples -------- >>> import HydroErr as he >>> import numpy as np >>> sim = np.array([5, 7, 9, 2, 4.5, 6.7]) >>> obs = np.array([4.7, 6, 10, 2.5, 4, 7]) >>> he.h6_mahe(sim, obs) 0.11743831388794852 References ---------- - Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured? The American Statistician 43-46. """ # Treats data simulated_array, observed_array = treat_values( simulated_array, observed_array, replace_nan=replace_nan, replace_inf=replace_inf, remove_neg=remove_neg, remove_zero=remove_zero ) top = (simulated_array / observed_array - 1) bot = np.power(0.5 * (1 + np.power(simulated_array / observed_array, k)), 1 / k) h = top / bot return np.mean(np.abs(h))
python
def h6_mahe(simulated_array, observed_array, k=1, replace_nan=None, replace_inf=None, remove_neg=False, remove_zero=False): # Treats data simulated_array, observed_array = treat_values( simulated_array, observed_array, replace_nan=replace_nan, replace_inf=replace_inf, remove_neg=remove_neg, remove_zero=remove_zero ) top = (simulated_array / observed_array - 1) bot = np.power(0.5 * (1 + np.power(simulated_array / observed_array, k)), 1 / k) h = top / bot return np.mean(np.abs(h))
[ "def", "h6_mahe", "(", "simulated_array", ",", "observed_array", ",", "k", "=", "1", ",", "replace_nan", "=", "None", ",", "replace_inf", "=", "None", ",", "remove_neg", "=", "False", ",", "remove_zero", "=", "False", ")", ":", "# Treats data", "simulated_ar...
Compute the H6 mean absolute error. .. image:: /pictures/H6.png .. image:: /pictures/AHE.png **Range:** **Notes:** Parameters ---------- simulated_array: one dimensional ndarray An array of simulated data from the time series. observed_array: one dimensional ndarray An array of observed data from the time series. k: int or float If given, sets the value of k. If None, k=1. replace_nan: float, optional If given, indicates which value to replace NaN values with in the two arrays. If None, when a NaN value is found at the i-th position in the observed OR simulated array, the i-th value of the observed and simulated array are removed before the computation. replace_inf: float, optional If given, indicates which value to replace Inf values with in the two arrays. If None, when an inf value is found at the i-th position in the observed OR simulated array, the i-th value of the observed and simulated array are removed before the computation. remove_neg: boolean, optional If True, when a negative value is found at the i-th position in the observed OR simulated array, the i-th value of the observed AND simulated array are removed before the computation. remove_zero: boolean, optional If true, when a zero value is found at the i-th position in the observed OR simulated array, the i-th value of the observed AND simulated array are removed before the computation. Returns ------- float The mean absolute H6 error. Examples -------- >>> import HydroErr as he >>> import numpy as np >>> sim = np.array([5, 7, 9, 2, 4.5, 6.7]) >>> obs = np.array([4.7, 6, 10, 2.5, 4, 7]) >>> he.h6_mahe(sim, obs) 0.11743831388794852 References ---------- - Tornquist, L., Vartia, P., Vartia, Y.O., 1985. How Should Relative Changes be Measured? The American Statistician 43-46.
[ "Compute", "the", "H6", "mean", "absolute", "error", "." ]
42a84f3e006044f450edc7393ed54d59f27ef35b
https://github.com/BYU-Hydroinformatics/HydroErr/blob/42a84f3e006044f450edc7393ed54d59f27ef35b/HydroErr/HydroErr.py#L5110-L5189
5,186
jgorset/fandjango
fandjango/decorators.py
facebook_authorization_required
def facebook_authorization_required(redirect_uri=FACEBOOK_AUTHORIZATION_REDIRECT_URL, permissions=None): """ Require the user to authorize the application. :param redirect_uri: A string describing an URL to redirect to after authorization is complete. If ``None``, redirects to the current URL in the Facebook canvas (e.g. ``http://apps.facebook.com/myapp/current/path``). Defaults to ``FACEBOOK_AUTHORIZATION_REDIRECT_URL`` (which, in turn, defaults to ``None``). :param permissions: A list of strings describing Facebook permissions. """ def decorator(function): @wraps(function) def wrapper(request, *args, **kwargs): # We know the user has been authenticated via a canvas page if a signed request is set. canvas = request.facebook is not False and hasattr(request.facebook, "signed_request") # The user has already authorized the application, but the given view requires # permissions besides the defaults listed in ``FACEBOOK_APPLICATION_DEFAULT_PERMISSIONS``. # # Derive a list of outstanding permissions and prompt the user to grant them. if request.facebook and request.facebook.user and permissions: outstanding_permissions = [p for p in permissions if p not in request.facebook.user.permissions] if outstanding_permissions: return authorize_application( request = request, redirect_uri = redirect_uri or get_post_authorization_redirect_url(request, canvas=canvas), permissions = outstanding_permissions ) # The user has not authorized the application yet. # # Concatenate the default permissions with permissions required for this particular view. if not request.facebook or not request.facebook.user: return authorize_application( request = request, redirect_uri = redirect_uri or get_post_authorization_redirect_url(request, canvas=canvas), permissions = (FACEBOOK_APPLICATION_INITIAL_PERMISSIONS or []) + (permissions or []) ) return function(request, *args, **kwargs) return wrapper if callable(redirect_uri): function = redirect_uri redirect_uri = None return decorator(function) else: return decorator
python
def facebook_authorization_required(redirect_uri=FACEBOOK_AUTHORIZATION_REDIRECT_URL, permissions=None): def decorator(function): @wraps(function) def wrapper(request, *args, **kwargs): # We know the user has been authenticated via a canvas page if a signed request is set. canvas = request.facebook is not False and hasattr(request.facebook, "signed_request") # The user has already authorized the application, but the given view requires # permissions besides the defaults listed in ``FACEBOOK_APPLICATION_DEFAULT_PERMISSIONS``. # # Derive a list of outstanding permissions and prompt the user to grant them. if request.facebook and request.facebook.user and permissions: outstanding_permissions = [p for p in permissions if p not in request.facebook.user.permissions] if outstanding_permissions: return authorize_application( request = request, redirect_uri = redirect_uri or get_post_authorization_redirect_url(request, canvas=canvas), permissions = outstanding_permissions ) # The user has not authorized the application yet. # # Concatenate the default permissions with permissions required for this particular view. if not request.facebook or not request.facebook.user: return authorize_application( request = request, redirect_uri = redirect_uri or get_post_authorization_redirect_url(request, canvas=canvas), permissions = (FACEBOOK_APPLICATION_INITIAL_PERMISSIONS or []) + (permissions or []) ) return function(request, *args, **kwargs) return wrapper if callable(redirect_uri): function = redirect_uri redirect_uri = None return decorator(function) else: return decorator
[ "def", "facebook_authorization_required", "(", "redirect_uri", "=", "FACEBOOK_AUTHORIZATION_REDIRECT_URL", ",", "permissions", "=", "None", ")", ":", "def", "decorator", "(", "function", ")", ":", "@", "wraps", "(", "function", ")", "def", "wrapper", "(", "request...
Require the user to authorize the application. :param redirect_uri: A string describing an URL to redirect to after authorization is complete. If ``None``, redirects to the current URL in the Facebook canvas (e.g. ``http://apps.facebook.com/myapp/current/path``). Defaults to ``FACEBOOK_AUTHORIZATION_REDIRECT_URL`` (which, in turn, defaults to ``None``). :param permissions: A list of strings describing Facebook permissions.
[ "Require", "the", "user", "to", "authorize", "the", "application", "." ]
01334a76c1d9f0629842aa6830678ae097756551
https://github.com/jgorset/fandjango/blob/01334a76c1d9f0629842aa6830678ae097756551/fandjango/decorators.py#L14-L65
5,187
jgorset/fandjango
fandjango/models.py
User.full_name
def full_name(self): """Return the user's first name.""" if self.first_name and self.middle_name and self.last_name: return "%s %s %s" % (self.first_name, self.middle_name, self.last_name) if self.first_name and self.last_name: return "%s %s" % (self.first_name, self.last_name)
python
def full_name(self): if self.first_name and self.middle_name and self.last_name: return "%s %s %s" % (self.first_name, self.middle_name, self.last_name) if self.first_name and self.last_name: return "%s %s" % (self.first_name, self.last_name)
[ "def", "full_name", "(", "self", ")", ":", "if", "self", ".", "first_name", "and", "self", ".", "middle_name", "and", "self", ".", "last_name", ":", "return", "\"%s %s %s\"", "%", "(", "self", ".", "first_name", ",", "self", ".", "middle_name", ",", "sel...
Return the user's first name.
[ "Return", "the", "user", "s", "first", "name", "." ]
01334a76c1d9f0629842aa6830678ae097756551
https://github.com/jgorset/fandjango/blob/01334a76c1d9f0629842aa6830678ae097756551/fandjango/models.py#L86-L91
5,188
jgorset/fandjango
fandjango/models.py
User.permissions
def permissions(self): """ A list of strings describing `permissions`_ the user has granted your application. .. _permissions: http://developers.facebook.com/docs/reference/api/permissions/ """ records = self.graph.get('me/permissions')['data'] permissions = [] for record in records: if record['status'] == 'granted': permissions.append(record['permission']) return permissions
python
def permissions(self): records = self.graph.get('me/permissions')['data'] permissions = [] for record in records: if record['status'] == 'granted': permissions.append(record['permission']) return permissions
[ "def", "permissions", "(", "self", ")", ":", "records", "=", "self", ".", "graph", ".", "get", "(", "'me/permissions'", ")", "[", "'data'", "]", "permissions", "=", "[", "]", "for", "record", "in", "records", ":", "if", "record", "[", "'status'", "]", ...
A list of strings describing `permissions`_ the user has granted your application. .. _permissions: http://developers.facebook.com/docs/reference/api/permissions/
[ "A", "list", "of", "strings", "describing", "permissions", "_", "the", "user", "has", "granted", "your", "application", "." ]
01334a76c1d9f0629842aa6830678ae097756551
https://github.com/jgorset/fandjango/blob/01334a76c1d9f0629842aa6830678ae097756551/fandjango/models.py#L102-L115
5,189
jgorset/fandjango
fandjango/models.py
User.synchronize
def synchronize(self, graph_data=None): """ Synchronize ``facebook_username``, ``first_name``, ``middle_name``, ``last_name`` and ``birthday`` with Facebook. :param graph_data: Optional pre-fetched graph data """ profile = graph_data or self.graph.get('me') self.facebook_username = profile.get('username') self.first_name = profile.get('first_name') self.middle_name = profile.get('middle_name') self.last_name = profile.get('last_name') self.birthday = datetime.strptime(profile['birthday'], '%m/%d/%Y') if profile.has_key('birthday') else None self.email = profile.get('email') self.locale = profile.get('locale') self.gender = profile.get('gender') self.extra_data = profile self.save()
python
def synchronize(self, graph_data=None): profile = graph_data or self.graph.get('me') self.facebook_username = profile.get('username') self.first_name = profile.get('first_name') self.middle_name = profile.get('middle_name') self.last_name = profile.get('last_name') self.birthday = datetime.strptime(profile['birthday'], '%m/%d/%Y') if profile.has_key('birthday') else None self.email = profile.get('email') self.locale = profile.get('locale') self.gender = profile.get('gender') self.extra_data = profile self.save()
[ "def", "synchronize", "(", "self", ",", "graph_data", "=", "None", ")", ":", "profile", "=", "graph_data", "or", "self", ".", "graph", ".", "get", "(", "'me'", ")", "self", ".", "facebook_username", "=", "profile", ".", "get", "(", "'username'", ")", "...
Synchronize ``facebook_username``, ``first_name``, ``middle_name``, ``last_name`` and ``birthday`` with Facebook. :param graph_data: Optional pre-fetched graph data
[ "Synchronize", "facebook_username", "first_name", "middle_name", "last_name", "and", "birthday", "with", "Facebook", "." ]
01334a76c1d9f0629842aa6830678ae097756551
https://github.com/jgorset/fandjango/blob/01334a76c1d9f0629842aa6830678ae097756551/fandjango/models.py#L126-L144
5,190
jgorset/fandjango
fandjango/models.py
OAuthToken.extended
def extended(self): """Determine whether the OAuth token has been extended.""" if self.expires_at: return self.expires_at - self.issued_at > timedelta(days=30) else: return False
python
def extended(self): if self.expires_at: return self.expires_at - self.issued_at > timedelta(days=30) else: return False
[ "def", "extended", "(", "self", ")", ":", "if", "self", ".", "expires_at", ":", "return", "self", ".", "expires_at", "-", "self", ".", "issued_at", ">", "timedelta", "(", "days", "=", "30", ")", "else", ":", "return", "False" ]
Determine whether the OAuth token has been extended.
[ "Determine", "whether", "the", "OAuth", "token", "has", "been", "extended", "." ]
01334a76c1d9f0629842aa6830678ae097756551
https://github.com/jgorset/fandjango/blob/01334a76c1d9f0629842aa6830678ae097756551/fandjango/models.py#L179-L184
5,191
jgorset/fandjango
fandjango/models.py
OAuthToken.extend
def extend(self): """Extend the OAuth token.""" graph = GraphAPI() response = graph.get('oauth/access_token', client_id = FACEBOOK_APPLICATION_ID, client_secret = FACEBOOK_APPLICATION_SECRET_KEY, grant_type = 'fb_exchange_token', fb_exchange_token = self.token ) components = parse_qs(response) self.token = components['access_token'][0] self.expires_at = now() + timedelta(seconds = int(components['expires'][0])) self.save()
python
def extend(self): graph = GraphAPI() response = graph.get('oauth/access_token', client_id = FACEBOOK_APPLICATION_ID, client_secret = FACEBOOK_APPLICATION_SECRET_KEY, grant_type = 'fb_exchange_token', fb_exchange_token = self.token ) components = parse_qs(response) self.token = components['access_token'][0] self.expires_at = now() + timedelta(seconds = int(components['expires'][0])) self.save()
[ "def", "extend", "(", "self", ")", ":", "graph", "=", "GraphAPI", "(", ")", "response", "=", "graph", ".", "get", "(", "'oauth/access_token'", ",", "client_id", "=", "FACEBOOK_APPLICATION_ID", ",", "client_secret", "=", "FACEBOOK_APPLICATION_SECRET_KEY", ",", "g...
Extend the OAuth token.
[ "Extend", "the", "OAuth", "token", "." ]
01334a76c1d9f0629842aa6830678ae097756551
https://github.com/jgorset/fandjango/blob/01334a76c1d9f0629842aa6830678ae097756551/fandjango/models.py#L186-L202
5,192
jgorset/fandjango
fandjango/middleware.py
FacebookMiddleware.process_request
def process_request(self, request): """Process the signed request.""" # User has already been authed by alternate middleware if hasattr(request, "facebook") and request.facebook: return request.facebook = False if not self.is_valid_path(request): return if self.is_access_denied(request): return authorization_denied_view(request) # No signed request found in either GET, POST nor COOKIES... if 'signed_request' not in request.REQUEST and 'signed_request' not in request.COOKIES: return # If the request method is POST and its body only contains the signed request, # chances are it's a request from the Facebook platform and we'll override # the request method to HTTP GET to rectify their misinterpretation # of the HTTP standard. # # References: # "POST for Canvas" migration at http://developers.facebook.com/docs/canvas/post/ # "Incorrect use of the HTTP protocol" discussion at http://forum.developers.facebook.net/viewtopic.php?id=93554 if request.method == 'POST' and 'signed_request' in request.POST: request.POST = QueryDict('') request.method = 'GET' request.facebook = Facebook() try: request.facebook.signed_request = SignedRequest( signed_request = request.REQUEST.get('signed_request') or request.COOKIES.get('signed_request'), application_secret_key = FACEBOOK_APPLICATION_SECRET_KEY ) except SignedRequest.Error: request.facebook = False # Valid signed request and user has authorized the application if request.facebook \ and request.facebook.signed_request.user.has_authorized_application \ and not request.facebook.signed_request.user.oauth_token.has_expired: # Initialize a User object and its corresponding OAuth token try: user = User.objects.get(facebook_id=request.facebook.signed_request.user.id) except User.DoesNotExist: oauth_token = OAuthToken.objects.create( token = request.facebook.signed_request.user.oauth_token.token, issued_at = request.facebook.signed_request.user.oauth_token.issued_at.replace(tzinfo=tzlocal()), expires_at = request.facebook.signed_request.user.oauth_token.expires_at.replace(tzinfo=tzlocal()) ) user = User.objects.create( facebook_id = request.facebook.signed_request.user.id, oauth_token = oauth_token ) user.synchronize() # Update the user's details and OAuth token else: user.last_seen_at = now() if 'signed_request' in request.REQUEST: user.authorized = True if request.facebook.signed_request.user.oauth_token: user.oauth_token.token = request.facebook.signed_request.user.oauth_token.token user.oauth_token.issued_at = request.facebook.signed_request.user.oauth_token.issued_at.replace(tzinfo=tzlocal()) user.oauth_token.expires_at = request.facebook.signed_request.user.oauth_token.expires_at.replace(tzinfo=tzlocal()) user.oauth_token.save() user.save() if not user.oauth_token.extended: # Attempt to extend the OAuth token, but ignore exceptions raised by # bug #102727766518358 in the Facebook Platform. # # http://developers.facebook.com/bugs/102727766518358/ try: user.oauth_token.extend() except: pass request.facebook.user = user
python
def process_request(self, request): # User has already been authed by alternate middleware if hasattr(request, "facebook") and request.facebook: return request.facebook = False if not self.is_valid_path(request): return if self.is_access_denied(request): return authorization_denied_view(request) # No signed request found in either GET, POST nor COOKIES... if 'signed_request' not in request.REQUEST and 'signed_request' not in request.COOKIES: return # If the request method is POST and its body only contains the signed request, # chances are it's a request from the Facebook platform and we'll override # the request method to HTTP GET to rectify their misinterpretation # of the HTTP standard. # # References: # "POST for Canvas" migration at http://developers.facebook.com/docs/canvas/post/ # "Incorrect use of the HTTP protocol" discussion at http://forum.developers.facebook.net/viewtopic.php?id=93554 if request.method == 'POST' and 'signed_request' in request.POST: request.POST = QueryDict('') request.method = 'GET' request.facebook = Facebook() try: request.facebook.signed_request = SignedRequest( signed_request = request.REQUEST.get('signed_request') or request.COOKIES.get('signed_request'), application_secret_key = FACEBOOK_APPLICATION_SECRET_KEY ) except SignedRequest.Error: request.facebook = False # Valid signed request and user has authorized the application if request.facebook \ and request.facebook.signed_request.user.has_authorized_application \ and not request.facebook.signed_request.user.oauth_token.has_expired: # Initialize a User object and its corresponding OAuth token try: user = User.objects.get(facebook_id=request.facebook.signed_request.user.id) except User.DoesNotExist: oauth_token = OAuthToken.objects.create( token = request.facebook.signed_request.user.oauth_token.token, issued_at = request.facebook.signed_request.user.oauth_token.issued_at.replace(tzinfo=tzlocal()), expires_at = request.facebook.signed_request.user.oauth_token.expires_at.replace(tzinfo=tzlocal()) ) user = User.objects.create( facebook_id = request.facebook.signed_request.user.id, oauth_token = oauth_token ) user.synchronize() # Update the user's details and OAuth token else: user.last_seen_at = now() if 'signed_request' in request.REQUEST: user.authorized = True if request.facebook.signed_request.user.oauth_token: user.oauth_token.token = request.facebook.signed_request.user.oauth_token.token user.oauth_token.issued_at = request.facebook.signed_request.user.oauth_token.issued_at.replace(tzinfo=tzlocal()) user.oauth_token.expires_at = request.facebook.signed_request.user.oauth_token.expires_at.replace(tzinfo=tzlocal()) user.oauth_token.save() user.save() if not user.oauth_token.extended: # Attempt to extend the OAuth token, but ignore exceptions raised by # bug #102727766518358 in the Facebook Platform. # # http://developers.facebook.com/bugs/102727766518358/ try: user.oauth_token.extend() except: pass request.facebook.user = user
[ "def", "process_request", "(", "self", ",", "request", ")", ":", "# User has already been authed by alternate middleware", "if", "hasattr", "(", "request", ",", "\"facebook\"", ")", "and", "request", ".", "facebook", ":", "return", "request", ".", "facebook", "=", ...
Process the signed request.
[ "Process", "the", "signed", "request", "." ]
01334a76c1d9f0629842aa6830678ae097756551
https://github.com/jgorset/fandjango/blob/01334a76c1d9f0629842aa6830678ae097756551/fandjango/middleware.py#L53-L141
5,193
jgorset/fandjango
fandjango/middleware.py
FacebookMiddleware.process_response
def process_response(self, request, response): """ Set compact P3P policies and save signed request to cookie. P3P is a WC3 standard (see http://www.w3.org/TR/P3P/), and although largely ignored by most browsers it is considered by IE before accepting third-party cookies (ie. cookies set by documents in iframes). If they are not set correctly, IE will not set these cookies. """ response['P3P'] = 'CP="IDC CURa ADMa OUR IND PHY ONL COM STA"' if FANDJANGO_CACHE_SIGNED_REQUEST: if hasattr(request, "facebook") and request.facebook and request.facebook.signed_request: response.set_cookie('signed_request', request.facebook.signed_request.generate()) else: response.delete_cookie('signed_request') return response
python
def process_response(self, request, response): response['P3P'] = 'CP="IDC CURa ADMa OUR IND PHY ONL COM STA"' if FANDJANGO_CACHE_SIGNED_REQUEST: if hasattr(request, "facebook") and request.facebook and request.facebook.signed_request: response.set_cookie('signed_request', request.facebook.signed_request.generate()) else: response.delete_cookie('signed_request') return response
[ "def", "process_response", "(", "self", ",", "request", ",", "response", ")", ":", "response", "[", "'P3P'", "]", "=", "'CP=\"IDC CURa ADMa OUR IND PHY ONL COM STA\"'", "if", "FANDJANGO_CACHE_SIGNED_REQUEST", ":", "if", "hasattr", "(", "request", ",", "\"facebook\"", ...
Set compact P3P policies and save signed request to cookie. P3P is a WC3 standard (see http://www.w3.org/TR/P3P/), and although largely ignored by most browsers it is considered by IE before accepting third-party cookies (ie. cookies set by documents in iframes). If they are not set correctly, IE will not set these cookies.
[ "Set", "compact", "P3P", "policies", "and", "save", "signed", "request", "to", "cookie", "." ]
01334a76c1d9f0629842aa6830678ae097756551
https://github.com/jgorset/fandjango/blob/01334a76c1d9f0629842aa6830678ae097756551/fandjango/middleware.py#L143-L159
5,194
jgorset/fandjango
fandjango/middleware.py
FacebookWebMiddleware.process_request
def process_request(self, request): """Process the web-based auth request.""" # User has already been authed by alternate middleware if hasattr(request, "facebook") and request.facebook: return request.facebook = False if not self.is_valid_path(request): return if self.is_access_denied(request): return authorization_denied_view(request) request.facebook = Facebook() oauth_token = False # Is there a token cookie already present? if 'oauth_token' in request.COOKIES: try: # Check if the current token is already in DB oauth_token = OAuthToken.objects.get(token=request.COOKIES['oauth_token']) except OAuthToken.DoesNotExist: request.facebook = False return # Is there a code in the GET request? elif 'code' in request.GET: try: graph = GraphAPI() # Exchange code for an access_token response = graph.get('oauth/access_token', client_id = FACEBOOK_APPLICATION_ID, redirect_uri = get_post_authorization_redirect_url(request, canvas=False), client_secret = FACEBOOK_APPLICATION_SECRET_KEY, code = request.GET['code'], ) components = parse_qs(response) # Save new OAuth-token in DB oauth_token, new_oauth_token = OAuthToken.objects.get_or_create( token = components['access_token'][0], issued_at = now(), expires_at = now() + timedelta(seconds = int(components['expires'][0])) ) except GraphAPI.OAuthError: pass # There isn't a valid access_token if not oauth_token or oauth_token.expired: request.facebook = False return # Is there a user already connected to the current token? try: user = oauth_token.user if not user.authorized: request.facebook = False return user.last_seen_at = now() user.save() except User.DoesNotExist: graph = GraphAPI(oauth_token.token) profile = graph.get('me') # Either the user already exists and its just a new token, or user and token both are new try: user = User.objects.get(facebook_id = profile.get('id')) if not user.authorized: if new_oauth_token: user.last_seen_at = now() user.authorized = True else: request.facebook = False return except User.DoesNotExist: # Create a new user to go with token user = User.objects.create( facebook_id = profile.get('id'), oauth_token = oauth_token ) user.synchronize(profile) # Delete old access token if there is any and only if the new one is different old_oauth_token = None if user.oauth_token != oauth_token: old_oauth_token = user.oauth_token user.oauth_token = oauth_token user.save() if old_oauth_token: old_oauth_token.delete() if not user.oauth_token.extended: # Attempt to extend the OAuth token, but ignore exceptions raised by # bug #102727766518358 in the Facebook Platform. # # http://developers.facebook.com/bugs/102727766518358/ try: user.oauth_token.extend() except: pass request.facebook.user = user request.facebook.oauth_token = oauth_token
python
def process_request(self, request): # User has already been authed by alternate middleware if hasattr(request, "facebook") and request.facebook: return request.facebook = False if not self.is_valid_path(request): return if self.is_access_denied(request): return authorization_denied_view(request) request.facebook = Facebook() oauth_token = False # Is there a token cookie already present? if 'oauth_token' in request.COOKIES: try: # Check if the current token is already in DB oauth_token = OAuthToken.objects.get(token=request.COOKIES['oauth_token']) except OAuthToken.DoesNotExist: request.facebook = False return # Is there a code in the GET request? elif 'code' in request.GET: try: graph = GraphAPI() # Exchange code for an access_token response = graph.get('oauth/access_token', client_id = FACEBOOK_APPLICATION_ID, redirect_uri = get_post_authorization_redirect_url(request, canvas=False), client_secret = FACEBOOK_APPLICATION_SECRET_KEY, code = request.GET['code'], ) components = parse_qs(response) # Save new OAuth-token in DB oauth_token, new_oauth_token = OAuthToken.objects.get_or_create( token = components['access_token'][0], issued_at = now(), expires_at = now() + timedelta(seconds = int(components['expires'][0])) ) except GraphAPI.OAuthError: pass # There isn't a valid access_token if not oauth_token or oauth_token.expired: request.facebook = False return # Is there a user already connected to the current token? try: user = oauth_token.user if not user.authorized: request.facebook = False return user.last_seen_at = now() user.save() except User.DoesNotExist: graph = GraphAPI(oauth_token.token) profile = graph.get('me') # Either the user already exists and its just a new token, or user and token both are new try: user = User.objects.get(facebook_id = profile.get('id')) if not user.authorized: if new_oauth_token: user.last_seen_at = now() user.authorized = True else: request.facebook = False return except User.DoesNotExist: # Create a new user to go with token user = User.objects.create( facebook_id = profile.get('id'), oauth_token = oauth_token ) user.synchronize(profile) # Delete old access token if there is any and only if the new one is different old_oauth_token = None if user.oauth_token != oauth_token: old_oauth_token = user.oauth_token user.oauth_token = oauth_token user.save() if old_oauth_token: old_oauth_token.delete() if not user.oauth_token.extended: # Attempt to extend the OAuth token, but ignore exceptions raised by # bug #102727766518358 in the Facebook Platform. # # http://developers.facebook.com/bugs/102727766518358/ try: user.oauth_token.extend() except: pass request.facebook.user = user request.facebook.oauth_token = oauth_token
[ "def", "process_request", "(", "self", ",", "request", ")", ":", "# User has already been authed by alternate middleware", "if", "hasattr", "(", "request", ",", "\"facebook\"", ")", "and", "request", ".", "facebook", ":", "return", "request", ".", "facebook", "=", ...
Process the web-based auth request.
[ "Process", "the", "web", "-", "based", "auth", "request", "." ]
01334a76c1d9f0629842aa6830678ae097756551
https://github.com/jgorset/fandjango/blob/01334a76c1d9f0629842aa6830678ae097756551/fandjango/middleware.py#L164-L274
5,195
jgorset/fandjango
fandjango/middleware.py
FacebookWebMiddleware.process_response
def process_response(self, request, response): """ Set compact P3P policies and save auth token to cookie. P3P is a WC3 standard (see http://www.w3.org/TR/P3P/), and although largely ignored by most browsers it is considered by IE before accepting third-party cookies (ie. cookies set by documents in iframes). If they are not set correctly, IE will not set these cookies. """ if hasattr(request, "facebook") and request.facebook and request.facebook.oauth_token: if "code" in request.REQUEST: """ Remove auth related query params """ path = get_full_path(request, remove_querystrings=['code', 'web_canvas']) response = HttpResponseRedirect(path) response.set_cookie('oauth_token', request.facebook.oauth_token.token) else: response.delete_cookie('oauth_token') response['P3P'] = 'CP="IDC CURa ADMa OUR IND PHY ONL COM STA"' return response
python
def process_response(self, request, response): if hasattr(request, "facebook") and request.facebook and request.facebook.oauth_token: if "code" in request.REQUEST: """ Remove auth related query params """ path = get_full_path(request, remove_querystrings=['code', 'web_canvas']) response = HttpResponseRedirect(path) response.set_cookie('oauth_token', request.facebook.oauth_token.token) else: response.delete_cookie('oauth_token') response['P3P'] = 'CP="IDC CURa ADMa OUR IND PHY ONL COM STA"' return response
[ "def", "process_response", "(", "self", ",", "request", ",", "response", ")", ":", "if", "hasattr", "(", "request", ",", "\"facebook\"", ")", "and", "request", ".", "facebook", "and", "request", ".", "facebook", ".", "oauth_token", ":", "if", "\"code\"", "...
Set compact P3P policies and save auth token to cookie. P3P is a WC3 standard (see http://www.w3.org/TR/P3P/), and although largely ignored by most browsers it is considered by IE before accepting third-party cookies (ie. cookies set by documents in iframes). If they are not set correctly, IE will not set these cookies.
[ "Set", "compact", "P3P", "policies", "and", "save", "auth", "token", "to", "cookie", "." ]
01334a76c1d9f0629842aa6830678ae097756551
https://github.com/jgorset/fandjango/blob/01334a76c1d9f0629842aa6830678ae097756551/fandjango/middleware.py#L277-L297
5,196
thombashi/SimpleSQLite
simplesqlite/converter.py
RecordConvertor.to_record
def to_record(cls, attr_names, values): """ Convert values to a record to be inserted into a database. :param list attr_names: List of attributes for the converting record. :param values: Values to be converted. :type values: |dict|/|namedtuple|/|list|/|tuple| :raises ValueError: If the ``values`` is invalid. """ try: # from a namedtuple to a dict values = values._asdict() except AttributeError: pass try: # from a dictionary to a list return [cls.__to_sqlite_element(values.get(attr_name)) for attr_name in attr_names] except AttributeError: pass if isinstance(values, (tuple, list)): return [cls.__to_sqlite_element(value) for value in values] raise ValueError("cannot convert from {} to list".format(type(values)))
python
def to_record(cls, attr_names, values): try: # from a namedtuple to a dict values = values._asdict() except AttributeError: pass try: # from a dictionary to a list return [cls.__to_sqlite_element(values.get(attr_name)) for attr_name in attr_names] except AttributeError: pass if isinstance(values, (tuple, list)): return [cls.__to_sqlite_element(value) for value in values] raise ValueError("cannot convert from {} to list".format(type(values)))
[ "def", "to_record", "(", "cls", ",", "attr_names", ",", "values", ")", ":", "try", ":", "# from a namedtuple to a dict", "values", "=", "values", ".", "_asdict", "(", ")", "except", "AttributeError", ":", "pass", "try", ":", "# from a dictionary to a list", "ret...
Convert values to a record to be inserted into a database. :param list attr_names: List of attributes for the converting record. :param values: Values to be converted. :type values: |dict|/|namedtuple|/|list|/|tuple| :raises ValueError: If the ``values`` is invalid.
[ "Convert", "values", "to", "a", "record", "to", "be", "inserted", "into", "a", "database", "." ]
b16f212132b9b98773e68bf7395abc2f60f56fe5
https://github.com/thombashi/SimpleSQLite/blob/b16f212132b9b98773e68bf7395abc2f60f56fe5/simplesqlite/converter.py#L21-L47
5,197
thombashi/SimpleSQLite
simplesqlite/converter.py
RecordConvertor.to_records
def to_records(cls, attr_names, value_matrix): """ Convert a value matrix to records to be inserted into a database. :param list attr_names: List of attributes for the converting records. :param value_matrix: Values to be converted. :type value_matrix: list of |dict|/|namedtuple|/|list|/|tuple| .. seealso:: :py:meth:`.to_record` """ return [cls.to_record(attr_names, record) for record in value_matrix]
python
def to_records(cls, attr_names, value_matrix): return [cls.to_record(attr_names, record) for record in value_matrix]
[ "def", "to_records", "(", "cls", ",", "attr_names", ",", "value_matrix", ")", ":", "return", "[", "cls", ".", "to_record", "(", "attr_names", ",", "record", ")", "for", "record", "in", "value_matrix", "]" ]
Convert a value matrix to records to be inserted into a database. :param list attr_names: List of attributes for the converting records. :param value_matrix: Values to be converted. :type value_matrix: list of |dict|/|namedtuple|/|list|/|tuple| .. seealso:: :py:meth:`.to_record`
[ "Convert", "a", "value", "matrix", "to", "records", "to", "be", "inserted", "into", "a", "database", "." ]
b16f212132b9b98773e68bf7395abc2f60f56fe5
https://github.com/thombashi/SimpleSQLite/blob/b16f212132b9b98773e68bf7395abc2f60f56fe5/simplesqlite/converter.py#L50-L62
5,198
jgorset/fandjango
fandjango/utils.py
is_disabled_path
def is_disabled_path(path): """ Determine whether or not the path matches one or more paths in the DISABLED_PATHS setting. :param path: A string describing the path to be matched. """ for disabled_path in DISABLED_PATHS: match = re.search(disabled_path, path[1:]) if match: return True return False
python
def is_disabled_path(path): for disabled_path in DISABLED_PATHS: match = re.search(disabled_path, path[1:]) if match: return True return False
[ "def", "is_disabled_path", "(", "path", ")", ":", "for", "disabled_path", "in", "DISABLED_PATHS", ":", "match", "=", "re", ".", "search", "(", "disabled_path", ",", "path", "[", "1", ":", "]", ")", "if", "match", ":", "return", "True", "return", "False" ...
Determine whether or not the path matches one or more paths in the DISABLED_PATHS setting. :param path: A string describing the path to be matched.
[ "Determine", "whether", "or", "not", "the", "path", "matches", "one", "or", "more", "paths", "in", "the", "DISABLED_PATHS", "setting", "." ]
01334a76c1d9f0629842aa6830678ae097756551
https://github.com/jgorset/fandjango/blob/01334a76c1d9f0629842aa6830678ae097756551/fandjango/utils.py#L17-L28
5,199
jgorset/fandjango
fandjango/utils.py
is_enabled_path
def is_enabled_path(path): """ Determine whether or not the path matches one or more paths in the ENABLED_PATHS setting. :param path: A string describing the path to be matched. """ for enabled_path in ENABLED_PATHS: match = re.search(enabled_path, path[1:]) if match: return True return False
python
def is_enabled_path(path): for enabled_path in ENABLED_PATHS: match = re.search(enabled_path, path[1:]) if match: return True return False
[ "def", "is_enabled_path", "(", "path", ")", ":", "for", "enabled_path", "in", "ENABLED_PATHS", ":", "match", "=", "re", ".", "search", "(", "enabled_path", ",", "path", "[", "1", ":", "]", ")", "if", "match", ":", "return", "True", "return", "False" ]
Determine whether or not the path matches one or more paths in the ENABLED_PATHS setting. :param path: A string describing the path to be matched.
[ "Determine", "whether", "or", "not", "the", "path", "matches", "one", "or", "more", "paths", "in", "the", "ENABLED_PATHS", "setting", "." ]
01334a76c1d9f0629842aa6830678ae097756551
https://github.com/jgorset/fandjango/blob/01334a76c1d9f0629842aa6830678ae097756551/fandjango/utils.py#L30-L41