예제 #1
0
파일: visualiser.py 프로젝트: turbak/lem_in
def main():
    if len(sys.argv) == 2:
        map_name = sys.argv[1]
    else:
        exit(1)
    map_file = open(map_name, 'r')

    # ввод данных
    map_data = map_file.read()
    links = re.findall('\w+-\w+', map_data)
    rooms = re.findall('\w+ \d+ \d+', map_data)
    paths = re.findall('(L.*?)\n', map_data)
    print(paths)

    # парсинг данных на узлы, ребра и перемещения за каждый шаг
    rooms_dict = {}
    links_list = []
    for room in rooms:
        buf = room.split(' ')
        rooms_dict[buf[0]] = (Room(buf[0],
                                   int(buf[1]) * ZOOM,
                                   int(buf[2]) * ZOOM, NODE_SIZE))
        print(buf[0], buf[1], buf[2])
    for link in links:
        buf = link.split('-')
        if not buf[0].startswith('L'):
            line = Link(None, None)
            for room in rooms_dict:
                room = rooms_dict[room]
                if room.name == buf[0]:
                    line.start = room
                elif room.name == buf[1]:
                    line.end = room
            links_list.append(line)

    start_room = re.findall('##start\n(\w+)', map_data)[0].split('\n')[0]

    moves_list = []
    moved_ants = set()
    for path in paths:
        move_per_ant = ' ' + path
        move_per_ant = move_per_ant.split(' L')
        moves = {}
        for ant_move in move_per_ant:
            if ant_move != '':
                ant_move = ant_move.split('-')
                if not ant_move[0] in moved_ants:
                    moved_ants.add(ant_move[0])
                    moves[ant_move[0]] = Move(rooms_dict[start_room],
                                              rooms_dict[ant_move[1]],
                                              ant_move[0])
                else:
                    previous_ant_move = moves_list[-1][ant_move[0]]
                    moves[ant_move[0]] = Move(previous_ant_move.end,
                                              rooms_dict[ant_move[1]],
                                              ant_move[0])
        moves_list.append(moves)

    game = Game(links_list, moves_list)
    game.run()
예제 #2
0
    def post(self):
        t_values = {}
        current_link_id = self.request.POST['current_link_id']
        link_title = self.request.POST['link_title']
        link_target = self.request.POST['link_target']
        link_sequence = self.request.POST['link_sequence']
        logging.info("LinkManager post: current_link_id = %s, link_title = %s, link_target = %s, link_sequence = %s" % (current_link_id, link_title, 'link_target', 'link_sequence'))

        if current_link_id:
            # edit existed link
            link = Link.get_by_id(long(current_link_id))
            link.title = link_title
            link.target = link_target
            link.sequence = long(link_sequence)
            link.put()
            t_values['alert_message'] = "link %s has been updated" % (link.title)
        else:
            # create new link
            link = Link(title=link_title, target=link_target, sequence=long(link_sequence))
            link.put()
            t_values['alert_message'] = "link %s has been added" % (link.title)

        # find all links
        links = Link.all().order("-date")
        t_values["links"] = links
        return self.response.out.write(render_template("links.html", t_values, "", True))
예제 #3
0
파일: admin.py 프로젝트: yobin/saepy-log
 def post(self, secret=""):
     data = (self.get_argument("data", ""),)
     if id and data and secret:
         if secret == getAttr("MOVE_SECRET"):
             Link.set_link(encode_special_txt(data[0]))
             return self.write("1")
     return self.write("Fail")
예제 #4
0
def addNewLink(originalLink):
    session = scoped_session(SessionFactory)
    link = Link(originalLink)
    session.add(link)
    session.flush()
    link.shortLink = makeMiniature(int(link.id))
    session.commit()
    session.remove()
    result = {
        'request_id': link.id,
        'short_url': request.url_root.encode() + link.shortLink
    }
    return 201, result
예제 #5
0
파일: blog.py 프로젝트: sunruijia/simblog
 def post(self):
     action = self.param('action')
     name,url = (self.request.get(item) for item in ('linkName', 'linkURL'))
     if(action == 'edit'):
         key = self.param('id')
         link = Link.get_by_id(int(key))
         link.linkName = name
         link.linkURL = url
     else:
         link = Link(linkName=name,linkURL=url)
     link.put()
     self.redirect('/admin/links')   
     return  
예제 #6
0
    def get(self):
        link = Link(title="linkx1", target="http://baidu.com", sequence=9)
        link.put()

        link = Link(title="linkx2", target="http://baidu.com", sequence=9)
        link.put()

        link = Link(title="linkx3", target="http://baidu.com", sequence=9)
        link.put()
        return self.response.out.write(render_template("index.html", {}, "basic", False))
