Exemple #1
1
 def create(username):
     index = r.hgetall(SESSION_PREFIX + username)
     # 检查库存
     for k, v in index.items():
         stock = Book.get_stock(k)
         if int(stock) < int(v):
             return False
     r.rename(SESSION_PREFIX + username, ORDER_PREFIX + username)
     for k, v in index.items():
         stock = Book.get_stock(k)
         Book.set_stock(k, int(stock) - int(v))
     db.orders.insert({'username': username, 'books': index})
     return True
Exemple #2
0
    def by_title(self, title):
        """
        Search for a book on OpenLibrary by title

        @param title: the title to search for
        @return: the raw data of all results
        """
        title = title.replace(' ', '+').lower()
        url = urllib.request.urlopen(self.search_url+'title='+title)
        data = simplejson.load(url)['docs']

        for result in data:
            book = Book(0)
            book.title = result['title']
            try:
                book.authors = ', '.join(result['author_name']) if isinstance(result['publisher'], list) else result['author_name']
            except KeyError:
                book.authors = "None"
            try:
                book.publisher = ', '.join(result['publisher']) if isinstance(result['publisher'], list) else result['publisher']
            except KeyError:
                book.publisher = "No publisher found."
            try:
                book.publ_year = result['first_publish_year']
            except KeyError:
                book.publ_year = 0
            try:
                book.description = ''.join(result['first_sentence'])
            except KeyError:
                book.description = "No description found."

            yield book
Exemple #3
0
def delete_book():
    to_do = input('''We're going to delete a book.  Do you have the barcode? [y/N]: ''')
    if to_do.strip() == "" or to_do.strip().lower() == "n":
        results = search()
        i = 1
        for item in results:
            print((i + ") " + item))  # not sure how this will come out.
        del_me = input("Which one is it? ")

        del_me = int(del_me)

        del_me = results[del_me - 1]
        del_me = del_me.split(",")
        del_me = Book(del_me[0])  # this is really fudged atm.  serious testing needed
        the_db = Bdb(dbLocation)
        the_db.delete(del_me)
        print("Deleted.")

    elif to_do.strip().lower() == "y":
        del_me = input("Ok, enter it now: ")
        if del_me.strip() == "":
            print("Invalid input.")
        else:
            del_me = int(del_me)
            del_me = Book(del_me)
            the_db = Bdb(dbLocation)
            the_db.delete(del_me)
            print("Deleted.")
 def test_decrease_number_of_copies(self):
     book = Book("Lords", "Steven Moore", 2000, "Thriller", 2, 15)
     book.decrease_number_of_copies(10)
     self.assertEqual(5, book.number_of_copies)
     book.decrease_number_of_copies(6)
     self.assertNotEqual(-1, book.number_of_copies)
     self.assertEqual(0, book.number_of_copies)
Exemple #5
0
class Tractatus:
    # This is the book
    tractatus = None

    def __init__(self):
        """ Construct the Tractatus """

        # Build the Book object
        self.tractatus = Book()

        # Get the tractatus from text
        SITE_ROOT = os.path.realpath(os.path.dirname(__file__))
        all_text = open(os.path.join(SITE_ROOT, "static", "tractatus.txt"), 'r')
        output = all_text.readlines()

        # Read the file line by line into self.tractatus
        # The actual content only begins at line 30 until the end
        for i in range(30, len(output)):
            complete_string = str(output[i])

            # We need to separate the index and the text
            split_string = complete_string.partition(" ")
            index = split_string[0]
            text = split_string[2].rstrip("\n")

            # Load them in
            self.tractatus.add_section(index, text)

        # print self.tractatus

    def get_book(self):
        return self.tractatus
 def test_increase_number_of_copies(self):
     book = Book("Lords", "Steven Moore", 2000, "Thriller", 2, 0)
     book.increase_number_of_copies(10)
     self.assertEqual(10, book.number_of_copies)
     book.increase_number_of_copies(5)
     self.assertNotEqual(10, book.number_of_copies)
     self.assertEqual(15, book.number_of_copies)
def test_read_book():
    book = Book('test/test_text_file.txt')
    book.read_book()
    chapters = book.get_chapters
    assert len(chapters) == 2
    assert chapters[0].get('title') == 'Chapter 1'
    sentences = chapters[0].get('sentences')
    assert len(sentences) == 4
  def add_book(self, b_name, b_quantity):

    b = Book(name= b_name, quantity= int(b_quantity))

    urllib.unquote(b.name)

    self.response.write("> Voce cadastrou o livro: " + b.name  + " com "+ str(b.quantity))

    b.put()
Exemple #9
0
def parse_all_books():
    for file in glob.glob("{}/*.txt".format(book_dir)):
        print("Parsing... {}".format(file))
        book = Book(file)
        book.read_book()
        book.count_distinct_words()
        print(book)

        all_books.append(book)
Exemple #10
0
 def delete(self, conn):
     for row in self.select(conn):
         book = Book(
             row['id'],
             row['title'],
             None,
             row['published_in'],
         )
         book.delete(conn)
         print("")
Exemple #11
0
 def read_book(self, bookname, read_what=None):
     if self.suffix == "":
         print bookname
         filename = self.dir + "/" + bookname
     else:
         print bookname + "." + self.suffix
         filename = self.dir + "/" + bookname + "." + self.suffix
     book = Book(filename)
     self.books.append(book)
     self.current_monad = book.read_linear(self.current_monad) + 1
