Ejemplo n.º 1
0
    def __init__(self, book='Genesis', chapter=1):
        """ Setup iterator.

        """

        start = Sword.VerseKey('%s %s:1' % (book, chapter))
        end = Sword.VerseKey(start.clone())
        end.setVerse(end.getVerseMax())

        super(ChapterIter, self).__init__(start.getText(), end.getText())
Ejemplo n.º 2
0
    def __init__(self, book='Genesis'):
        """ Setup iterator.

        """

        start = Sword.VerseKey('%s 1:1' % book)
        end = Sword.VerseKey(start.clone())
        end.setChapter(end.getChapterMax())
        end.setVerse(end.getVerseMax())

        super(BookIter, self).__init__(start.getText(), end.getText())
Ejemplo n.º 3
0
    def __init__(self,
                 reference_iter,
                 strongs=False,
                 morph=False,
                 module='KJV',
                 markup=Sword.FMT_PLAIN,
                 render=''):
        """ Initialize.

        """

        markup = Sword.MarkupFilterMgr(markup)

        # We don't own this or it will segfault.
        markup.thisown = False
        self._library = Sword.SWMgr(markup)
        self._library.setGlobalOption("Headings", "On")
        self._library.setGlobalOption("Cross-references", "Off")

        if strongs:
            self._library.setGlobalOption("Strong's Numbers", "On")
        else:
            self._library.setGlobalOption("Strong's Numbers", "Off")

        if morph:
            self._library.setGlobalOption("Morphological Tags", "On")
        else:
            self._library.setGlobalOption("Morphological Tags", "Off")

        # Strings for finding the heading.
        self._head_str = Sword.SWBuf('Heading')
        self._preverse_str = Sword.SWBuf('Preverse')
        self._canon_str = Sword.SWBuf('canonical')

        self._module = self._library.getModule(module)
        self._key = self._module.getKey()

        if render.lower() == 'raw':
            self._render_func = self._module.getRawEntry
        elif render.lower() == 'render_raw':
            self._fix_space_regx = re.compile(r'([^\.:\?!])\s+')
            self._fix_end_regx = re.compile(r'\s+([\.:\?!,;])')
            self._fix_start_tag_regx = re.compile(r'(<[npi]>)\s*')
            self._fix_end_tag_regx = re.compile(r'\s*(</[npi]>)')
            self._upper_divname_regx = re.compile(r'(\w+)([\'s]*)')
            self._render_func = \
                    lambda: self._parse_raw(self._module.getRawEntry(),
                                            strongs, morph)
        else:
            self._render_func = self._module.renderText

        self._ref_iter = reference_iter
Ejemplo n.º 4
0
    def __init__(self, privatePath="./", sr=None):
        self.statusReporter = sr
        self.privatePath = privatePath
        self.transport = None
        self.passive = False
        self.term = False
        if self.privatePath:
            self.privatePath = removeTrailingSlash(self.privatePath)

        confPath = privatePath + "/InstallMgr.conf"
        FileMgr.createParent(confPath)

        installConf = Sword.SWConfig(confPath)

        #SectionMap::iterator sourcesSection;
        #ConfigEntMap::iterator sourceBegin;
        #ConfigEntMap::iterator sourceEnd;

        self.sources = {}

        self.setFTPPassive(installConf.get("General", "PassiveFTP") == "false")

        sourcesSection = installConf.getSections().find(Sword.SWBuf("Sources"))
        if sourcesSection != installConf.getSections().end():
            ftp_source = Sword.SWBuf("FTPSource")
            ss = sourcesSection.value()[1]

            sourceBegin = ss.lower_bound(ftp_source)
            sourceEnd = ss.upper_bound(ftp_source)

            while sourceBegin != sourceEnd:
                install_source = InstallSource("FTP",
                                               sourceBegin.value()[1].c_str())

                self.sources[install_source.caption] = install_source
                parent = privatePath + "/" + install_source.source + "/file"
                FileMgr.createParent(parent)
                install_source.localShadow = privatePath + "/" + install_source.source
                sourceBegin += 1

        self.defaultMods = set()
        sourcesSection = installConf.getSections().find(Sword.SWBuf("General"))
        general = sourcesSection.value()[1]

        if sourcesSection != installConf.getSections().end():
            default_mod = Sword.SWBuf("DefaultMod")
            sourceBegin = general.lower_bound(default_mod)
            sourceEnd = general.upper_bound(default_mod)

            while sourceBegin != sourceEnd:
                self.defaultMods.add(sourceBegin.value()[1].c_str())
                sourceBegin += 1