예제 #7
0
파일: blog.py 프로젝트: sunruijia/simblog
 def post(self):
     action = self.param('action')
     name, url = (self.request.get(item)
                  for item in ('linkName', 'linkURL'))
     if (action == 'edit'):
         key = self.param('id')
         link = Link.get_by_id(int(key))
         link.linkName = name
         link.linkURL = url
     else:
         link = Link(linkName=name, linkURL=url)
     link.put()
     self.redirect('/admin/links')
     return
def selection_sort_swap_value(link: Link) -> Link:
    """
    选择排序

    不交换节点,只交换值的方式
    """
    head_node = Node(0, link.head_node)
    start_node = head_node.next_node
    while start_node:
        swap_node = None
        current_node = start_node.next_node
        while current_node:
            if current_node < start_node:
                if not swap_node or swap_node > current_node:
                    swap_node = current_node

            current_node = current_node.next_node

        if swap_node:
            swap_node.element, start_node.element = start_node.element, swap_node.element

        start_node = start_node.next_node

    link.head_node = head_node.next_node
    return link
예제 #9
0
 def delete_link(cls, id):
     link = LinkModel.get_by_id(id)
     if link:
         link.key.delete()
     linkDoc = cls.getDoc(id)
     if linkDoc:
         cls.removeDocById(id)
예제 #10
0
    def get(self, name = ''):
        objs = Category.get_cat_page_posts(name, 1)

        catobj = Category.get_cat_by_name(name)
        if catobj:
            pass
        else:
            self.redirect(BASE_URL)
            return

        allpost =  catobj.id_num
        allpage = allpost/EACH_PAGE_POST_NUM
        if allpost%EACH_PAGE_POST_NUM:
            allpage += 1

        output = self.render('index.html', {
            'title': "%s - %s"%( catobj.name, getAttr('SITE_TITLE')),
            'keywords':catobj.name,
            'description':getAttr('SITE_DECR'),
            'objs': objs,
            'cats': Category.get_all_cat_name(),
            'tags': Tag.get_hot_tag_name(),
            'archives': Archive.get_all_archive_name(),
            'page': 1,
            'allpage': allpage,
            'listtype': 'cat',
            'name': name,
            'namemd5': md5(name.encode('utf-8')).hexdigest(),
            'comments': Comment.get_recent_comments(),
            'links':Link.get_all_links(),
            'isauthor':self.isAuthor(),
            'Totalblog':get_count('Totalblog',NUM_SHARDS,0),
        },layout='_layout.html')
        self.write(output)
        return output
def optimize_insertion_sort(link: Link) -> Link:
    """
    优化插入排序

    测试:
        链表的长度为 1000 --- Total execution time: 235 ms
        链表的长度为 10000 --- Total execution time: 23785 ms

    leetcode:
        link: https://leetcode-cn.com/problems/insertion-sort-list/
        执行用时: 220 ms, 在所有 Python3 提交中击败了 74.71% 的用户
        内存消耗: 15.3 MB, 在所有 Python3 提交中击败了 12.50% 的用户
    """
    head_node = Node(0, link.head_node)

    current_node = link.head_node
    while current_node and current_node.next_node:
        if current_node <= current_node.next_node:
            current_node = current_node.next_node
            continue

        start_node = head_node
        while start_node.next_node < current_node.next_node:
            start_node = start_node.next_node

        temp_node = current_node.next_node
        current_node.next_node = temp_node.next_node
        temp_node.next_node = start_node.next_node
        start_node.next_node = temp_node

    link.head_node = head_node.next_node
    return link
예제 #12
0
    def get(self, page_slug=""):
        if page_slug:
            t_values = {}

            posts = Entry.all().filter("is_external_page =", True).filter("entrytype =", 'page').filter("slug =", page_slug)
            if posts.count() == 1:
                logging.warning("find one page with slug=%s" % (page_slug))
                posts = posts.fetch(limit=1)
                post = posts[0]
                t_values['post'] = post
                # dump(post)

                # find all comments
                comments = Comment.all().filter("entry =", post).order("date")
                t_values['comments'] = comments
            else:
                logging.warning("%d entries share the same slug %s" % (posts.count(), page_slug))

            links = Link.all().order("date")
            t_values['links'] = links

            categories = Category.all()
            t_values['categories'] = categories

            pages = Entry.all().filter("is_external_page =", True).filter("entrytype =", 'page').order("date")
            t_values['pages'] = pages

            return self.response.out.write(render_template("page.html", t_values, "basic", False))
        else:
            self.redirect(uri_for("weblog.index"))