def update_location(id):
    book = Book(id)

    if 'update_person' in request.form:
        new_location = request.form['location']
    else:
        new_location = request.form['shelf']
    book.update_location(new_location)

    return render_book_info(book)
def run():
    mbook = Book.parse(get_mtgox())
    bbook = Book.parse(bitfloor.book(level=2))

    mbook.flatten('0.01')

    our_book, our_book2 = get_our_book()

    # remove our stuff from bbook
    # bbook will have the orders we don't control
    bbook.subtract(our_book2)

    # mbook will now have the gap needed to be filled by our orders
    mbook.subtract(bbook)

    funds = get_funds()

    # get the total remaining area needed to fill
    # find which factor of it we can fill with our total funds
    sumb = sum(o.price*o.size for o in mbook.bids if o.size > 0)*D('1.04')
    bfactor = min(1, funds['USD']/sumb) if sumb > 0 else 1
    suma = sum(o.size for o in mbook.asks if o.size > 0)
    afactor = min(1, funds['BTC']/suma) if suma > 0 else 1

    print afactor, bfactor
    print suma, sumb

    # multiply everything positive by the factor
    # mbook will now have what we need to provide to bitfloor's book
    for o in mbook.bids:
        if o.size > 0:
            o.size *= bfactor
            o.size = o.size.quantize(D('0.00000001'), rounding=decimal.ROUND_DOWN)
    for o in mbook.asks:
        if o.size > 0:
            o.size *= afactor
            o.size = o.size.quantize(D('0.00000001'), rounding=decimal.ROUND_DOWN)

    # now, get the difference between what we need to provide and what we have
    mbook.subtract(our_book2)

    # cancel orders first which are above the gap
    cancel(mbook, our_book, 'bid')
    cancel(mbook, our_book, 'ask')

    # send in orders to fill the gaps
    for o in mbook.bids:
        if o.size > SIZE_LIMIT:
            print 'bid', o
            bitfloor.buy(size=str(o.size), price=str(o.price))
    for o in mbook.asks:
        if o.size > SIZE_LIMIT:
            print 'ask', o
            bitfloor.sell(size=str(o.size), price=str(o.price))
Exemple #14
0
    def _make_book(self, cell, year):
        bookID, title, originalTitle = self._extract_titles(cell)

        book = Book(bookID, title, originalTitle, year)

        alt = filter(alt_text, cell)
        if alt:
            assert len(alt) == 1
            #noinspection PyUnresolvedReferences
            book.addTitles(*[x.strip() for x in re.split('\s*;\s+', alt[0].text.strip()[3:-1])])

        return book
Exemple #15
0
 def update(self, conn, field, new_value):
     for row in self.select(conn):
         author_name = Authors(['name', '=', row[2]]).select(conn).fetchone()[1]
         if field == "name":
             author_name = new_value
         book = Book(
             row['id'],
             row['title'],
             author_name,
             row['published_in'],
         )
         setattr(book, field, new_value)
         book.save(conn)
def process_json(json_request):
    books = json_request['Books']
    book_id_list = []
    for book in books:
        user_book_dict[book[u'ID']] = Book(book[u'ID'],
                                           book[u'Title'],
                                           book[u'Description'],
                                           book[u'Image'],
                                           book[u'isbn'])
        if u'Subtitle' in book:
            user_book_dict[book[u'ID']].subtitle = book[u'Subtitle']
        book_id_list.append(book[u'ID'])

    return book_id_list
Exemple #17
0
def create_book_from_dict(book_dict):
    book = Book(book_dict["bc"], book_dict["isbn"], book_dict["title"],
                book_dict["authors"], book_dict["pages"],
                book_dict["publ_year"], book_dict["publisher"],
                book_dict["location"], book_dict["description"],
                book_dict["call_num"], book_dict["tags"])
    return book
def uploadtextbook():
    if session.get('user') is not None:
        username = decode(session['user']).userid
        email = decode(session['user']).email
    else:
        username = None
        email = None
        return redirect(url_for('login'))

    error = None
    if request.method == 'POST':
        title = request.form['title']
        author = request.form['author']
        subject = request.form['subject']
        course = request.form['course']
        condition = request.form['condition']
        price = request.form['price']

        boolError = isValidUpload(title, author, subject, course, condition,
                                  price)
        if boolError[0]:
            app.logger.debug('valid upload info')
            book = Book(title, author, subject, course, condition, price,
                        username, email)
            dao = BookDao()
            dao.insert(book)
            return findtextbooks()
        else:
            error = boolError[1]

    app.logger.debug('error %r', error)

    return render_template('uploadtextbook.html', **locals())
def get_our_book():
    orders = bitfloor.orders()

    our_book = {
        'bids': {},
        'asks': {}
    }

    our_book2 = {
        'bids': [],
        'asks': []
    }

    for o in orders:
        size = Decimal(str(o['size']))
        price = Decimal(str(o['price']))
        order = Order(size, price)
        order.id = o['order_id'] # TODO: hacky
        tup = (str(price), str(size))
        if o['side'] == 0:
            our_book['bids'].setdefault(price, []).append(order)
            our_book2['bids'].append(tup)
        elif o['side'] == 1:
            our_book['asks'].setdefault(price, []).append(order)
            our_book2['asks'].append(tup)

    return our_book, Book.parse(our_book2)
