예제 #1
0
 def geturlwk(self, paramdct):
     wk = None
     if self.request.get('wkid'):
         paramdct['wkid'] = self.request.get('wkid')
         wk = Wiki.by_id(int(paramdct['wkid']))
     else:
         if paramdct['ishistorypage']:
             wk = Wiki.by_url_fetch(paramdct['path_info'])
             # wk=self.getDict(wk)
         else:
             wk = Wiki.by_url_get(paramdct['path_info'])
     return wk
예제 #2
0
    def post(self):
        paramdct = {}
        try:
            self.initwiki(paramdct)
            self.updatedct(paramdct)

            if paramdct['wkedit'] and not paramdct['haserror']:
                paramdct['content'] = self.request.get('content')
                if paramdct['content'] != paramdct['contentedit'] or paramdct[
                        'isnewurl']:
                    w = Wiki.newwikiurl(paramdct['path_info'],
                                        paramdct['content'])
                    w.put()
                    # self.redirect(paramdct['path_info']+'?wkid='+str(w.key().id()))
                # else:
                self.redirect(paramdct['path_info'])
            if paramdct['haserror']:
                self.response.write(
                    jw.WriteTemplate('wiki.html', 'website_layout.css', path,
                                     **paramdct))
            else:
                self.redirect(paramdct['path_info'])
        except Exception as err:
            if paramdct.has_key('error'):
                paramdct['error'] += ', ' + str(err)
            else:
                paramdct['error'] = err
            paramdct['wktemplate'] = 'wiki.html'
            self.response.write(
                jw.WriteTemplate(paramdct['wktemplate'], 'website_layout.css',
                                 path, **paramdct))
예제 #3
0
    def test_http_wiki_extract(self, monkeypatch):
        """To test a place, "musée d'orsay", with its latitude and longitude, that has a wikipedia page."""
        story = Wiki(48.8599614, 2.3265614)
        results = {
            "query": {
                "pages": [{
                    "extract":
                    "Le musée d’Orsay est un musée national inauguré en 1986, "
                    "situé dans le 7e arrondissement de Paris le long de la rive "
                    "gauche de la Seine. Il est installé dans l’ancienne gare d'Orsay, "
                    "construite par Victor Laloux de 1898 à 1900 et réaménagée en musée "
                    "sur décision du Président de la République Valéry Giscard d'Estaing."
                }]
            }
        }

        def mockreturn():
            return results

        monkeypatch.setattr(urllib.request, "urlopen", mockreturn)
        assert story.comment()[0] == results["query"]["pages"][0]["extract"]
예제 #4
0
 def get_content(word: Word, count: int) -> WikipediaExample:
     wikis = []
     try:
         items = wikipedia.search(word.name)[:count]
         for item in items:
             try:
                 page = wikipedia.page(item)
             except wikipedia.DisambiguationError as e:
                 item = e.options[0]
                 page = wikipedia.page(item)
             wikis.append(
                 Wiki(page.title,
                      page.content.split('\n', 1)[0], page.categories))
     except Exception as e:
         print(e)
     else:
         return WikipediaExample(word, wikis)
예제 #5
0
def query():
    """Method to receive the query from the client side (input form) with AJAX
    and return all the objects needed in json to AJAX, after making instances
    and running the methods from classes.py."""

    # Getting the text the user type in the input form.
    user_text = request.args.get("text")
    # Parsing the user text.
    # Parser instance creation.
    user_request = Parser(user_text)

    # Running the parsing method.
    user_query = user_request.parsing()

    # GoogleMaps instance creation.
    query = GoogleMaps(user_query)
    print(GoogleMaps("openclassrooms"))
    # Find the address of the place looked for.
    try:
        # Running the coordinates method and retrieving latitude, longitude
        # and the global address of the place the user is looking for.
        address_coords = query.location()
        format_address = address_coords[0]
        latitude = address_coords[1]
        longitude = address_coords[2]
        # GrandPy Bot different possible messages in case of success.
        addressAnswer = GrandPyMessages.randomAnswer()
        # Find a story of the wanted place.
        try:
            # MediaWiki instance creation.
            coords = Wiki(latitude, longitude)
            # Running the history method to get the wikipedia page for that coordonates.
            wikiExtract = coords.comment()[0]
            pageid = coords.comment()[1]
            if wikiExtract:
                # GrandPy Bot different possible messages in case of success.
                storyAnswer = GrandPyMessages.randomStory()
            else:
                # GrandPy Bot different possible messages if there is no answer from Wikipedia.
                storyAnswer = GrandPyMessages.randomNoStory()
                # Reference this empty variable.
                wikiExtract = ""
                pageid = ""
        except:
            print("coucou")
            # GrandPy Bot different possible messages if there is no answer from Wikipedia.
            storyAnswer = GrandPyMessages.randomNoStory()
            # Reference this empty variable.
            wikiExtract = ""
            pageid = ""
    except:

        # GrandPy Bot different possible messages if there is no answer from GoogleMaps.
        addressAnswer = GrandPyMessages.randomNoAnswer()
        # Reference those empty variables.
        latitude = ""
        longitude = ""
        format_address = ""
        wikiExtract = ""
        storyAnswer = ""
        pageid = ""

    # JSON with the responses send back to AJAX (home.js).
    return json.dumps(
        {
            "userText": user_text,
            "addressAnswer": addressAnswer,
            "lat": latitude,
            "lng": longitude,
            "format_address": format_address,
            "storyAnswer": storyAnswer,
            "wikiExtract": wikiExtract,
            "pageid": pageid,
        }
    )