예제 #13
0
 def get(self, direction = 'next', page = '2', base_id = '1'):
     if page == '1':
         self.redirect(BASE_URL)
         return
     objs = Article.get_page_posts(direction, page, base_id)
     if objs:
         if direction == 'prev':
             objs.reverse()            
         fromid = objs[0].id
         endid = objs[-1].id
     else:
         fromid = endid = ''
     
     allpost =  Article.count_all_post()
     allpage = allpost/EACH_PAGE_POST_NUM
     if allpost%EACH_PAGE_POST_NUM:
         allpage += 1
     output = self.render('index.html', {
         'title': "%s - %s | Part %s"%(SITE_TITLE,SITE_SUB_TITLE, page),
         'keywords':KEYWORDS,
         'description':SITE_DECR,
         'objs': objs,
         'cats': Category.get_all_cat_name(),
         'tags': Tag.get_hot_tag_name(),
         'page': int(page),
         'allpage': allpage,
         'listtype': 'index',
         'fromid': fromid,
         'endid': endid,
         'comments': Comment.get_recent_comments(),
         'links':Link.get_all_links(),
     },layout='_layout.html')
     self.write(output)
     return output
예제 #14
0
 def get(self):
     try:
         objs = Article.get_post_for_homepage()
     except:
         self.redirect('/install')
         return
     if objs:
         fromid = objs[0].id
         endid = objs[-1].id
     else:
         fromid = endid = ''
     
     allpost =  Article.count_all_post()
     allpage = allpost/EACH_PAGE_POST_NUM
     if allpost%EACH_PAGE_POST_NUM:
         allpage += 1
     
     output = self.render('index.html', {
         'title': "%s - %s"%(SITE_TITLE,SITE_SUB_TITLE),
         'keywords':KEYWORDS,
         'description':SITE_DECR,
         'objs': objs,
         'cats': Category.get_all_cat_name(),
         'tags': Tag.get_hot_tag_name(),
         'page': 1,
         'allpage': allpage,
         'listtype': 'index',
         'fromid': fromid,
         'endid': endid,
         'comments': Comment.get_recent_comments(),
         'links':Link.get_all_links(),
     },layout='_layout.html')
     self.write(output)
     return output
예제 #15
0
def main():
    Q = QiniuProvider()
    countries = parseTable(
        Link(f'{domain}/wiki/List_of_IOC_country_codes').getText())
    beginTime = datetime.now()
    with ThreadPoolExecutor(max_workers=10) as pool:
        allTasks = []

        sqlFile = open('countryList.sql', 'w', encoding="utf-8")
        sqlWriter = SQLExporter(sqlFile, 'nationality',
                                ['name', 'code', 'flag'])

        for country in countries:
            print(f'graping {country.name}...')
            allTasks.append(
                pool.submit(
                    executor,
                    ExecutorParams(q=Q, country=country, writer=sqlWriter)))

        for task in as_completed(allTasks):
            print(f'{task.result()} downloaded.')

        sqlFile.close()

        endTime = datetime.now()

        print(f'run time: {endTime - beginTime}')
예제 #16
0
 def get(self, name = ''):
     objs = Tag.get_tag_page_posts(name, 1)
     
     catobj = Tag.get_tag_by_name(name)
     if catobj:
         pass
     else:
         self.redirect(BASE_URL)
         return
     
     allpost =  catobj.id_num
     allpage = allpost/EACH_PAGE_POST_NUM
     if allpost%EACH_PAGE_POST_NUM:
         allpage += 1
         
     output = self.render('index.html', {
         'title': "%s - %s"%( catobj.name, SITE_TITLE),
         'keywords':catobj.name,
         'description':SITE_DECR,
         'objs': objs,
         'cats': Category.get_all_cat_name(),
         'tags': Tag.get_hot_tag_name(),
         'page': 1,
         'allpage': allpage,
         'listtype': 'tag',
         'name': name,
         'namemd5': md5(name.encode('utf-8')).hexdigest(),
         'comments': Comment.get_recent_comments(),
         'links':Link.get_all_links(),
     },layout='_layout.html')
     self.write(output)
     return output
예제 #17
0
 def delete_link(cls, id):
     link = LinkModel.get_by_id(id)
     if link:
         link.key.delete()
     linkDoc = cls.getDoc(id)
     if linkDoc:
         cls.removeDocById(id)