Exemple #20
0
def reading_file(name, books, libraries):
    #print("Reading file")
    mon_fichier = open(name, "r")
    content = mon_fichier.readlines()
    nb_books = content[0].split(" ")[0]
    nb_libraries = content[0].split(" ")[1]
    nb_days_scanning = content[0].split(" ")[2]

    for idx, livre in enumerate(content[1].split(" ")):
        new_book = Book(idx, int(livre))
        books.append(new_book)

    for idx, library in enumerate(content[2:]):
        if len(library) > 2:
            #print(idx, library)
            if idx % 2 == 0:
                new_library = Library(int(idx / 2), [],
                                      int(library.split(" ")[1]),
                                      int(library.split(" ")[2]))
                libraries.append(new_library)
            else:
                libraries[-1].books = []
                temp_list_livres = library.split(" ")
                for num in temp_list_livres:
                    num = int(num)
                    libraries[-1].books.append(books[num])
        #time.sleep(0.01)

    mon_fichier.close()
    return int(nb_days_scanning)
Exemple #21
0
 def get_books(self, query=None, genre=None, year=None, p=None):
     books = []
     offset = (int(p) - 1) * 12 if (int(p) > 0 and p) else 0
     with dbapi2.connect(self.db_url) as connection:
         cursor = connection.cursor()
         if query:
             query1 = "SELECT ID, TITLE, YR, COVER FROM BOOK WHERE LOWER(TITLE) LIKE LOWER(%s) ORDER BY ID OFFSET %s LIMIT 12"
             query_words = query.split()
             like_pattern = '%'
             for word in query_words:
                 like_pattern += '{}%'.format(word)
             cursor.execute(query1, (like_pattern, offset))
         elif genre:
             query1 = "SELECT BOOK.ID, BOOK.TITLE, BOOK.YR, BOOK.COVER FROM BOOK INNER JOIN GENRES ON BOOK.ID = GENRES.BOOKID WHERE (GENRE = %s) GROUP BY BOOK.ID, BOOK.TITLE, BOOK.YR, BOOK.COVER ORDER BY BOOK.ID OFFSET %s LIMIT 12"
             cursor.execute(query1, (genre, offset))
         elif year:
             query1 = "SELECT ID, TITLE, YR, COVER FROM BOOK WHERE (YR = %s) ORDER BY ID OFFSET %s LIMIT 12"
             cursor.execute(query1, (year, offset))
         else:
             query1 = "SELECT ID, TITLE, YR, COVER FROM BOOK ORDER BY ID OFFSET %s LIMIT 12"
             cursor.execute(query1, (offset, ))
         for book_id, title, year, cover in cursor:
             books.append(
                 Book(id=book_id, title=title, year=year, cover=cover))
     return books
def create_book_list():
    book_list = []
    for i in range(0, 10):
        book_list.append(Book())

    with open('resources/book_list', 'wb') as fp:
        pickle.dump(book_list, fp)
Exemple #23
0
class BookTest(unittest.TestCase):
	mozzarella = Recipe('mozzarella_sticks', 3, 20, ['mozzarella', 'sticks'], "", "starter")
	nugget = Recipe('nugget', 4, 65, ['chicken', 'bread'], "", "starter")
	omelette = Recipe('omelette au fromage', 2, 10, ['eggs', 'cheese', 'pepper'], "", "lunch")
	fondant = Recipe('fondant', 4, 30, ['eggs', 'chocolate', 'butter'], "", "dessert")
	creation = datetime.datetime(2019, 4, 13, 00, 00, 00)
	last = datetime.datetime(2019, 5, 27, 00, 00, 00)
	recipe_list = {
		'starter': {
			mozzarella,
			nugget,
		},
		'lunch': {
			omelette,
		},
		'dessert': {
			fondant,
		}
	}
	test_book = Book("Text Book", last, creation, recipe_list)

	def test_get_recipe_by_type_method(self):
		gibberish_type = "blabla"
		integer_type = 123

		with self.assertRaises(SystemExit):
			self.test_book.get_recipes_by_type(gibberish_type)
			self.test_book.get_recipes_by_type(integer_type)

	def test_get_recipe_by_name_method(self):
		non_existing_name = "blabla"
		int_name = 123
		empty_name = ""

		with self.assertRaises(SystemExit):
			self.test_book.get_recipes_by_type(non_existing_name)
			self.test_book.get_recipes_by_type(int_name)
			self.test_book.get_recipes_by_type(empty_name)

	def test_add_recipe_method(self):
		non_recipe_object = "blabla"

		with self.assertRaises(SystemExit):
			self.test_book.add_recipe(non_recipe_object)

	def test_add_recipe_does_the_adding(self):
		recipe_to_add = Recipe('pasta', 1, 9, ['pasta', 'water'], "", 'lunch')
		self.test_book.add_recipe(recipe_to_add)
		type_of_added_recipe = recipe_to_add.recipe_type

		self.assertIn(recipe_to_add, self.test_book.recipes_list[type_of_added_recipe])

	def test_add_recipe_method_update_time(self):
		recipe_to_add = Recipe('cheesecake', 5, 45, ['cheese', 'cake'], "", 'dessert')
		last_update1 = self.test_book.last_update
		self.test_book.add_recipe(recipe_to_add)
		self.test_book.print_content_recipe_list()
		last_update2 = self.test_book.last_update

		self.assertNotEqual(last_update1, last_update2)
    def create_item():
        """
        Creates an item.
        :return: an item
        """
        print(
            "What kind of items would you like to add to the library catalogue?"
        )
        print("1. Book")
        print("2. DVD")
        print("3. Journal")

        option = int(input("Select type of item: "))

        title = input("Enter title: ")
        call_num = input("Enter call number: ")
        author = input("Enter author name: ")
        num_copies = input("Enter the number of copies: ")

        if option == 1:
            return Book(call_num, title, num_copies, author)

        if option == 2:
            release_date = input("Enter release date: ")
            region_code = input("Enter region code: ")
            return Dvd(call_num, title, num_copies, author, release_date,
                       region_code)

        if option == 3:
            names = input("Enter name: ")
            issue_number = input("Enter issue number: ")
            publisher = input("Enter publisher: ")
            return Journal(call_num, title, num_copies, author, names,
                           issue_number, publisher)
