def make_books(self, odds, evens): self.books.clear() current_book = book.Book() total = len(odds) for i in range(total): odd = odds[i] even = evens[i] if i % 3 == 0: name_a_s = BeautifulSoup(str(odd), 'html5lib').find_all('a') current_book.target = name_a_s[0].get('href') current_book.book_name = name_a_s[0].string chapter_a_s = BeautifulSoup(str(even), 'html5lib').find_all('a') current_book.new_chapter = chapter_a_s[0].string if i % 3 == 1: current_book.author = odd.string current_book.words = even.string if i % 3 == 2: current_book.time = odd.string current_book.status = even.string self.books.append(current_book) current_book = book.Book() self.show_msg('共找到' + str(len(self.books)) + '本书') print('共找到', len(self.books), '本书')
def test_equals_operator(self): """Tests the == operator for the Book class.""" book1 = book.Book("Little Women", ("Louisa", "May", "Alcott")) book2 = book.Book("Little Women", ("Louisa", "May", "Alcott")) self.assertEqual(book1, book2) book3 = book.Book("War and Peace", ("Leo", "", "Tolstoy")) self.assertNotEqual(book1, book3)
def test_RemoveBook(self): """Tests that a book is successfully removed from a shelf, decreasing the book count from 2 to 1.""" test_shelf = shelf.Shelf() little_women = book.Book("Little Women", ("Louisa", "May", "Alcott")) warriors = book.Book("Warriors", ("Erin", "", "Hunter")) test_shelf.AddBook(warriors) test_shelf.AddBook(little_women) test_shelf.RemoveBook("Little Women") self.assertTrue(test_shelf.GetBookCount(), 1)
def test_GetAuthor(self): """Tests that the author is a tuple.""" little_women = book.Book("Little Women", ("Louisa", "May", "Alcott")) self.assertIsInstance(little_women.GetAuthor(), tuple) self.assertEqual(3, len(little_women.GetAuthor())) little_women = book.Book("Little Women", ()) self.assertIsInstance(little_women.GetAuthor(), tuple) self.assertEqual(0, len(little_women.GetAuthor()))
def test_GetAuthorAsString(self): """Tests that the author is returned as a properly formatted string.""" little_women = book.Book("Little Women", ("Louisa", "May", "Alcott")) self.assertEqual("Louisa May Alcott", little_women.GetAuthorAsString()) war_and_peace = book.Book("War and Peace", ("Leo", "", "Tolstoy")) self.assertEqual("Leo Tolstoy", war_and_peace.GetAuthorAsString()) hobbit = book.Book("The Hobbit", ("J", "R R", "Tolkien")) self.assertEqual("J R R Tolkien", hobbit.GetAuthorAsString())
def sort_shelves(self, letter, shelf_id): if shelf_id <= 1: return temp = self.get_first_book_on_shelf(letter, shelf_id) first_id = temp[0] first_book = bk.Book(temp[1], temp[2], temp[3]) temp = self.get_last_book_on_shelf(letter, (shelf_id - 1)) last_id = temp[0] last_book = bk.Book(temp[1], temp[2], temp[3]) if last_book > first_book: self.replace_book_on_shelf(last_id, letter, shelf_id) self.replace_book_on_shelf(first_id, letter, (shelf_id - 1)) self.sort_shelves(letter, (shelf_id - 1))
def test_shelf_space_exhausted(self): """Tests that an exception is raised and the book count does not change when adding a book to a shelf with insufficient space.""" test_shelf = shelf.Shelf() little_women = book.Book("Little Women", ("Louisa", "May", "Alcott")) warriors = book.Book("Warriors", ("Erin", "", "Hunter")) warriors.SetPages(70) warriors.SetCoverType(book.CoverType.HARDCOVER) little_women.SetPages(20) little_women.SetCoverType(book.CoverType.HARDCOVER) test_shelf.AddBook(warriors) test_shelf.AddBook(little_women) self.assertRaises(RuntimeError) self.assertTrue(test_shelf.GetBookCount(), 1)
def main(): rev = review.Review("Horosho") rev2 = review.Review("Ploho") autor_Tolstoy = author.Author("Leo", "Tolstoy", 1828) boo = book.Book(autor_Tolstoy, "WAR Pease", "1488", "War") boo1 = book.Book(autor_Tolstoy, "Anna K", "1489", "Drama") boo.add_review(rev) boo.add_review(rev2) autor_Tolstoy.add_book(boo) autor_Tolstoy.add_book(boo1) print(autor_Tolstoy) print(boo) print(boo1)
def parse(input_file_path): with open(input_file_path, "r") as input_file: books_count, libraries_count, days = ( int(x) for x in input_file.readline().split(' ')) # print books_count, libraries_count, days books = [ book.Book(book_id, score) for (book_id, score) in enumerate(input_file.readline().split(' ')) ] # for b in books: # print b.id, b.score libraries_data_lines = input_file.readlines() # print libraries_data_lines libraries = [] for lib_id in range(libraries_count): number_of_books, signup_time, scanning_throughput = ( int(x) for x in libraries_data_lines[2 * lib_id].split(' ')) # print number_of_books, signup_time, scanning_throughput books_ids = [ int(x) for x in libraries_data_lines[2 * lib_id + 1].split(' ') ] libraries.append( library.Library(lib_id, signup_time, scanning_throughput, books_ids)) # for lib in libraries: # print lib.id, lib.signup_time, lib.scanning_throughput, lib.books_ids return task_setting.TaskSetting(books_count, libraries_count, days, libraries, books)
def add_new_book(): """Get info from user, add new book""" title_and_author = ui.get_new_book_info() new_book = book.Book(title_and_author[0], title_and_author[1]) datastore.add_book(new_book) ui.message('Book added: ' + new_book.get_title()) warn_if_previously_read(new_book.title)
def __init__(self): signal.signal(signal.SIGINT, self.on_sig_int) self.closing = False self.dev = None self.ep = None self.abook = book.Book() qr_img = "" #vid_dev = "/dev/video0" # Need to scan for this and make it work in windows? builder = gtk.Builder() self.gladefile = os.path.join(os.path.dirname(__file__),"ui/gui.glade") builder.add_from_file(self.gladefile) self.window = builder.get_object("window1") builder.connect_signals(self) self.text_view = builder.get_object("textview1") self.qr_img = builder.get_object("image1") self.button_scan = builder.get_object("button_scan") self.cur = None self.owner = getpass.getuser() # Assume the logged in person owns the book. try: self.db = MySQLdb.connect(user=db_user, host=db_host, db=db_base, passwd = db_pass); except: print (_("No database connection. Check config file")) self.db = False if self.db: self.cur = self.db.cursor() idVendor, idProduct = self.find_scanner() self.dev, self.ep = self.init_scanner(idVendor, idProduct ) self.window.show() if self.dev: self.button_scan.set_sensitive(False) gtk.gdk.threads_init() thread = threading.Thread(target=self.real_scanner) thread.setDaemon(True) thread.start() gtk.main()
def test_GetPages(self): """Tests that GetPages returns the correct page count when set or unset.""" little_women = book.Book("Little Women", ("Louisa", "May", "Alcott")) self.assertIsNone(little_women.GetPages()) little_women.SetPages(306) self.assertEqual(306, little_women.GetPages())
def process(self): log.info("Processing msg") if (self.msg.startswith('wiki')): summary = wiki.getSummery(self.msg[5:]) self.send(mtype='text', msg=summary) elif (self.msg.startswith('song')): sname = self.msg[5:] legel, rname = hello.giveTitle(sname) self.send(mtype='mtext', msg=rname) if (legel): spath = hello.giveMe(sname) self.send(mtype='audio', params=[spath]) elif (self.msg.startswith("book")): """n= 2 try: n= int(self.msg[5]) name= self.msg[7:] except Exception as e: n= 2""" name = self.msg[5:] bk = book.Book() bk.search(name) self.send(mtype='text', msg='Downloading books.\nPlease wait') urls = bk.process() for url in urls: self.send(mtype='doc', params=[url]) elif ("i love you" in self.msg): self.send(mtype='mtext', msg="`But I don't love you`") elif (self.msg.startswith("hello")): self.send(mtype='mtext', msg=c.HELP_MSG) else: self.send(mtype='text', msg='No match found') log.info('=' * 40 + '\n')
def setUp(self): """Use or delete this method.""" book1 = book.Book("Catcher in the Rye", ("J", "D", "Salinger")) book1.SetCoverType(book.CoverType.HARDCOVER) book1.SetPages(277) return (book1) pass
def on_button_clear_clicked(self, widget): ''' Clear all the edit boxes so A new book can be entered. ''' self.isbn.set_text('') self.author.set_text('') self.title.set_text('') textbuffer = self.abstract.get_buffer() textbuffer.set_text('') self.publisher.set_text('') self.city.set_text('') self.year.set_text('0') self.copies.set_text('') self.lent_select.set_active(0) #DEBUG(getpass.getuser()) self.book_owner.set_text(str( getpass.getuser())) # Assume the user is the book owner. # Create a new empty book import book self.orig_book = book.Book() self.mybook = copy.copy(self.orig_book) self.populate_borrowers() self.populate_locations() self.status.set_text( _("Everything cleared. Enter new book's details."))
def test_book_player_dead(self, mock_player, mock_page): b = book.Book() b.pages.append(mock_page) b.pages.append(mock_page) mock_player.dead.returnvalue = True b.play_book(mock_player, 0) mock_page.play.assert_not_called()
def getBook(self, bookUrl): url = _BASEURL + bookUrl b = book.Book(url, self.workDir) idx = b.current() if b.downloaded(): return print if idx == 0: idx += 1 r = self.getRequest(url) b.write(r.text) if b.isCorrupted(): sys.stdout.write('\r' + url + ' : url not found') sys.stdout.flush() return self.progress(b.heading(), 50, idx) while idx <= b.pages(): nextIdx = idx + 1 url = bookUrl url = _BASEURL + url[:-5] + '_' + str(nextIdx) + '.html' r = self.getRequest(url) b.write(r.text) self.progress(b.heading(), b.pages(), idx) idx = nextIdx
def test_book_player_dies_2nd_page(self, mock_player, mock_page): b = book.Book() b.pages.append(mock_page) b.pages.append(mock_page) mock_player.dead.side_effect = [False, True] b.play_book(mock_player, 0) mock_page.play.assert_called_with(mock_player) self.assertEqual(mock_page.play.call_count, 1)
def __init__(self, author_dict): for key, val in author_dict.items(): if key == 'books': book_list = [book.Book(book_dict) for book_dict in author_dict[key]['book']] self.__dict__[key] = book_list continue self.__dict__[key] = val
def clone(): potion_book = book.Book("leather book", __file__, "leather-bound tome", "This is an old leather-bound book titled \"Potion Recipes for the Beginning and Intermediate Sorcerer (First Edition).\"", pref_id="potion_book") potion_book.add_names("tome", "book") potion_book.add_adjectives("leather-bound", "leather") potion_book.set_message(''' ============================================================ |Potion Recipes for the Beginning and Intermediate Sorcerer| | | | (First Edition) | ============================================================ #* Spells Pg ================================== | Invisibility Potion 1 | | Pink Potion 2 | | Strength Potion 3 | ================================== #* Invisibility Potion =================== Step 1: > Gather thyself moss from a cave, water, truffles, a petal from a sunflower, and molasses. Step 2: > Put the ingredients in thy cauldron and put the cauldron over a burner. Step 3: > Drink thy potion, and turn thyself invisible. ** Beware: Thou will not be invisible forever! ** #* Pink Potion =========== Step 1: > Gather thyself water, molasses, and a seed from a poppy. Step 2: > Put the ingredients in a cauldron and put the cauldron over a burner. Step 3: > Drink thy potion, and turn thyself pink. ** Beware: Thou will not be pink for long! ** #* Strength Potion =============== Step 1: > Gather thyself moss from a cave, molasses, and a seed from a poppy Step 2: > Put the ingredients in thy cauldron and put the cauldron over a burner. Step3: > Drink thy potion, and make thyself stronger. ** Beware: Thou will not be stronger forever! ** ''') return potion_book
def __init__(self): self.borrowers = 0 builder = gtk.Builder() self.gladefile = os.path.join(os.path.dirname(__file__), "ui/edit_book.glade") builder.add_from_file(self.gladefile) builder.connect_signals(self) self.window = builder.get_object("window_edit") self.isbn = builder.get_object("entry1") self.author = builder.get_object("entry2") self.title = builder.get_object("entry3") self.publisher = builder.get_object("entry4") self.year = builder.get_object("entry5") self.city = builder.get_object("entry6") scrolled_window = builder.get_object("scrolledwindow1") self.abstract = builder.get_object("textview_abtract") self.mtype = builder.get_object("entry8") self.copies = builder.get_object("entry9") self.lent = builder.get_object("checkbutton1") self.lentlist = builder.get_object("liststore1") self.lent_select = builder.get_object("comboboxentry1") self.book_owner = builder.get_object("entry_owner") self.add_button = builder.get_object( "button_new_user") # Add a new user or edit self.rating_select = builder.get_object("combobox_rating") self.rating_liststore = builder.get_object("liststore_rating") self.rating_select.set_model(self.rating_liststore) self.where = "" self.add_date = False # builder.get_object("comboboxentry1") #To be added to GUI self.mybook = book.Book() self.orig_book = book.Book() self.status = builder.get_object("label_status") self.lent_date = builder.get_object("b_date") self.location_dropdown = builder.get_object("combobox_location") self.location_liststore = builder.get_object("liststore_locations") self.location_dropdown.set_model(self.location_liststore) self.location_dropdown.set_text_column(1) self.values_dropdown = builder.get_object("comboboxentry_value") self.values_liststore = builder.get_object("liststore_values") self.lent_select.set_model(self.lentlist) self.lent_select.set_text_column(1) self.o_date = ''
def test_SetPages(self): """Tests that SetPages raises an exception when attempting to set to a float value.""" war_and_peace = book.Book("War and Peace", ("Leo", "", "Tolstoy")) # Example uses a 'lambda' as a wrapper to catch the exception. self.assertRaises(ValueError, lambda: war_and_peace.SetPages(1000.5)) # Example uses a 'with' as a wrapper to catch the exception. with self.assertRaises(ValueError): war_and_peace.SetPages(1000.5)
def get_books(cursor): cursor.execute( "SELECT book_id, book_name, details, author FROM whatabook.book") result = cursor.fetchall() books = [] for item in result: books.append(book.Book(item[0], item[1], item[2], item[3])) return books
def test_AddBook_reduces_shelf_capacity(self): """Tests that shelf capacity is reduced after adding a book, so the available capacity should be less than the initial capacity after adding a book.""" test_shelf = shelf.Shelf() initial = test_shelf.GetInitialCapacity() warriors = book.Book("Warriors", ("Erin", "", "Hunter")) warriors.SetPages(20) warriors.SetCoverType(book.CoverType.HARDCOVER) test_shelf.AddBook(warriors) self.assertLess(test_shelf.GetAvailableCapacity(), initial)
def get_books_in_wish_list(cursor, user_id): cursor.execute("SELECT book.book_id, book_name, details, author \ FROM whatabook.book \ INNER JOIN whatabook.wishlist \ ON whatabook.book.book_id = whatabook.wishlist.book_id \ WHERE wishlist.user_id = {}".format(user_id)) result = cursor.fetchall() books = [] for item in result: books.append(book.Book(item[0], item[1], item[2], item[3])) return books
def _new(self): seq = self.book_number self.book_number += 1 new_book = book.Book(seq, self) new_book.new_empty() self.open_books[seq] = new_book index = self.editview_tabset.addTab(new_book.get_edit_view(), new_book.get_book_name()) self.editview_tabset.setTabToolTip( index, _TR('Tooltip of edit of new unsaved file', 'this file has not been saved')) self.focus_me(seq)
def get_books(self): for i in range(self.num_books): new_title = pyip.inputStr(f'What is the name of book {i + 1}: ') self.book_set.append(book.Book(new_title)) for i in range(len(self.book_set)): current_page = pyip.inputInt( f"What is the current page of {self.book_set[i].title}?: ", min=1) current_HW_page = pyip.inputInt( f"What is the current HW page of {self.book_set[i].title}?: ", min=1) self.book_set[i].current_page = current_page self.book_set[i].current_HW_page = current_HW_page
def test_RemoveBook_increases_shelf_capacity(self): """Tests that shelf capacity is increased after removing a book, so the available capacity should be greater after removing a book should from a shelf containing 1 book, which should also be equal to the initial capacity since there are no longer books on the shelf.""" test_shelf = shelf.Shelf() initial = test_shelf.GetInitialCapacity() warriors = book.Book("Warriors", ("Erin", "", "Hunter")) warriors.SetPages(20) warriors.SetCoverType(book.CoverType.HARDCOVER) test_shelf.AddBook(warriors) pass1 = test_shelf.GetAvailableCapacity() test_shelf.RemoveBook("Warriors") self.assertGreater(test_shelf.GetAvailableCapacity(), pass1) self.assertEqual(test_shelf.GetAvailableCapacity(), initial)
def send_data(): """ 입력 버튼의 이벤트. 여기서 유저 객체를 생성하고 값들을 집어넣을 것이다. :return: nothing """ # 유저 패키지에 있는 SignUp 클래스를 불러 데이터 전달. bookAdder = book.Book() flag = bookAdder.addBook(title.get(), writer.get(), price.get(), hyperLink.get(), isbn.get(), shortDetail.get()) if flag: messagebox.showerror('등록실패', '이미 존재하는 도서입니다. *동일한 isbn 존재') else: messagebox.showinfo('등록성공', '도서 등록에 성공하였습니다.')
def get_books_not_in_wish_list(cursor, user_id): #Query solution based on guidance from WhatABook requirements. cursor.execute("SELECT book_id, book_name, details, author \ FROM whatabook.book \ WHERE book_id NOT IN \ (SELECT book_id \ FROM whatabook.wishlist \ WHERE user_id = {})".format(user_id)) result = cursor.fetchall() books = [] for item in result: books.append(book.Book(item[0], item[1], item[2], item[3])) return books