예제 #18
0
파일: cache.py 프로젝트: fly2014/XBLOG
	def update_basic_info(
		update_categories=False,
		update_tags=False,
		update_links=False,
		update_comments=False,
		update_archives=False,
		update_pages=False):

		from model import Entry,Archive,Comment,Category,Tag,Link
		basic_info = ObjCache.get(is_basicinfo=True)
		if basic_info is not None:
			info = ObjCache.get_cache_value(basic_info.cache_key)
			if update_pages:
				info['menu_pages'] = Entry.all().filter('entrytype =','page')\
							.filter('published =',True)\
							.filter('entry_parent =',0)\
							.order('menu_order').fetch(limit=1000)
			if update_archives:
				info['archives'] = Archive.all().order('-year').order('-month').fetch(12)
			if update_comments:
				info['recent_comments'] = Comment.all().order('-date').fetch(5)
			if update_links:
				info['blogroll'] = Link.all().filter('linktype =','blogroll').fetch(limit=1000)
			if update_tags:
				info['alltags'] = Tag.all().order('-tagcount').fetch(limit=100)
			if update_categories:
				info['categories'] = Category.all().fetch(limit=1000)

			logging.debug('basic_info updated')
			basic_info.update(info)
예제 #19
0
파일: blog.py 프로젝트: yobin/saepy-log
    def get(self, direction='next', page='2', base_id='1'):
        if page == '1':
            self.redirect(BASE_URL)
            return
        objs = Article.get_page_posts(direction, page, base_id)
        if objs:
            if direction == 'prev':
                objs.reverse()
            if MYSQL_TO_KVDB_SUPPORT:
                fromid = objs[0]['id']
                endid = objs[-1]['id']
            else:
                fromid = objs[0].id
                endid = objs[-1].id
        else:
            fromid = endid = ''

        allpost = Article.count_all_post()
        allpage = allpost / EACH_PAGE_POST_NUM
        if allpost % EACH_PAGE_POST_NUM:
            allpage += 1
        output = self.render('index.html', {
            'title':
            "%s - %s | Part %s" %
            (getAttr('SITE_TITLE'), getAttr('SITE_SUB_TITLE'), page),
            'keywords':
            getAttr('KEYWORDS'),
            'description':
            getAttr('SITE_DECR'),
            'objs':
            objs,
            'cats':
            Category.get_all_cat_name(),
            'tags':
            Tag.get_hot_tag_name(),
            'archives':
            Archive.get_all_archive_name(),
            'page':
            int(page),
            'allpage':
            allpage,
            'listtype':
            'index',
            'fromid':
            fromid,
            'endid':
            endid,
            'comments':
            Comment.get_recent_comments(),
            'links':
            Link.get_all_links(),
            'isauthor':
            self.isAuthor(),
            'Totalblog':
            get_count('Totalblog', NUM_SHARDS, 0),
        },
                             layout='_layout.html')
        self.write(output)
        return output
예제 #20
0
def create_link(teacher_id, student_id):
    """Create a teacher/student link."""

    link = Link(teacher_id=teacher_id, student_id=student_id)

    db.session.add(link)
    db.session.commit()

    return link
예제 #21
0
파일: blog.py 프로젝트: sunruijia/simblog
 def get(self):
     action = self.param('action')
     values = {'action': action}
     if (action == 'edit'):
         key = self.param('id')
         link = Link.get_by_id(int(key))
         values.update({'link': link})
     self.generateBasePage('manage/link.html', values)
     return
예제 #22
0
파일: blog.py 프로젝트: sunruijia/simblog
 def get(self):
     action = self.param('action')
     values = {'action':action}
     if(action == 'edit'):
         key = self.param('id')
         link = Link.get_by_id(int(key))
         values.update({'link':link})
     self.generateBasePage('manage/link.html', values)
     return