Ejemplo n.º 5
0
def getNbrChapter(moduleName, bookAbbr):
    mgr = Sword.SWMgr()
    mod = mgr.getModule(moduleName)
    versification = mod.getConfigEntry("Versification")
    vk = Sword.VerseKey()
    vk.setVersificationSystem(versification)
    targetBook = 0
    for curBook in getAllBooks(versification):
        if curBook["abbr"] == bookAbbr:
            targetBook = curBook
    nbrChapter = vk.chapterCount(targetBook['testament'],
                                 targetBook['bookCount'])
    return nbrChapter
Ejemplo n.º 6
0
def book_gen() -> Generator[str, None, None]:
    """Create a Generator that yields book names in order."""
    # Yield a list of all the book names in the bible.
    verse_key = Sword.VerseKey('Genesis 1:1')
    for testament in [1, 2]:
        for book in range(1, verse_key.bookCount(testament) + 1):
            yield (verse_key.bookName(testament, book))
Ejemplo n.º 7
0
def show_available_modules():
    mgr = Sword.SWMgr()
    mgr.prefixPath = swordDir
    mgr.configPath = "%s/mods.d" % swordDir

    for m in mgr.getModules().values():
        print "%s -> %s "%(m.Name(),m.Description())
Ejemplo n.º 8
0
 def __init__( self ):
     if SwordType == "CrosswireLibrary":
         self.library = Sword.SWMgr()
         #self.keyCache = {}
         #self.verseCache = {}
     else:
         self.library = SwordModules.SwordModules() # Loads all of conf files that it can find
Ejemplo n.º 9
0
def getVerseMax(moduleName, bookName, chapterNbr, mgr):
    mod = mgr.getModule(moduleName)
    versification = mod.getConfigEntry("Versification")
    vk = Sword.VerseKey()
    vk.setVersificationSystem(versification)
    vk.setBookName(bookName)
    vk.setChapter(chapterNbr)
    return vk.getVerseMax()
Ejemplo n.º 10
0
    def __init__(self, *argv, **kwargs):
        logger.debug("SwordBible - Create a new instance")

        super().__init__(*argv, **kwargs)

        self.key = Sword.VerseKey_castTo(self.mod.getKey())
        self.key.setPersist(True)
        self.key.setVersificationSystem(self.mod.getConfigEntry("Versification"))
Ejemplo n.º 11
0
    def __init__(self, reference_iter: Iterator, module: str = 'KJV'):
        """Initialize the sword module."""
        # This doesn't matter.
        markup = Sword.MarkupFilterMgr(Sword.FMT_PLAIN)

        # We don't own this or it will segfault.
        markup.thisown = False
        self._library = Sword.SWMgr(markup)

        self._module = self._library.getModule(module)
        self._key = self._module.getKey()

        self._ref_iter = reference_iter

        self._fix_space_regx = re.compile(r'([^\.:\?!])\s+')
        self._fix_end_regx = re.compile(r'\s+([\.:\?!,;])')
        self._remove_tag_regx = re.compile(r'(<i>\s?|\s?</i>)')
        self._fix_start_tag_regx = re.compile(r'(<i>)\s*')
        self._fix_end_tag_regx = re.compile(r'\s*(</i>)')