예제 #6
0
def main(stdscr):

    #initialization
    menu = Menu(stdscr, 'Help', 'Play', 'Stats', 'Exit')
    keyboard = Keyboard(stdscr)
    database = Database(stdscr)
    mode = 0
    key = 0
    curses.curs_set(0)
    curses.noecho()
    curses.use_default_colors()

    #selct mode based on menu options
    while mode != 4:

        #menu mode
        if mode == 0:
            stdscr.clear()
            menu.print_splash()
            menu.print_menu()
            mode = menu.navigate(stdscr.getch())
            stdscr.refresh()

        #help mode
        elif mode == 1:
            help_string = '''
            Welcome to termtype! Termtype is a touch-typing aid 
            that allows you to practice your skills by typing 
            random Wikipedia articles. Simply type the displayed
            text, and refer to the line above to check which finger
            to use. From left pinky to right pinky, the fingers
            are numbered 1-8, with thumbs omitted.

            Press enter to remove typed words from the display,
            and press escape at any time to stop typing. Your
            typed words will still count towards your progress
            even if you don't finish the article, so feel free
            to stop at anytime!

            For more information, visit https://github.com/bajaco/termtype

            Press any key to continue:
            '''
            help_formatter = Formatter(stdscr, help_string)
            stdscr.clear()
            help_formatter.print_text()
            c = stdscr.getch()

            mode = 0

        #play mode
        elif mode == 2:

            #initialization for play mode
            wiki = Wiki()
            typing_buffer = Buffer()
            page_text = wiki.get_page()
            guide_text = keyboard.transform_text(page_text)
            error_text = ''
            errors = 0
            entered_words = 0
            timer = Timer()

            #Formatter for article
            wiki_formatter = Formatter(stdscr,
                                       page_text,
                                       line_height=6,
                                       vertical_offset=1,
                                       vertical_buffer=0)

            #Formatter for finger indication
            guide_formatter = Formatter(stdscr,
                                        guide_text,
                                        line_height=6,
                                        vertical_offset=0,
                                        vertical_buffer=0)

            #Formatter for typed text
            typing_formatter = Formatter(stdscr,
                                         typing_buffer.get_text(),
                                         line_height=6,
                                         vertical_offset=2,
                                         vertical_buffer=0)

            #Formatter for error text
            error_formatter = Formatter(stdscr,
                                        error_text,
                                        line_height=6,
                                        vertical_offset=3,
                                        vertical_buffer=0)

            #gameplay loop
            while (True):
                #clear string and print from formatters
                stdscr.clear()
                wiki_formatter.print_text()
                guide_formatter.print_text()
                typing_formatter.print_text()
                error_formatter.print_text()

                #break if there are no more words to be typed and show statistics
                if wiki_formatter.out_of_words():
                    timer.stop()
                    break

                #if key is enter, remove page from wiki and guide formatters
                stdscr.refresh()
                c = stdscr.getch()

                #if key is ENTER
                if c == 10:
                    count = typing_buffer.get_count()
                    entered_words += count
                    removed = wiki_formatter.remove_words(count)
                    guide_formatter.remove_words(count)
                    errors += typing_buffer.new_errors(removed)
                    typing_buffer.clear()
                    error_formatter.set_master('')
                    typing_formatter.set_master('')

                #if key is ESC
                elif c == 27:
                    count = typing_buffer.get_count()
                    entered_words += count
                    if entered_words == 0:
                        break
                    timer.stop()
                    removed = wiki_formatter.remove_words(count)
                    guide_formatter.remove_words(count)
                    errors += typing_buffer.new_errors(removed)
                    break

                #other keys
                else:
                    #start timing if necessary
                    if not timer.is_timing():
                        timer.start()

                    typing_buffer.input(c, keyboard)
                    typing_formatter.set_master(typing_buffer.get_text())
                    error_formatter.set_master(
                        keyboard.error_text(wiki_formatter.dump_text(),
                                            typing_buffer.get_text()))

            #statistics loop
            while (True):
                if entered_words == 0:
                    mode = 0
                    break
                stdscr.clear()
                database.write(timer.get_duration(), entered_words, errors)
                database.read()
                database.print_stats()
                stdscr.refresh()

                c = stdscr.getkey()
                if c == 'q':
                    mode = 4
                    break
                else:
                    mode = 0
                    break
        #stats mode
        elif mode == 3:

            while (True):
                stdscr.clear()
                database.read()
                database.print_stats()
                stdscr.refresh()
                c = stdscr.getkey()
                if c == 'q':
                    mode = 4
                    break
                else:
                    mode = 0
                    break