예제 #23
0
    def get(self, id = '', title = ''):
        tmpl = ''
        obj = Article.get_article_by_id_detail(id)
        if not obj:
            self.redirect(BASE_URL)
            return
        #redirect to right title
        try:
            title = unquote(title).decode('utf-8')
        except:
            pass
        if title != obj.slug:
            self.redirect(obj.absolute_url, 301)
            return
        #
        if obj.password and THEME == 'default':
            rp = self.get_cookie("rp%s" % id, '')
            if rp != obj.password:
                tmpl = '_pw'
        elif obj.password and BLOG_PSW_SUPPORT:
            rp = self.get_cookie("rp%s" % id, '')
            print 'rp===%s' % (str(rp))
            if rp != obj.password:
                tmpl = '_pw'

        keyname = 'pv_%s' % (str(id))
        increment(keyname)#yobin 20120701
        self.set_cookie(keyname, '1', path = "/", expires_days =1)
        self.set_header("Last-Modified", obj.last_modified)
        output = self.render('page%s.html'%tmpl, {
            'title': "%s - %s"%(obj.title, getAttr('SITE_TITLE')),
            'keywords':obj.keywords,
            'description':obj.description,
            'obj': obj,
            'cobjs': obj.coms,
            'postdetail': 'postdetail',
            'cats': Category.get_all_cat_name(),
            'tags': Tag.get_hot_tag_name(),
            'archives': Archive.get_all_archive_name(),
            'page': 1,
            'allpage': 10,
            'comments': Comment.get_recent_comments(),
            'links':Link.get_all_links(),
            'isauthor':self.isAuthor(),
            'hits':get_count(keyname),
            'Totalblog':get_count('Totalblog',NUM_SHARDS,0),
            'listtype': '',
        },layout='_layout.html')
        self.write(output)

        if obj.password and BLOG_PSW_SUPPORT:
            return output
        elif obj.password and THEME == 'default':
            return
        else:
            return output
예제 #24
0
    def post(self):
        act = self.get_argument("act", "")
        id = self.get_argument("id", "")
        name = self.get_argument("name", "")
        sort = self.get_argument("sort", "0")
        url = self.get_argument("url", "")

        if name and url:
            params = {"id": id, "name": name, "url": url, "displayorder": sort}
            if act == "add":
                Link.add_new_link(params)

            if act == "edit":
                Link.update_link_edit(params)

            clear_cache_by_pathlist(["/"])

        self.redirect("%s/admin/links" % (BASE_URL))
        return
예제 #25
0
파일: blog.py 프로젝트: sunruijia/simblog
 def post(self):
     try:
         checkList = self.request.get_all('checks')
         for key in checkList:
             keyID = int(key)
             link=Link.get_by_id(keyID)
             link.delete()
     finally:
         self.redirect('/admin/links')        
     return   
예제 #26
0
    def post(self):
        act = self.get_argument("act",'')
        id = self.get_argument("id",'')
        name = self.get_argument("name",'')
        sort = self.get_argument("sort",'0')
        url = self.get_argument("url",'')

        if name and url:
            params = {'id': id, 'name': name, 'url': url, 'displayorder': sort}
            if act == 'add':
                Link.add_new_link(params)

            if act == 'edit':
                Link.update_link_edit(params)

            clear_cache_by_pathlist(['/'])

        self.redirect('%s/admin/links'% (BASE_URL))
        return
예제 #27
0
파일: blog.py 프로젝트: sunruijia/simblog
 def post(self):
     try:
         checkList = self.request.get_all('checks')
         for key in checkList:
             keyID = int(key)
             link = Link.get_by_id(keyID)
             link.delete()
     finally:
         self.redirect('/admin/links')
     return
예제 #28
0
def get_all_links():
  next_page_cur = request.args.get('next')
  links, cursor, more = L.get_all_links(next_page_cur)
  if len(links):
    links = [l.to_dict() for l in links]
    return jsonify(size=len(links), \
                   data=links, \
                   next=cursor.urlsafe() if more else None, \
                   more=more)
  else:
    return jsonify(size=0, data=[], next=None, more=False)
def insertion_sort(link: Link) -> Link:
    """
    插入排序

    测试:
        链表的长度为 1000 --- Total execution time: 286 ms
        链表的长度为 10000 --- Total execution time: 30442 ms

    leetcode:
        link: https://leetcode-cn.com/problems/insertion-sort-list/
        执行用时: 2564 ms, 在所有 Python3 提交中击败了 9.48% 的用户
        内存消耗: 15.3 MB, 在所有 Python3 提交中击败了 12.50% 的用户

    问题:
        1.使用了新的空间
        2.进行了多次的比较

    优化:
        1.在不断链的情况下进行排序
        2.减少比较次数
    """

    new_head_node = None
    current_node = link.head_node

    while current_node:
        next_node = current_node.next_node
        current_node.next_node = None

        if not new_head_node:
            new_head_node = current_node
        else:
            node = new_head_node
            last_node = None
            while node:
                if node > current_node:
                    current_node.next_node = node
                    if not last_node:
                        new_head_node = current_node
                    else:
                        last_node.next_node = current_node
                    break

                elif not node.next_node:
                    node.next_node = current_node
                    break

                last_node = node
                node = node.next_node

        current_node = next_node

    link.head_node = new_head_node
    return link