Ejemplo n.º 12
0
def _sword_bible_search(unicode_key_search):
    bible = BIBLE_CONFIG['default_bible']
    locale = BIBLE_CONFIG['default_locale']

    str_key_search = to_str(unicode_key_search)

    try:
        library = sw.SWMgr()
        bible_module = library.getModule(bible)
        key_module = sw.SWKey(str_key_search)
        key_module.setLocale(locale)
        bible_module.setKey(key_module)

        unicode_bible_name = bible
        unicode_module_text = to_unicode(bible_module.getRawEntry())
        unicode_key_name = to_unicode(bible_module.getKeyText())

    except Exception, e:
        raise BibleError(e)
Ejemplo n.º 13
0
    def _book_gen(self):
        """ A Generator function that yields book names in order.

        """

        # Yield a list of all the book names in the bible.
        verse_key = Sword.VerseKey('Genesis 1:1')
        for testament in [1, 2]:
            for book in range(1, verse_key.bookCount(testament) + 1):
                yield (verse_key.bookName(testament, book))
Ejemplo n.º 14
0
    def __init__(self, reference: str = "Genesis 1:1"):
        """ Get the book, chapter, and verse of the reference so it can be
        incremented and decremented.

        """

        self._verse_ref = Sword.VerseKey(reference)
        self._book = self._verse_ref.getBookCount()
        self._chapter = self._verse_ref.getChapter()
        self._verse = self._verse_ref.getVerse()
Ejemplo n.º 15
0
    def __init__(self, start, end='Revelation of John 22:21'):
        """ Setup the start and end references of the range.

        """

        # Make sure the range is in order.
        start, end = sorted([start, end], key=sort_key)
        self._verse = Sword.VerseKey(start, end)
        self._end_ref = self._verse.getUpperBound().getText()

        self._verse_ref = ''
Ejemplo n.º 16
0
 def Find( attribute ):
     """ Search for methods and attributes """
     print( "\nSearching for attribute '{}'...".format( attribute ) )
     found = False
     AA = attribute.upper()
     for thing in dir(Sword):
         BB = thing.upper()
         if BB.startswith(AA): print( "  Have {} in Sword".format( thing ) ); found = True
     for thing in dir(Sword.SWVersion()):
         BB = thing.upper()
         if BB.startswith(AA): print( "  Have {} in SWVersion".format( thing ) ); found = True
     for thing in dir(Sword.SWMgr()):
         BB = thing.upper()
         if BB.startswith(AA): print( "  Have {} in SWMgr".format( thing ) ); found = True
     module = library.getModule( "KJV" )
     for thing in dir(module):
         BB = thing.upper()
         if BB.startswith(AA): print( "  Have {} in SWModule".format( thing ) ); found = True
     for thing in dir(Sword.SWKey()):
         BB = thing.upper()
         if BB.startswith(AA): print( "  Have {} in SWKey".format( thing ) ); found = True
     for thing in dir(Sword.VerseKey()):
         BB = thing.upper()
         if BB.startswith(AA): print( "  Have {} in VerseKey".format( thing ) ); found = True
     #for thing in dir(Sword.InstallMgr()):
         #BB = thing.upper()
         #if BB.startswith(AA): print( "  Have {} in InstallMgr".format( thing ) ); found = True
     for thing in dir(Sword.LocaleMgr()):
         BB = thing.upper()
         if BB.startswith(AA): print( "  Have {} in LocaleMgr".format( thing ) ); found = True
     for thing in dir(Sword.SWFilterMgr()):
         BB = thing.upper()
         if BB.startswith(AA): print( "  Have {} in SWFilterMgr".format( thing ) ); found = True
     if not found: print( " Sorry, '{}' not found.".format( attribute ) )
