_id
stringlengths 2
7
| title
stringlengths 1
88
| partition
stringclasses 3
values | text
stringlengths 75
19.8k
| language
stringclasses 1
value | meta_information
dict |
|---|---|---|---|---|---|
q5100
|
MEntity.get_id_by_impath
|
train
|
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
|
{
"resource": ""
}
|
q5101
|
MEntity.create_entity
|
train
|
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
|
{
"resource": ""
}
|
q5102
|
CollectHandler.add_or_update
|
train
|
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
|
{
"resource": ""
}
|
q5103
|
CollectHandler.show_list
|
train
|
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
|
{
"resource": ""
}
|
q5104
|
MWiki.create_wiki
|
train
|
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
|
{
"resource": ""
}
|
q5105
|
MWiki.create_page
|
train
|
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
|
{
"resource": ""
}
|
q5106
|
MWiki.__create_rec
|
train
|
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
|
{
"resource": ""
}
|
q5107
|
MWiki.query_dated
|
train
|
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
|
{
"resource": ""
}
|
q5108
|
MWiki.query_most
|
train
|
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
|
{
"resource": ""
}
|
q5109
|
MWiki.update_view_count
|
train
|
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
|
{
"resource": ""
}
|
q5110
|
MWiki.update_view_count_by_uid
|
train
|
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
|
{
"resource": ""
}
|
q5111
|
MWiki.get_by_wiki
|
train
|
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
|
{
"resource": ""
}
|
q5112
|
MWiki.view_count_plus
|
train
|
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
|
{
"resource": ""
}
|
q5113
|
MWiki.query_all
|
train
|
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
|
{
"resource": ""
}
|
q5114
|
MWiki.query_random
|
train
|
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
|
{
"resource": ""
}
|
q5115
|
MLabel.get_id_by_name
|
train
|
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
|
{
"resource": ""
}
|
q5116
|
MLabel.get_by_slug
|
train
|
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
|
{
"resource": ""
}
|
q5117
|
MLabel.create_tag
|
train
|
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
|
{
"resource": ""
}
|
q5118
|
MPost2Label.get_by_uid
|
train
|
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
|
{
"resource": ""
}
|
q5119
|
MPost2Label.add_record
|
train
|
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
|
{
"resource": ""
}
|
q5120
|
MPost2Label.total_number
|
train
|
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
|
{
"resource": ""
}
|
q5121
|
MEntity2User.create_entity2user
|
train
|
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
|
{
"resource": ""
}
|
q5122
|
check_html
|
train
|
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
|
{
"resource": ""
}
|
q5123
|
do_for_dir
|
train
|
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
|
{
"resource": ""
}
|
q5124
|
run_checkit
|
train
|
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
|
{
"resource": ""
}
|
q5125
|
MPost2Catalog.query_all
|
train
|
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
|
{
"resource": ""
}
|
q5126
|
MPost2Catalog.remove_relation
|
train
|
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
|
{
"resource": ""
}
|
q5127
|
MPost2Catalog.remove_tag
|
train
|
def remove_tag(tag_id):
'''
Delete the records of certain tag.
'''
entry = TabPost2Tag.delete().where(
TabPost2Tag.tag_id == tag_id
)
entry.execute()
|
python
|
{
"resource": ""
}
|
q5128
|
MPost2Catalog.query_by_post
|
train
|
def query_by_post(postid):
'''
Query records by post.
'''
return TabPost2Tag.select().where(
TabPost2Tag.post_id == postid
).order_by(TabPost2Tag.order)
|
python
|
{
"resource": ""
}
|
q5129
|
MPost2Catalog.__get_by_info
|
train
|
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
|
{
"resource": ""
}
|
q5130
|
MPost2Catalog.query_count
|
train
|
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
|
{
"resource": ""
}
|
q5131
|
MPost2Catalog.update_field
|
train
|
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
|
{
"resource": ""
}
|
q5132
|
MPost2Catalog.add_record
|
train
|
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
|
{
"resource": ""
}
|
q5133
|
MPost2Catalog.count_of_certain_category
|
train
|
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
|
{
"resource": ""
}
|
q5134
|
MPost2Catalog.query_pager_by_slug
|
train
|
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
|
{
"resource": ""
}
|
q5135
|
MPost2Catalog.query_by_entity_uid
|
train
|
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
|
{
"resource": ""
}
|
q5136
|
MPost2Catalog.get_first_category
|
train
|
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
|
{
"resource": ""
}
|
q5137
|
InfoRecentUsed.render_it
|
train
|
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
|
{
"resource": ""
}
|
q5138
|
LinkHandler.to_add_link
|
train
|
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
|
{
"resource": ""
}
|
q5139
|
LinkHandler.update
|
train
|
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
|
{
"resource": ""
}
|
q5140
|
LinkHandler.to_modify
|
train
|
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
|
{
"resource": ""
}
|
q5141
|
LinkHandler.p_user_add_link
|
train
|
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
|
{
"resource": ""
}
|
q5142
|
LinkHandler.user_add_link
|
train
|
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
|
{
"resource": ""
}
|
q5143
|
LinkHandler.delete_by_id
|
train
|
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
|
{
"resource": ""
}
|
q5144
|
MRating.get_rating
|
train
|
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
|
{
"resource": ""
}
|
q5145
|
MRating.update
|
train
|
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
|
{
"resource": ""
}
|
q5146
|
MRating.__update_rating
|
train
|
def __update_rating(uid, rating):
'''
Update rating.
'''
entry = TabRating.update(
rating=rating
).where(TabRating.uid == uid)
entry.execute()
|
python
|
{
"resource": ""
}
|
q5147
|
MRating.__insert_data
|
train
|
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
|
{
"resource": ""
}
|
q5148
|
update_category
|
train
|
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
|
{
"resource": ""
}
|
q5149
|
MRelation.add_relation
|
train
|
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
|
{
"resource": ""
}
|
q5150
|
MRelation.get_app_relations
|
train
|
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
|
{
"resource": ""
}
|
q5151
|
LabelHandler.remove_redis_keyword
|
train
|
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
|
{
"resource": ""
}
|
q5152
|
build_directory
|
train
|
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
|
{
"resource": ""
}
|
q5153
|
run_create_admin
|
train
|
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
|
{
"resource": ""
}
|
q5154
|
run_update_cat
|
train
|
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
|
{
"resource": ""
}
|
q5155
|
RatingHandler.update_post
|
train
|
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
|
{
"resource": ""
}
|
q5156
|
RatingHandler.update_rating
|
train
|
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
|
{
"resource": ""
}
|
q5157
|
MCategory.query_all
|
train
|
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
|
{
"resource": ""
}
|
q5158
|
MCategory.query_field_count
|
train
|
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
|
{
"resource": ""
}
|
q5159
|
MCategory.get_by_slug
|
train
|
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
|
{
"resource": ""
}
|
q5160
|
MCategory.update_count
|
train
|
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
|
{
"resource": ""
}
|
q5161
|
MCategory.update
|
train
|
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
|
{
"resource": ""
}
|
q5162
|
MCategory.add_or_update
|
train
|
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
|
{
"resource": ""
}
|
q5163
|
PostListHandler.recent
|
train
|
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
|
{
"resource": ""
}
|
q5164
|
PostListHandler.errcat
|
train
|
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
|
{
"resource": ""
}
|
q5165
|
PostListHandler.refresh
|
train
|
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
|
{
"resource": ""
}
|
q5166
|
build_dir
|
train
|
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
|
{
"resource": ""
}
|
q5167
|
MReply.create_reply
|
train
|
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
|
{
"resource": ""
}
|
q5168
|
MReply.query_by_post
|
train
|
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
|
{
"resource": ""
}
|
q5169
|
__write_filter_dic
|
train
|
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
|
{
"resource": ""
}
|
q5170
|
MWikiHist.get_last
|
train
|
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
|
{
"resource": ""
}
|
q5171
|
is_prived
|
train
|
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
|
{
"resource": ""
}
|
q5172
|
auth_view
|
train
|
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
|
{
"resource": ""
}
|
q5173
|
multi_process
|
train
|
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
|
{
"resource": ""
}
|
q5174
|
func
|
train
|
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
|
{
"resource": ""
}
|
q5175
|
me
|
train
|
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
|
{
"resource": ""
}
|
q5176
|
mae
|
train
|
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
|
{
"resource": ""
}
|
q5177
|
mle
|
train
|
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
|
{
"resource": ""
}
|
q5178
|
ed
|
train
|
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
|
{
"resource": ""
}
|
q5179
|
ned
|
train
|
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
|
{
"resource": ""
}
|
q5180
|
nrmse_range
|
train
|
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
|
{
"resource": ""
}
|
q5181
|
nrmse_mean
|
train
|
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
|
{
"resource": ""
}
|
q5182
|
nrmse_iqr
|
train
|
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
|
{
"resource": ""
}
|
q5183
|
mase
|
train
|
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
|
{
"resource": ""
}
|
q5184
|
h1_mhe
|
train
|
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
|
{
"resource": ""
}
|
q5185
|
h6_mahe
|
train
|
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
|
{
"resource": ""
}
|
q5186
|
facebook_authorization_required
|
train
|
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
|
{
"resource": ""
}
|
q5187
|
User.full_name
|
train
|
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
|
{
"resource": ""
}
|
q5188
|
User.permissions
|
train
|
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
|
{
"resource": ""
}
|
q5189
|
User.synchronize
|
train
|
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
|
{
"resource": ""
}
|
q5190
|
OAuthToken.extended
|
train
|
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
|
{
"resource": ""
}
|
q5191
|
OAuthToken.extend
|
train
|
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
|
{
"resource": ""
}
|
q5192
|
FacebookMiddleware.process_request
|
train
|
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
|
{
"resource": ""
}
|
q5193
|
FacebookMiddleware.process_response
|
train
|
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
|
{
"resource": ""
}
|
q5194
|
FacebookWebMiddleware.process_request
|
train
|
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
|
{
"resource": ""
}
|
q5195
|
FacebookWebMiddleware.process_response
|
train
|
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
|
{
"resource": ""
}
|
q5196
|
RecordConvertor.to_record
|
train
|
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
|
{
"resource": ""
}
|
q5197
|
RecordConvertor.to_records
|
train
|
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
|
{
"resource": ""
}
|
q5198
|
is_disabled_path
|
train
|
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
|
{
"resource": ""
}
|
q5199
|
is_enabled_path
|
train
|
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
|
{
"resource": ""
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.