예제 #30
0
 def save_link(cls, title, url, body="", tags=[], clicks=0, unread=True):
     url = norm(url)
     id = mmh3.hash(url)
     key = ndb.Key(LinkModel, id)
     domain = urlparse(url).netloc
     if len(domain) > 4 and domain.startswith('www.'):
         domain = domain[4:]
     link = LinkModel(key=key,
                      title=title,
                      url=url,
                      domain=domain,
                      body=body,
                      tags=tags,
                      clicks=clicks,
                      unread=unread)
     link.put()
     id = str(link.id)
     doc = cls._buildDoc(id, title, body, domain, tags)
     cls.add(doc)
     return cls(doc, link)
예제 #31
0
 def save_link(cls, title, url, body="", tags=[], clicks=0, unread=True):
     url = norm(url)
     id = mmh3.hash(url)
     key = ndb.Key(LinkModel, id)
     domain = urlparse(url).netloc
     if len(domain)>4 and domain.startswith('www.'):
         domain = domain[4:]
     link = LinkModel( key = key,
                       title = title,
                       url = url,
                       domain = domain,
                       body = body,
                       tags = tags,
                       clicks = clicks,
                       unread = unread )
     link.put()
     id = str(link.id)
     doc = cls._buildDoc(id, title, body, domain, tags)
     cls.add(doc)
     return cls(doc, link)
예제 #32
0
    def get(self):
        act = self.get_argument("act",'')
        id = self.get_argument("id",'')

        obj = None
        if act == 'del':
            if id:
                Link.del_link_by_id(id)
                clear_cache_by_pathlist(['/'])
            self.redirect('%s/admin/links'% (BASE_URL))
            return
        elif act == 'edit':
            if id:
                obj = Link.get_link_by_id(id)
                clear_cache_by_pathlist(['/'])
        self.echo('admin_link.html', {
            'title': "管理友情链接",
            'objs': Link.get_all_links(),
            'obj': obj,
        },layout='_layout_admin.html')
예제 #33
0
 def get(self):
     act = self.get_argument("act",'')
     id = self.get_argument("id",'')
     
     obj = None
     if act == 'del':
         if id:
             Link.del_link_by_id(id)
             clear_cache_by_pathlist(['/'])
         self.redirect('%s/admin/links'% (BASE_URL))
         return
     elif act == 'edit':
         if id:
             obj = Link.get_link_by_id(id)
             clear_cache_by_pathlist(['/'])
     self.echo('admin_link.html', {
         'title': "管理友情链接",
         'objs': Link.get_all_links(),
         'obj': obj,
     },layout='_layout_admin.html')        
예제 #34
0
def migrate():
    LinkDoc.deleteAllInIndex()
    q = Link.query()
    links = q.fetch(65535)
    for link in links:
        title = link.title
        url = link.url
        tags = link.tags
        body = link.body
        link.key.delete()
        LinkDoc.save_link(title, url, body, tags)
예제 #35
0
    def get(self):
        act = self.get_argument("act", "")
        id = self.get_argument("id", "")

        obj = None
        if act == "del":
            if id:
                Link.del_link_by_id(id)
                clear_cache_by_pathlist(["/"])
            self.redirect("%s/admin/links" % (BASE_URL))
            return
        elif act == "edit":
            if id:
                obj = Link.get_link_by_id(id)
                clear_cache_by_pathlist(["/"])
        self.echo(
            "admin_link.html",
            {"title": "管理友情链接", "objs": Link.get_all_links(), "obj": obj},
            layout="_layout_admin.html",
        )
예제 #36
0
def reverse_link(link: Link) -> Link:
    " 反转链表 "
    new_head_node = None
    current_node = link.head_node
    while current_node:
        next_node = current_node.next_node
        current_node.next_node = new_head_node
        new_head_node = current_node
        current_node = next_node

    link.head_node = new_head_node
    return link
예제 #37
0
    def get(self):
        # find stats for this blog
        stats = {}
        stats['posts'] = Entry.all().filter("entrytype =", "post").filter("is_external_page =", True).count()
        stats['pages'] = Entry.all().filter("entrytype =", "page").filter("is_external_page =", True).count()
        stats['comments'] = Comment.all().count()
        stats['categories'] = Category.all().count()
        stats['links'] = Link.all().count()

        t_values = {}
        t_values['stats'] = stats
        return self.response.out.write(render_template("index.html", t_values, "", True))
def quicksort_main_swap_node(link: Link) -> Link:
    """
    快速排序(递归,交换节点)

    测试:
        链表的长度为 1000 --- Total execution time: 19 ms
        链表的长度为 10000 --- Total execution time: 239 ms
    """
    head_pre_node = Node(0, link.head_node)
    quicksort_swap_node(head_pre_node, link.head_node, None)
    link.head_node = head_pre_node.next_node
    return link