Ejemplo n.º 17
0
def add_context(ref_set, count=0):
    """ Add count number of verses before and after each reference.

    """

    if count == 0:
        return ref_set

    # Make a copy to work on.
    clone_set = set(ref_set)
    for ref in ref_set:
        start = Sword.VerseKey(ref)
        end = Sword.VerseKey(ref)
        # Pass the beginning of the book.
        start.decrement()
        start.decrement(count - 1)
        # Pass the end of the book.
        end.increment()
        end.increment(count - 1)
        clone_set.update(VerseIter(start.getText(), end.getText()))

    return clone_set
Ejemplo n.º 18
0
    def get_text(self, key):
        """ Get the text at the given key in the module.
        i.e. get_text('3778') returns the greek strongs.

        """

        encoding = get_encoding()
        self._module.setKey(Sword.SWKey(key.encode('utf8')))
        item_text = self._module.renderText()
        # Make the text printable.
        # item_text = item_text.encode(encoding, 'replace')
        # item_text = item_text.decode(encoding, 'replace')
        return fill(item_text, screen_size()[1])
Ejemplo n.º 19
0
 def getGenBookTOC( tk, parent ):
     if tk is None: # obtain one from the module
         tk = Sword.TreeKey_castTo( module.getKey() ) # Only works for gen books
     if tk and tk.firstChild():
         while True:
             print( " ", tk.getText() )
             # Keep track of the information for custom implementation
             #Class *item = storeItemInfoForLaterUse(parent, text);
             item = (parent) # temp ....................
             if tk.hasChildren():
                 print( "  Getting children..." )
                 getGenBookTOC( tk, item )
             if not tk.nextSibling(): break
Ejemplo n.º 20
0
    def get_raw_text(self, key):
        """ Get the text at the given key in the module.
        i.e. get_text('3778') returns the greek strongs.

        """

        encoding = get_encoding()
        self._module.setKey(Sword.SWKey(key.encode('utf-8')))
        item_text = self._module.getRawEntry()

        # Make the text printable.
        # item_text = item_text.encode(encoding, 'replace')
        # item_text = item_text.decode(encoding, 'replace')
        return item_text
Ejemplo n.º 21
0
 def makeKey( self, BBB, C, V ):
     #if Globals.debugFlag: print( "SwordResources.makeKey({})".format( BCV ) )
     #if BCV  in self.keyCache:
         #print( "Cached", BCV )
         #return self.keyCache[BCV]
     if SwordType == "CrosswireLibrary":
         B = Globals.BibleBooksCodes.getOSISAbbreviation( BBB )
         refString = "{} {}:{}".format( B, C, V )
         #print( 'refString', refString )
         verseKey = Sword.VerseKey( refString )
         #self.keyCache[BCV] = verseKey
         return verseKey
     else:
         return SwordKey( BBB, C, V )
Ejemplo n.º 22
0
    def do_search():
        rawResults = mod.mod.doSearch(keyword)

        # rawResults cannot be pass to callback (weird bug)
        # so it is copied in a dictionnary
        # In addition, results are sort by book
        results = {}
        for _ in range(rawResults.getCount()):
            bookName = str(Sword.VerseKey_castTo(rawResults.getElement()).getBookName())
            results[bookName] = results.get(bookName, []) + [str(rawResults.getText())]
            #results.append(rawResults.getText())
            rawResults.increment()

        GLib.idle_add(callback, results)
Ejemplo n.º 23
0
 def attack(self):
     if self.isAttacking == True:
         pass
     elif self.attackDelay == 0:
         if self.direction == "left":
             facing = -1
         if self.direction == "right":
             facing = 1
         if self.direction == "none":
             facing = 0
         self.sword = Sword(self.rect.x, self.rect.y, 40, 20, facing)
         self.level.enemy_attack_list.add(self.sword)
         self.isAttacking = True
         self.attackDelay = 30