Exemple #25
0
def get_book(file_path):
    xmldoc = minidom.parse(file_path)
    itemlist = xmldoc.getElementsByTagName('section')
    book_name = xmldoc.getElementsByTagName(
        'book-title')[0].firstChild.nodeValue
    logging.info('Book name is:' + book_name)
    text = get_text(itemlist)
    words = text.split()
    count_p = xmldoc.getElementsByTagName('p').length
    count_words = len(words)
    count_letters = len(text)
    words_with_capital_letter = 0
    words_without_capital_letter = 0
    for word in words:
        if word.istitle():
            words_with_capital_letter += 1
        else:
            words_without_capital_letter += 1

    return Book(book_name, count_p, count_words, count_letters,
                words_with_capital_letter, words_without_capital_letter)
    logging.info('Count of words in lowercase is: ' +
                 str(words_without_capital_letter))
    logging.info('Count of words with capital letter is:' +
                 str(words_with_capital_letter))
    def register_book(self):

        system('cls')

        ISBN = input("Enter the ISB of book: ")
        pos = self.find_ISBN(ISBN)

        if pos == -1:
            title = input("Enter the title of book: ")
            author = input("Enter the author of book: ")
            pages = int(input("Enter the pages of book: "))
            edition = input("Enter the edition of book: ")
            publisher = input("Enter the publisher of book: ")
            place = input("Enter the place of book: ")
            date_edition = self.__order_date_book()

            new_book = Book(title, author, ISBN, pages, edition, publisher,
                            place, date_edition)
            self.books.append(new_book)

            system('cls')
            print("The book was save successful !!")

        else:
            print("ERROR - The book already exists")

        input()
    def addBook(self, author, country, imageLink, language, link, pages, title, year):


        """
        books리스트에 Book클래스로 추가하고 bookset.json에 추가로 저장할것
        :param author:
        :param country:
        :param imageLink:
        :param language:
        :param link:
        :param pages:
        :param title:
        :param year:
        :return:
        """
        self.books.append(Book(author, country, imageLink, language, link, pages, title, year))
        json_data = []
        obj = {"author": author, "country": country, "imageLink": imageLink, "language": language, "link": link,
               "pages": pages, "title": title, "year": year}

        with open('bookset.json') as f:
            json_data = json.load(f)
        json_data.append(obj)

        with open('bookset.json', 'w') as f:
            json.dump(json_data, f)
        print(f'성공적으로 책제목: {obj["title"]}을 저장하였습니다.')
Exemple #28
0
def makeBook(**params):
    name = params['name']
    extraData = params['extraData']
    author = params['author']
    public = params['public']
    content = params['content']
    img_url = params['img_url']
    db_num = params['db_num']
    card = Card()
    card.set('name', name)
    card.set('author', author)
    card.set('content', content)
    card.set('img_url', img_url)
    card.set('extraData', json.loads(extraData))
    card.set('db_num', db_num)
    if 'formId' in params:
        formId = params['formId']
        card.set('formId', formId)
    userid = params['userid']
    user = User.create_without_data(userid)
    card.set('user', user)
    card.set('user', user)
    card.set('type', 'book')
    card.set('public', public)
    card.set('publish', False)
    card.set('likes', 0)
    card.set('shares', 0)
    card.save()
    stat = Book.generate(card)
    if stat == 'ok':
        result = {'code': 200, 'data': card.get('objectId')}
        return result
    else:
        result = {'code': 500, 'message': 'failed'}
        return result
Exemple #29
0
def api_update_book(id):
    data = Library.str_to_json(flask.request.json)
    library = load_library()
    book = library.get_book(id)
    if not book:
        flask.abort(404)
    if not data or not valid_post_put(data, post=False):
        flask.abort(400)
    old_book_data = book.to_dict()
    updated_book = Book(
        id,
        **dict(
            (k, data.get(k, old_book_data[k])) for k in Book.DEFAULTS.keys()))
    library.update_book(id, updated_book)
    library.save()
    return flask.jsonify({'book': updated_book.to_dict()})