예제 #39
0
    def get(self, link_id="", operation=""):
        t_values = {}
        logging.info("LinkManager: link_id = %s, operation = %s" % (link_id, operation))

        # find current_link from link_id
        if link_id:
            current_link = Link.get_by_id(long(link_id))
            if current_link:
                logging.info("found link %s from link_id: %s" % (current_link.title, link_id))
                if operation == "delete":
                    current_link.delete()
                    t_values['alert_message'] = "Link %s has been deleted." % (current_link.title)
                    # t_values['redirect_location'] = uri_for("admin.links")
                    # return self.response.out.write(render_template("alert.html", t_values, "", True))
                elif operation == "edit":
                    # pass current_link to template
                    t_values['current_link'] = current_link

        # find all links
        links = Link.all().order("-date")
        t_values["links"] = links
        return self.response.out.write(render_template("links.html", t_values, "", True))
def merge_sort_main(link: Link) -> Link:
    """
    归并排序(递归)

    测试:
        链表的长度为 1000 --- Total execution time: 14 ms
        链表的长度为 10000 --- Total execution time: 175 ms

    leetcode:
        link: https://leetcode-cn.com/problems/sort-list/submissions/
        执行用时: 224 ms, 在所有 Python3 提交中击败了 67.87% 的用户
        内存消耗: 20.7 MB, 在所有 Python3 提交中击败了 28.57% 的用户
    """
    link.head_node = merge_sort(link.head_node)
    return link
예제 #41
0
def search_link():
  query = request.args.get('query')
  if not query:
    return jsonify(size=0, data=[])

  query_string = to_query_string(query)
  if query_string == '':
    return jsonify(size=0, data=[])

  ids = Link.search(query_string)
  if len(ids):
    links = map(lambda x:L.get_by_id(int(x)), ids)
    links = [l.to_dict() for l in links]
    return jsonify(size = len(links), data=links)
  else:
    return jsonify(size=0, data=[])
예제 #42
0
def update_link(id):
  link = L.get_by_id(id)
  if link == None:
    return jsonify(success=False, message="No link exisit by id: "+str(id))
  title = request.form.get('title')
  body = request.form.get('body')
  unread = request.form.get('unread', type=bool)
  tags = request.form.getlist('tags')
  clicks = int(request.form.get('clicks'))
  if title != link.title or body != link.body or tags != link.tags:
    Link.save_link(title, link.url, body, tags, clicks, unread)
  elif unread != link.unread or clicks != link.clicks:
    link.unread = unread
    link.clicks = clicks
    link.put()

  return jsonify(success=True, size=1, data=link)
예제 #43
0
    def get(self, page="1", cate_slug=""):
        t_values = {}
        page = int(page)
        logging.info("IndexHandler - get: page = %d, cate_slug = %s" % (page, cate_slug))

        # find all entries by order
        query = Entry.all().filter("is_external_page =", True).filter("entrytype =", 'post').order("-date")
        # add category filter?
        if cate_slug:
            cates = Category.all().filter("slug =", cate_slug)
            if cates:
                query = query.filter("category =", cates[0])

        # pagination
        total_posts = query.count()
        q_limit = Configuration["posts_per_page"]
        q_offset = (page - 1) * Configuration["posts_per_page"]
        logging.info("limit = %d, offset = %d" % (q_limit, q_offset))

        # get entries
        entries = query.fetch(limit=q_limit, offset=q_offset)
        t_values['entries'] = entries

        # show entries for debug purpose
        # for entry in entries:
        #     logging.info("entry title: %s, public = %s, cate = %s" % (entry.title, entry.is_external_page, entry.category.name))

        logging.info("total posts = %d, current_page = %d, posts_per_page = %d" % (total_posts, page, Configuration['posts_per_page']))
        t_values['navlist'] = generateNavList(total_posts, page, Configuration["posts_per_page"])
        # logging.info(t_values['navlist'])

        # find all links
        links = Link.all().order("date")
        t_values['links'] = links

        # find all categories
        categories = Category.all()
        t_values['categories'] = categories

        # find all pages
        pages = Entry.all().filter("is_external_page =", True).filter("entrytype =", 'page').order("date")
        t_values['pages'] = pages

        # show index page
        return self.response.out.write(render_template("index.html", t_values, "basic", False))