Ejemplo n.º 24
0
def get_verse(bookStr,
              chapterInt,
              verseNbr,
              moduleName,
              outputType=Sword.FMT_PLAIN):
    markup = Sword.MarkupFilterMgr(outputType)
    markup.thisown = False
    mgr = Sword.SWMgr(markup)

    mod = mgr.getModule(moduleName)
    versification = mod.getConfigEntry("Versification")
    vk = Sword.VerseKey()
    vk.setVersificationSystem(versification)
    #vk.setTestament() ??
    vk.setBookName(bookStr)
    vk.setChapter(chapterInt)
    vk.setVerse(verseNbr)
    mod.setKey(vk)
    mgr.setGlobalOption("Hebrew Vowel Points", "On")
    #mgr.setGlobalOption("Hebrew Cantillation", "Off")
    if not mod:
        print("No module")
        sys.exit()
    return mod.renderText()
Ejemplo n.º 25
0
Archivo: index.py Proyecto: a2ohm/theke
    def index_sword_biblical_book_names(self) -> None:
        """Index sword biblical book names.

        Sword use some names to designate biblibal books.
        Index them once for all.
        """

        if self.index.get_from_header('are_sword_biblical_books_indexed',
                                      "no") == "yes":
            logger.debug(
                "ThekeIndexBuilder − Index sword biblical book names [skip]")
            return

        logger.debug("ThekeIndexBuilder − Index sword biblical book names")

        # Index names used by sword for biblical books
        vk = Sword.VerseKey()

        for itestament in [theke.BIBLE_OT, theke.BIBLE_NT]:
            vk.setTestament(itestament)

            for ibook in range(1, vk.getBookMax() + 1):
                vk.setBook(ibook)

                # Create a new biblical book entry
                documentId = self.index.execute_returning_id(
                    """INSERT INTO documents  (type)
                    VALUES(?);""", (theke.TYPE_BIBLE, ))

                # Index the biblical book name
                self.index_biblical_book_name(documentId,
                                              vk.getBookName(),
                                              "en",
                                              "sword",
                                              doCommit=False)

                # Index the number of chapters and the testament
                self.index.execute(
                    """INSERT OR IGNORE INTO biblicalBookData (id_document, nbOfChapters, testament)
                    VALUES(?, ?, ?);""",
                    (documentId, vk.getChapterMax(), itestament))

        self.index.execute("""INSERT INTO header (key, value) VALUES(?, ?);""",
                           ("are_sword_biblical_books_indexed", "yes"))

        self.index.commit()
 def attack(self):
   if self.isAttacking == True:
     pass
   else:
     # print(self.playerID, " is attacking!")
     if self.direction == "left":
       facing = -1
     if self.direction == "right":
       facing = 1
     if self.direction == "none":
       facing = 0
     
     self.sword = Sword(self.rect.x, self.rect.y, 25, 10, self.color, facing)
     if self.isAI:
         self.level.player_attack_list.add(self.sword)
     else:
         self.level.enemy_attack_list.add(self.sword)
     self.isAttacking = True
Ejemplo n.º 27
0
def getAllBooks():
    """
     Return an array:
     [{'testament': 1, 'bookCount': 1, 'name': 'Genesis', 'abbr': 'Gen'},
     {'testament': 1, 'bookCount': 2, 'name': 'Exodus', 'abbr': 'Exod'},
    """
    vk=Sword.VerseKey()
    out=[]
    for i in range(1,3):
      vk.setTestament(i)
      for j in range(1,vk.bookCount(i)+1):
         vk.setBook(j)
         tmp={}
         tmp['name']=vk.bookName(i,j)
         tmp['abbr']=vk.getBookAbbrev()
         tmp['testament']=i
         tmp['bookCount']=j
         out.append(tmp)
    return out