def parse_input(file):
    B = 0
    L = 0
    D = 0
    libraries = []
    books = []

    with open("input/" + file, "r") as input:
        lines = input.readlines()
        [B, L, D] = [int(i) for i in lines[0].split(" ")]
        book_scores = [int(i) for i in lines[1].split(" ")]

        for idx, score in enumerate(book_scores):
            books.append(Book(score, idx))

        lines = lines[2:]
        for idx, line in enumerate(lines):

            if line == "\n":
                break

            if idx % 2 == 0:
                libraries.append(
                    Library(lines[idx], lines[idx + 1], idx // 2, books))

    return Problem(B, L, D, books, libraries)
Exemple #31
0
def fare():
    try:
        if request.method == "GET":
            '''
            jwt_token               = request.headers["token"]
            stat, tok               = Authorize.verify_jwt(jwt_token)
            if stat == 0:
                raise ValueError("Not authorized")
            if len(tok) > 0:
                logging.critical("failure in v1/fare with token expired: ")
                return token_expiry_error
            '''
            user_number = request.args["number"]
            from_latitude = request.args["fromLatitude"]
            from_longitude = request.args["fromLongitude"]
            to_latitude = request.args["toLatitude"]
            to_longitude = request.args["toLongitude"]
            response = Book.get_fare(from_longitude, from_latitude,
                                     to_longitude, to_latitude)
            response = json.dumps(response)
            with app.app_context():
                response = make_response(response)
            return response
    except RuntimeError as e:
        logging.critical("failure in v1/fare with error: " + str(e))
        return default_error
Exemple #32
0
 def add_book(self, book = Book()):
     """
     This method appends a book to the booklists
     :param book: book is an instance of the Class "Book"
     :return: None
     """
     self.booklists.append(book)
Exemple #33
0
 def adding_book(self, this_author, appInfo):
     if self.lineEdit_4.text():
         if self.lineEdit.text():
             book = self.lineEdit_4.text()
             self.lineEdit_4.setText("")
             if book not in this_author.book_list:
                 this_author.book_list.append(book)
             this_book = Book(book, self.lineEdit.text())
             if this_book not in appInfo.library.book_list:
                 appInfo.library.add_book_object(this_book)
                 appInfo.books_database.insert_one({
                     "name":
                     this_book.name,
                     "author":
                     this_book.author,
                     "year":
                     this_book.year,
                     "description":
                     this_book.description,
                     "tags":
                     this_book.tag_list,
                     "genres":
                     this_book.genre_list
                 })
                 message = CreateABook(appInfo, this_book)
                 message.exec_()
         else:
             message = ErrorDialog()
             message.label_2.setText("Enter a name first.")
             message.exec_()
     self.update_tables(this_author)
 def test_constructor_vacio(self):
     book = Book()
     self.assertDictEqual(book.__dict__, {
         '_name': '',
         '_authorName': '',
         '_memberLegajo': ''
     })
Exemple #35
0
    def generate_item(call_num):
        user_input = None
        # If entered invalid option, loops user back to choices below
        while user_input != 4:
            print("What type of item would you like to add")
            print("1. Book")
            print("2. DVD")
            print("3. Journal")
            print("4. Back")
            string_input = input("Please enter your choice (1-4)")
            user_input = int(string_input)
            title = input("Enter title: ")
            num_copies = int(input("Enter number of copies (positive number): "))
            item_data = (call_num, title, num_copies)

            # creates the item object of input choice
            if user_input == 1:
                author = input("Enter Author Name: ")
                return Book(item_data[0], item_data[1], item_data[2], author)
            if user_input == 2:
                release_date = input("Enter release date (yyyy/mm/dd): ")
                code = input("Enter region code: ")
                return DVD(item_data[0], item_data[1], item_data[2], release_date, code)
            if user_input == 3:
                names = input("Enter names")
                issue_number = input("Please enter issue number")
                publisher = input("Enter publisher")
                return Journal(item_data[0], item_data[1], item_data[2], names, issue_number, publisher)
            # return to menu
            if user_input == 4:
                pass
Exemple #36
0
def get_new_book_info():

    ''' Get title and author of new book from user '''

    title = input('Enter title: ')
    author = input('Enter author: ')
    return Book(title, author)
Exemple #37
0
 def get_book(self, book_id):
     with dbapi2.connect(self.db_url) as connection:
         cursor = connection.cursor()
         query1 = "SELECT TITLE, AUTHORID, YR, PGNUM, COVER, DESCRIPTION FROM BOOK WHERE (ID = %s)"
         cursor.execute(query1, (book_id, ))
         title, author_id, year, pageNumber, cover, description = cursor.fetchone(
         )
         author = None
         if author_id:
             query2 = "SELECT NAME FROM AUTHOR WHERE (ID = %s)"
             cursor.execute(query2, (author_id, ))
             author = cursor.fetchone()[0]
         query3 = "SELECT AVG(SCORE) FROM REVIEW WHERE (BOOKID = %s)"
         cursor.execute(query3, (book_id, ))
         avgscore = cursor.fetchone()[0]
         genres = self.get_genres(book_id)
     book_ = Book(id=book_id,
                  title=title,
                  author=author,
                  year=year,
                  genres=genres,
                  pageNumber=pageNumber,
                  cover=cover,
                  description=description,
                  avgscore=avgscore)
     return book_, author_id
Exemple #38
0
def get_books(**kwargs):
    ''' Return books from DB. With no arguments, returns everything. '''

    sql = None

    books = []

    if kwargs == None:
        sql = 'SELECT * FROM {}'.format(BOOK_TABLE)

    if kwargs['read'] == True:
        sql = 'SELECT * FROM {} WHERE {} = 1'.format(BOOK_TABLE, READ)

    if kwargs['read'] == False:
        sql = 'SELECT * FROM {} WHERE {} = 0'.format(BOOK_TABLE, READ)

    if sql:

        conn = sqlite3.connect(DB_NAME)
        conn.row_factory = sqlite3.Row  # This type of row can be accessed by column name
        cur = conn.cursor()
        rows = cur.execute(sql)

        for row in rows:
            read_bool = tf_val(row[3])
            book = Book(row[TITLE], row[AUTHOR], read_bool, row[ID])
            books.append(book)

        conn.close()

    return books
    def insert_book(self):
        if (not self.title_input.text or not self.author_input.text
                or not self.length_input.text):
            self.parent.book_list_panel.status_bar_text = \
                'All fields must be completed!'
            return

        try:
            length = int(self.length_input.text)
        except Exception as e:
            print(e)
            self.parent.book_list_panel.status_bar_text = \
                'Please enter a valid number!'
            return

        if length <= 0:
            self.parent.book_list_panel.status_bar_text = \
                'Pages must be a positive integer!'
            return

        book = Book(self.title_input.text, self.author_input.text, length,
                    False)

        self.parent.book_list_panel.book_list.add(book)
        self.parent.book_list_panel.book_list.save()
        self.parent.book_list_panel.refresh_books(False)

        self.parent.book_list_panel.status_bar_text = \
            'Book added successfully!'
Exemple #40
0
    def findBook(self, title):
        for b in self.books:
            for t in filter(None, chain([b.title], b.alternative)):
                if Book.compareTitle(t, title):
                    return b

        return None
Exemple #41
0
def make_book_list(string_from_file):
    """ turn the string from the file into a list of Book objects"""

    global book_list

    if len(string_from_file) > 0:
        book_json = json.loads(string_from_file)

        for book in book_json:
            if 'stars_str' in book:
                stars_str = book["stars_str"]
            else:
                stars_str = ""
            if 'date' in book:
                date = book["date"]
            else:
                date = ""
            book_list.append(
                Book(title=book["title"],
                     author=book["author"],
                     read=bool(book["read"]),
                     id=int(book["id"]),
                     date=date,
                     stars=int(book["stars"]),
                     stars_str=stars_str))
Exemple #42
0
    def bookFromUrl(url):
        try:
            # Request data from CEO Library
            # set headers
            headers = {
                "User-Agent":
                "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.89 Safari/537.36"
            }
            req = requests.get(url, headers=headers)
            req.raise_for_status()
            soup = bs4.BeautifulSoup(req.text, "html.parser")
            # get cover
            cover_url = getCoverUrl(soup, 'book-cover-actions')
            # get title
            title = getTitle(soup, "book-info-intro")
            # get authors
            authors = getAuthors(soup, "book-info-intro")
            # get isbn and rating
            #isbn, rating = getISBNRating(soup, "buy-book")
            #rating = goodReadsSearchForBookRating(title, authors[0])
            info = getInfo(soup, "amazon-book-description")
            book = Book(title, authors, info, cover_url, "NA", 0)
            return book

        except Exception as e:
            print(e)
    def __init__(self, conn_details, status_light):
        """Setup a connection to MPD to be able to play audio.
        
        Also update the MPD database with any new MP3 files that may have been added
        and clear any existing playlists.
        """
        self.status_light = status_light
        self.book = Book()

        self.mpd_client = LockableMPDClient()
        with self.mpd_client:
            self.mpd_client.connect(**conn_details)

            self.mpd_client.update()
            self.mpd_client.clear()
            self.mpd_client.setvol(100)
Exemple #44
0
def read_input_file(filename: str) -> File:
    """Reads the data of input problem

    returns:
    D: number of days,
    LIBS: list of Library objects,
    BOOKS: list of Book objects,
    """
    lines = list(
        map(lambda x: [int(y) for y in x.strip().split()],
            open(filename).readlines()))
    book_count, libs_count, days = lines[0]
    books = []
    for idx, score in enumerate(lines[1]):
        books.append(Book(idx, score))
    assert len(books) == len(lines[1])

    libraries = []
    for i in range(2, len(lines), 2):
        if len(lines[i]) == 0:
            continue
        num_books, signup_delay, books_per_day = lines[i]

        lib_books = list(map(lambda x: books[x], lines[i + 1]))
        assert len(lib_books) == num_books, f"Incorrect parsing of {line[i]}"
        libraries.append(
            Library((i - 2) // 2, signup_delay, lib_books, books_per_day))

    return File(books, libraries, days)
Exemple #45
0
    def pull_book_json(self, book_number):
        with open(self.file_name, "r") as read_file:
            data = json.load(read_file)
            data = data[self.name][str(book_number)]
            loaded_book = Book(len(data['page']) - 5, book_number)
            for idi, i in enumerate(data['page']):
                loaded_book.content[idi].data = eval(i)
            loaded_book.book_indirection_flag = data['i_flag']
            loaded_book.tps = data['tps']

            for i in range(512):
                if loaded_book.content[1].read_no_index_check(i) != 0:
                    for page in loaded_book.content:
                        page.num_records += 1

            return loaded_book
 def list_req(self):
     """
     This function is to giving information about the required books and it will be displayed as button on the BoxLayout
     :return: none
     """
     self.root.ids.box_display.clear_widgets()
     for each in self.data_list.printed_the_books("r"):
         temp_book = Book(each)
         temp_click = Button(text=each[0])
         temp_click.bind(on_release=self.mark_as_completed)
         temp_click.background_color = temp_book.get_the_color()
         self.root.ids.box_display.add_widget(temp_click)
     pages = self.data_list.get_the_number_of_page("r")
     self.count_the_page = "Total pages to read: {}".format(pages)
     self.root.ids.req_book.state = 'down'
     self.root.ids.comp_book.state = 'normal'
 def edit_book(self, name, author=None, year=0, description=None):
     this_book = Book(name, author, year, description)
     if this_book not in self._book_list:
         return False
     self.delete_book(this_book.name)
     self._book_list.append(this_book)
     return True
 def add_record(self, book):
     """
         Adds a new record of a book to the file.If there is a book record
         with the same title,author and year of publication then the book
         is recorded and we only change the number of copies of the
         recorded book.Otherwise, we add the new book.
     """
     with open(self.file, 'r') as file:
         data = file.readlines()
     try:
         _file = self.file
         enum = enumerate(data)
         I = next(i for i, v in enum if Book.book_by_record(v) == book)
         os.rename(os.path.realpath(_file), os.path.realpath(_file)+".bak")
         copies = int(data[I].rstrip('\n').split('+')[-1])
         book_update = book.special_record().rstrip('\n').split('+')
         book_update[-1] = str(int(book_update[-1]) + copies)
         data[I] = '+'.join(book_update) + '\n'
         with open(_file, 'w') as file:
             file.writelines(data)
         os.remove(os.path.realpath(self.file)+".bak")
     except StopIteration:
         data.append(book.special_record())
         with open(self.file, 'a') as file:
             file.write(book.special_record())
Exemple #49
0
    def __init__(self, conn_details, status_light):

        """Setup a connection to MPD to be able to play audio.
        Also update the MPD database with any new MP3 files that may have been added
        and clear any existing playlists.
        """
        self.status_light = status_light
        self.book = Book()
        self.book_titles = []

        self.index_lock = RLock()
        self.current_index = -1

        self.mpd_client = LockableMPDClient()
        with self.mpd_client:
            self.mpd_client.connect(**conn_details)

            self.mpd_client.update()
            self.mpd_client.clear()
            self.mpd_client.setvol(100)

            files = self.mpd_client.search("filename", ".mp3")
            if not files:
                self.status_light.interrupt("blink_fast", 3)
            else:
                for file in files:
                    book_title = os.path.dirname(file["file"]) + "/"
                    if book_title not in self.book_titles:
                        self.book_titles.append(book_title)
def get_our_book():
    orders = bitfloor.orders()

    our_book = {
        'bids': {},
        'asks': {}
    }

    our_book2 = {
        'bids': [],
        'asks': []
    }

    for o in orders:
        size = D(str(o['size']))
        price = D(str(o['price']))
        order = Order(size, price)
        order.id = o['order_id'] # TODO: hacky
        tup = (str(price), str(size))
        if o['side'] == 0:
            our_book['bids'].setdefault(price, []).append(order)
            our_book2['bids'].append(tup)
        elif o['side'] == 1:
            our_book['asks'].setdefault(price, []).append(order)
            our_book2['asks'].append(tup)

    return our_book, Book.parse(our_book2)
 def test_book_by_record(self):
     book = Book.book_by_record("Fall+Carl Jon+1999+Crime+3+2")
     self.assertEqual(
         "<Book Information>\nTitle:Fall\nAuthor:Carl "
         + "Jon\nPublished in:1999\nGenre:Crime\n"
         + "Rating:3.0\nNumber of copies:2\n",
         str(book),
     )
Exemple #52
0
 def entirebook(self,ordergrouping=1):
 #Open orders book with bids and asks
     url = "order_book/"
     params = {"group":ordergrouping}    #group orders with the same price (0 - false; 1 - true). Default: 1
     orderbook = self.get(url,params) 
     from book import Book
     entirebook = Book.parse(orderbook)
     entirebook.sort()
     return entirebook       #Returns a sorted Book class object,containing entirebook.bids and entirebook.asks
Exemple #53
0
class TestPlayerOneLogic(unittest.TestCase):
    ''' Unittests for the logic patterns if the book is the first player
    '''
    def setUp(self):
        self.grid = Grid()
        self.book = Book('X')
        
    def run_game(self, moves):
        '''Actually runs the game until someone wins, or there are no more squares available
        '''
        while not self.grid.test_win() and self.grid.get_available():
            self.grid = self.book.check_grid(self.grid)
            try:
                self.grid = self.grid.fill_square(user='******', square=moves.pop())
            except:
                break
            
        
    def test_first_center_corner(self):
        ''' Game for the second player taking the center, then a corner
        '''
        moves = ['5', '7', '2']
        moves.reverse() # reversing so I can pop them off
        self.run_game(moves)
        self.assertEquals(self.grid.test_win(), 'X')
        
    def test_first_center_edge(self):
        ''' Game for the second player taking the center, then an edge
        '''
        moves = ['5', '8', '3', '4']
        moves.reverse()
        self.run_game(moves)
        self.assertFalse(self.grid.get_available())
        
    def test_first_corner(self):
        ''' Game for the second player taking a corner
        '''
        moves = ['3', '5', '4']
        moves.reverse()
        self.run_game(moves)
        self.assertEquals(self.grid.test_win(), 'X')
    
    def test_first_edge_nothreat(self):
        ''' Game where the second player takes an edge, followed by a non-threat move
        '''
        moves = ['4', '9', '7']
        moves.reverse()
        self.run_game(moves)
        self.assertEquals(self.grid.test_win(), 'X')
        
    def test_first_edge_threat(self):
        ''' Game where the second player takes an edge, followed by a threat
        '''
        moves = ['6', '9', '7']
        moves.reverse()
        self.run_game(moves)
        self.assertEquals(self.grid.test_win(), 'X')
Exemple #54
0
    def __init__(self, conn_details, status_light):
        """Setup a connection to MPD to be able to play audio.

        Also update the MPD database with any new MP3 files that may have been added
        and clear any existing playlists.
        """
        self.status_light = status_light
        self.book = Book()

        self.mpd_client = LockableMPDClient()
        self.init_mpd(conn_details)
Exemple #55
0
   def __init__(self):

      self.series = Series()
      self.author = Author()
      self.book = Book()
      self.whenRead = WhenRead()

      #establish list of fields the book method is purely responsible for
      # updating
      self.bookOnlyFields = ['book_id', 'title', 'notes', 'published',
                             'owner_status_id', 'read_status_id', 'type_id', 
                             'series_num']
Exemple #56
0
    def load_books(self):
        print("Loading books...")
        if self.has_books:

            accordion = self.index_soup.find('div', attrs={'id': 'accordion'})
            panels = accordion.find_all('div', attrs={'class': 'panel'})

            for panel in panels:
                book = Book()
                book.number = int(panel.find('h4').find('span', attrs={'class': 'book'}).get_text())

                if self.skip_first:
                    book.number -= 1
                    if book.number == 0:
                        continue

                book.number = str(book.number)
                if book.number not in self.chosen_books:
                    continue

                book.title = panel.find('h4').find('span', attrs={'class': 'title'}).find('a').get_text().strip()

                links = panel.find('div', attrs={'class': 'panel-body'}).find_all('a')
                for link in links:
                    book.add_chapter(Chapter(url=link.get('href'), title=link.get_text().strip()))

                self.books.append(book)
                print("Book {} done!".format(book))
Exemple #57
0
def start_game(grid, human):
    ''' Starts the actual tic-tac-toe game
    '''
    if human == 'O':
        ai = Book('X')        
    else:
        ai = Book('O')
        while 1==1:
            # A turn for the human if they want to go first.
            grid.print_grid()
            square = raw_input("What square would you like to fill? (1-9) ")
            if square[0] in grid.get_available():
                grid = grid.fill_square(user=human, square=square[0])
                break
            else:
                print "I'm sorry, %s isn't available." % square  
    
    # Main game loop
    while 1 == 1:
        grid = ai.check_grid(grid)
        if grid.test_win():
            grid.print_grid()
            print "Computer won!"
            break
        while 1==1:
            grid.print_grid()
            square = raw_input("What square would you like to fill? (1-9) ")
            available = grid.get_available()
            if square[0] not in available:
                print "I'm sorry, %s isn't available." % square
            else:
                grid = grid.fill_square(user=human, square=square[0])
                grid.print_grid()
                break
        if grid.test_win() == 'Draw':
            print "Draw! No one won!"
            break
        if grid.test_win():
            print "You won!"
            break        
Exemple #58
0
class TestBook(unittest.TestCase):
    ''' Unittest for the book class (just the non-logic functions. Logic is tested elsewhere)
    '''
    def setUp(self):
        self.grid = Grid()
        self.book = Book('X')
        
    def test_check_win(self):
        ''' Book can detect a threat
        '''
        self.grid.fill_square(user='******', square='1')
        self.grid.fill_square(user='******', square='2')
        self.grid, win = self.book.check_win(grid=self.grid, player='X')
        self.assertEquals(self.grid.test_win(), 'X')
Exemple #59
0
    def _get_book_from_json_dict(self, data):
        """
        Create a new Book instance based on a JSON dict.

        @param data: a JSON dictionary
        @return: a new Book instance (sans ISBN)
        """
        publishers = ', '.join([self._get_publisher_from_json_dict(p) for p in data['publishers']])
        authors = ', '.join([self._get_author_from_json_dict(a) for a in data['authors']])
        book = Book(0)  # better to create an object, even if there's no valid barcode yet
        book.title = data.get('title', None)
        book.publisher = publishers
        book.authors = authors
        book.pages = data.get('number_of_pages', None)  # might cause issue, be careful.
        book.publ_year = data.get('publish_date', None)
        book.description = data.get('excerpts', None)
        return book
Exemple #60
0
class Indexable(Persistent):
  # prepend _v_ to make it volatilive
  _v_book = None
  def __init__(self):
    self._v_book = Book()
    self._v_book.addData(self)
  def __setattr__(self, name, value):
    #only run this if the name is within the current objects attributes
    if self._v_book and name not in Persistent.__dict__:
      # if the book exists AND
      # if the value has changed
      # and that attribute is an indexable attribute
      # OR we want it to be indexed, however it is not actually in the index (this condition will be caught 
      # in updateIndexedValue)
      if self._v_book and self.__dict__.get(name) != value and name in self.indexableAttrs:
        self._v_book.updateIndexedValue(self, name, value)
      # save changes
      self._v_book.commitTransaction()
    Persistent.__setattr__(self, name, value)


  #TODO
  def __delattr__(self, name):
    pass