예제 #44
0
파일: blog.py 프로젝트: yobin/saepy-log
    def get(self, listtype = '', direction = 'next', page = '1', name = ''):
        if listtype == 'cat':
            objs = Category.get_cat_page_posts(name, page)
            catobj = Category.get_cat_by_name(name)
        elif listtype == 'tag':
            objs = Tag.get_tag_page_posts(name, page)
            catobj = Tag.get_tag_by_name(name)
        elif listtype == 'archive':
            objs = Archive.get_archive_page_posts(name, page)
            catobj = Archive.get_archive_by_name(name)
        #
        if not catobj:
            return self.redirect(BASE_URL)

        if not objs:
            return self.redirect(BASE_URL)

        if MYSQL_TO_KVDB_SUPPORT:
            allpost =  len(catobj.split(','))
        else:
            allpost =  catobj.id_num
        allpage = allpost/EACH_PAGE_POST_NUM
        if allpost%EACH_PAGE_POST_NUM:
            allpage += 1

        output = self.render('index.html', {
            'title': "%s - %s | Part %s"%( name, getAttr('SITE_TITLE'), page),
            'keywords':name,
            'description':getAttr('SITE_DECR'),
            'objs': objs,
            'cats': Category.get_all_cat_name(),
            'tags': Tag.get_hot_tag_name(),
            'archives': Archive.get_all_archive_name(),
            'page': int(page),
            'allpage': allpage,
            'listtype': listtype,
            'name': name,
            'namemd5': md5(name.encode('utf-8')).hexdigest(),
            'comments': Comment.get_recent_comments(),
            'links':Link.get_all_links(),
            'isauthor':self.isAuthor(),
            'Totalblog':get_count('Totalblog',NUM_SHARDS,0),
        },layout='_layout.html')
        self.write(output)
        return output
예제 #45
0
파일: blog.py 프로젝트: yobin/saepy-log
    def get(self):
        try:
            objs = Article.get_post_for_homepage()
        except:
            self.redirect('/install')
            return
        if objs:
            if MYSQL_TO_KVDB_SUPPORT:
                fromid = objs[0]['id']
                endid = objs[-1]['id']
                #totalblog = Article.get_totalnum_arti()
                totalblog = get_count('Totalblog',NUM_SHARDS,0)
            else:
                fromid = objs[0].id
                endid = objs[-1].id
                totalblog = get_count('Totalblog',NUM_SHARDS,0)
        else:
            fromid = endid = ''

        allpost =  Article.count_all_post()
        allpage = allpost/EACH_PAGE_POST_NUM
        if allpost%EACH_PAGE_POST_NUM:
            allpage += 1

        output = self.render('index.html', {
            'title': "%s - %s"%(getAttr('SITE_TITLE'),getAttr('SITE_SUB_TITLE')),
            'keywords':getAttr('KEYWORDS'),
            'description':getAttr('SITE_DECR'),
            'objs': objs,
            'cats': Category.get_all_cat_name(),
            'tags': Tag.get_hot_tag_name(),
            'archives': Archive.get_all_archive_name(),
            'page': 1,
            'allpage': allpage,
            'listtype': 'index',
            'fromid': fromid,
            'endid': endid,
            'comments': Comment.get_recent_comments(),
            'links':Link.get_all_links(),
            'isauthor':self.isAuthor(),
            'Totalblog':totalblog,
        },layout='_layout.html')
        self.write(output)
        return output
예제 #46
0
 def get(self, id = '', title = ''):
     tmpl = ''
     obj = Article.get_article_by_id_detail(id)
     if not obj:
         self.redirect(BASE_URL)
         return
     #redirect to right title
     try:
         title = unquote(title).decode('utf-8')
     except:
         pass
     if title != obj.slug:
         self.redirect(obj.absolute_url, 301)
         return        
     #
     if obj.password and THEME == 'default':
         rp = self.get_cookie("rp%s" % id, '')
         if rp != obj.password:
             tmpl = '_pw'
     
     self.set_header("Last-Modified", obj.last_modified)
         
     output = self.render('page%s.html'%tmpl, {
         'title': "%s - %s"%(obj.title, SITE_TITLE),
         'keywords':obj.keywords,
         'description':obj.description,
         'obj': obj,
         'cobjs': obj.coms,
         'postdetail': 'postdetail',
         'cats': Category.get_all_cat_name(),
         'tags': Tag.get_hot_tag_name(),
         'page': 1,
         'allpage': 10,
         'comments': Comment.get_recent_comments(),
         'links':Link.get_all_links(),
     },layout='_layout.html')
     self.write(output)
     
     if obj.password and THEME == 'default':
         return
     else:
         return output