Ejemplo n.º 28
0
def modcompare(arglist=sys.argv):  # pylint: disable=dangerous-default-value
    """
    Compares two modules, verse by verse, and reports verses that differ between
    the two.
    """
    parser = argparse.ArgumentParser(
        description="Compares two SWORD modules, verse by"
        " verse, to certify that the contents of each are identical")
    parser.add_argument("original", help="First module")
    parser.add_argument("test",
                        help="Second module to compare against the first")
    args = parser.parse_args(arglist)

    original = utils.get_mod(args.original)
    test = utils.get_mod(args.test)

    if original is None or test is None:
        print(
            "Please double check that both modules are installed and accessible",
            file=sys.stderr,
        )
        sys.exit(1)

    key = Sword.VerseKey(original.createKey())
    test.setKey(key)
    book = key.getBook()

    while key.popError() == "\x00":
        if book != key.getBook():
            print("Checked up through ", key.getText())
            book = key.getBook()
        original_text = original.renderText().c_str()
        test_text = test.renderText().c_str()
        if original_text != test_text:
            print(f"Mismatch in {key.getText()}")
            print(f"Original text is*********:\n{original_text}")
            print(f"New text is*********:\n{test_text}")
        key.increment()
        original.setKey(key)
        test.setKey(key)

    print("Comparison ended at ", key.getText())
Ejemplo n.º 29
0
def get_verse(bookStr, chapterInt, verseNbr, moduleName, mgr):
    mod = mgr.getModule(moduleName)
    versification = mod.getConfigEntry("Versification")
    vk = Sword.VerseKey()
    vk.setVersificationSystem(versification)
    vk.setBookName(bookStr)
    vk.setChapter(chapterInt)
    vk.setVerse(verseNbr)
    mod.setKey(vk)
    mgr.setGlobalOption("Hebrew Vowel Points", "On")
    mgr.setGlobalOption("Hebrew Cantillation", "On")
    mgr.setGlobalOption("Strong's Numbers", "Off")
    mgr.setGlobalOption("Headings", "Off")
    mgr.setGlobalOption("Footnotes", "Off")
    mgr.setGlobalOption("Textual Variants", "Off")
    mgr.setGlobalOption("Morphological Tags", "Off")
    mgr.setGlobalOption("Lemmas", "Off")
    mgr.setGlobalOption("Greek Accents", "On")

    if not mod:
        print("No module")
        sys.exit()
    return mod.renderText()
Ejemplo n.º 30
0
Archivo: index.py Proyecto: a2ohm/theke
    def index_sword_biblical_module(self, sourceId, mod) -> None:
        """Index a sword biblical module
        """

        logger.debug("ThekeIndexBuilder - Index %s as a Bible (id: %s)",
                     mod.get_name(), sourceId)

        # Index each of the biblical books of this module
        # TODO: Y a-t-il une façon plus propre de faire la même chose ?
        vk = Sword.VerseKey()

        for itestament in [1, 2]:
            vk.setTestament(itestament)

            for ibook in range(1, vk.getBookMax() + 1):
                vk.setBook(ibook)
                if mod.has_entry(vk):
                    bookId = self.index.get_document_id(vk.getBookName())
                    self.link_biblical_book(vk.getBookName(),
                                            bookId,
                                            sourceId,
                                            doCommit=False)

        self.index.commit()
Ejemplo n.º 31
0
    def __init__(self):
        Sword1 = Sword(1)
        Sword2 = Sword(2)
        Sword3 = Sword(3)
        Staff1 = Staff(1)
        Staff2 = Staff(2)
        Staff3 = Staff(3)
        Bow1 = Bow(1)
        Bow2 = Bow(2)
        Bow3 = Bow(3)

        self.inventory = {
            Sword1.getitemName(): 100,
            Staff1.getitemName(): 100,
            Bow1.getitemName(): 100,
            Sword2.getitemName(): 200,
            Staff2.getitemName(): 200,
            Bow2.getitemName(): 200,
            Sword3.getitemName(): 300,
            Staff3.getitemName(): 300,
            Bow3.getitemName(): 300,
        }