_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
31
13.1k
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:
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(
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))
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,
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)
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()
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(),
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 ==
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
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(
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(
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:
python
{ "resource": "" }
q5112
MWiki.view_count_plus
train
def view_count_plus(slug): ''' View count plus one. ''' entry
python
{ "resource": "" }
q5113
MWiki.query_all
train
def query_all(**kwargs): ''' Qeury recent wiki. ''' kind = kwargs.get('kind', '1') limit = kwargs.get('limit', 50)
python
{ "resource": "" }
q5114
MWiki.query_random
train
def query_random(num=6, kind='1'): ''' Query wikis randomly. ''' return TabWiki.select().where(
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:
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 ==
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.
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'),
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()
python
{ "resource": "" }
q5120
MPost2Label.total_number
train
def total_number(slug, kind='1'): ''' Return the number of certian slug. ''' return TabPost.select().join(
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)
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:
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'):
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)
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(
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) &
python
{ "resource": "" }
q5127
MPost2Catalog.remove_tag
train
def remove_tag(tag_id): ''' Delete the records of certain tag. ''' entry = TabPost2Tag.delete().where(
python
{ "resource": "" }
q5128
MPost2Catalog.query_by_post
train
def query_by_post(postid): ''' Query records by post. ''' return TabPost2Tag.select().where(
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:
python
{ "resource": "" }
q5130
MPost2Catalog.query_count
train
def query_count(): ''' The count of post2tag. ''' recs = TabPost2Tag.select( TabPost2Tag.tag_id,
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,
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:
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(
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(
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)
python
{ "resource": "" }
q5136
MPost2Catalog.get_first_category
train
def get_first_category(app_uid): ''' Get the first, as the uniqe category of post.
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],
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': '',
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,
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',
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 =
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()
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}
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) )
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) )
python
{ "resource": "" }
q5146
MRating.__update_rating
train
def __update_rating(uid, rating): ''' Update rating. ''' entry = TabRating.update(
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,
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
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(
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(
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']
python
{ "resource": "" }
q5152
build_directory
train
def build_directory(): ''' Build the directory for Whoosh database, and locale. ''' if os.path.exists('locale'): pass else:
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',
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)
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:
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'])
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:
python
{ "resource": "" }
q5158
MCategory.query_field_count
train
def query_field_count(limit_num, kind='1'): ''' Query the posts count of certain category.
python
{ "resource": "" }
q5159
MCategory.get_by_slug
train
def get_by_slug(slug): ''' return the category record . ''' rec = TabTag.select().where(TabTag.slug == slug)
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(
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
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'],
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),
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:
python
{ "resource": "" }
q5165
PostListHandler.refresh
train
def refresh(self): ''' List the post of dated. ''' kwd = { 'pager': '', 'title': '', } self.render('list/post_list.html',
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
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(),
python
{ "resource": "" }
q5168
MReply.query_by_post
train
def query_by_post(postid): ''' Get reply list of certain post. ''' return TabReply.select().where(
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:
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
python
{ "resource": "" }
q5171
is_prived
train
def is_prived(usr_rule, def_rule): ''' Compare between two role string. ''' for iii in range(4):
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,
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)
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)
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
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
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
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
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
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
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
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
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
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
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,
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
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,
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 = []
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')
python
{ "resource": "" }
q5190
OAuthToken.extended
train
def extended(self): """Determine whether the OAuth token has been extended.""" if self.expires_at:
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
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(
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
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(),
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 """
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:
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.
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. """
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. """
python
{ "resource": "" }