Esempio n. 1
0
 def testDefaultMethods(self):
     try:
         testdefault = JClass('jpype.overloads.Test1$DefaultC')()
     except:
         pass
     else:
         self.assertEquals('B', testdefault.defaultMethod())
Esempio n. 2
0
    def from_dict(cls, dictionary):
        JProperties = JClass(cls.PROPERTIES_CLASS)
        jprops = JProperties()
        for k, v in dictionary.items():
            if not isinstance(k, str):
                raise ValueError('[{}] keys must be strings, got: {}'.format(cls.PROPERTIES_CLASS, type(k)))
            jprops.setProperty(k, v)

        return jprops
Esempio n. 3
0
 def testSerialize(self):
     o = JClass("jpype.serial.SerializationTest")()
     tmp = self.tempname
     fos = java.io.FileOutputStream(tmp)
     oos = java.io.ObjectOutputStream(fos)
     oos.writeObject(o)
     oos.flush()
     oos.close()
     fos.close()
Esempio n. 4
0
    def zemberek(self):
        try:
            if not jpype.isJVMStarted():
                jpype.startJVM(self.libjvmpath,
                               "-Djava.class.path=" + self.zemberekJarpath,
                               "-ea",
                               convertStrings=False)
                return JClass("zemberek.morphology.TurkishMorphology")
            else:
                # print("Zaten jvm çalışıyor!")
                return JClass("zemberek.morphology.TurkishMorphology")
        except:
            print(
                "Libjvm veya zemberek.jar dosyalarının pathleri yanlış yerde! "
            )


#ZemberekInit(libjvmpath=r"C:\Program Files\Java\jdk1.8.0_151\jre\bin\server\jvm.dll").zemberek()
Esempio n. 5
0
    def testPassedObjectGetsCleanedUp(self):
        import platform
        if platform.python_implementation() == 'PyPy':
            raise common.unittest.SkipTest(
                'PyPy memory model does not pass test')

        h = JClass('jpype.attr.Test1')()
        block_size = 1024 * 1024 * 10

        def allocate_then_free():
            byte_buffer = jpype.JClass('java.nio.ByteBuffer')
            inst = byte_buffer.allocate(1024 * 1024 * 100)
            # passing the object back to java seems to stop it being collected
            result = h.callWithSomething(inst)

        rt = JClass('java.lang.Runtime').getRuntime()
        free = rt.freeMemory()
        for x in range(0, 10 * free // block_size):
            allocate_then_free()
Esempio n. 6
0
    def sent_Tokenize(self, paragraph):
        TurkishSentenceExtractor: JClass = JClass(
            'zemberek.tokenization.TurkishSentenceExtractor')

        extractor: TurkishSentenceExtractor = TurkishSentenceExtractor.DEFAULT

        sentences = extractor.fromParagraph((paragraph))

        for i, word in enumerate(sentences):
            print(f'Sentence {i + 1}: {word}')
Esempio n. 7
0
    def get_object_jar(self):
        # 获取java的实体类
        java_class = JClass("com.jar.test.JavaClass")

        # java的实体类使用案例
        java_instance = java_class("oldvalue")  # 实例化对象
        self.log.info(java_instance.getValue())  # 调用JAVA对象的方法
        java_instance.setName("胜")
        self.log.info(java_instance.name)
        self.log.info(java_instance.getName())
Esempio n. 8
0
    def testDifferentiateClassAndObject(self):
        h = JClass('jpype.attr.Test1')()

        self.assertEqual(h.callWithSomething(JClass('jpype.attr.Test1')),
                         u"Class")
        result = h.callWithSomething(
            jpype.JObject(JClass('jpype.attr.Test1'),
                          JClass('java.lang.Object')))
        self.assertEqual(result, u"Object")
Esempio n. 9
0
class Zemberek:

    ZEMBEREK_PATH: str = join('zemberek-full.jar')

    startJVM(getDefaultJVMPath(),
             '-ea',
             f'-Djava.class.path={ZEMBEREK_PATH}',
             convertStrings=False)

    TurkishMorphology: JClass = JClass('zemberek.morphology.TurkishMorphology')
    morphology: TurkishMorphology = TurkishMorphology.createWithDefaults()
Esempio n. 10
0
    def stem(self, word):
        TurkishMorphology: JClass = JClass(
            'zemberek.morphology.TurkishMorphology')
        WordAnalysis: JClass = JClass(
            'zemberek.morphology.analysis.WordAnalysis')

        morphology: TurkishMorphology = TurkishMorphology.createWithDefaults()

        print(f'\nWord: {word}\n\nResults:')

        results: WordAnalysis = morphology.analyze(JString(word))

        for result in results:
            print(
                f'{str(result.formatLong())}'
                f'\n\tStems ='
                f' {", ".join([str(result) for result in result.getStems()])}'
                f'\n\tLemmas ='
                f' {", ".join([str(result) for result in result.getLemmas()])}'
            )
Esempio n. 11
0
 def split_into_sentences(self):
     if self.sentences:
         return self.sentences
     else:
         turkish_sentence_extractor: JClass = JClass(
             'zemberek.tokenization.TurkishSentenceExtractor')
         extractor: turkish_sentence_extractor = turkish_sentence_extractor.DEFAULT
         print("Sile" + self.file.raw_text)
         sentences = extractor.fromParagraph(self.file.raw_text)
         # s = []
         return [word for word in sentences]
    def initializeJVM(self, client_dir='./'):

        self.NATS_SIMULATION_STATUS_ENDED = NATS_SIMULATION_STATUS_ENDED
        NATSClientFactory = JClass('NATSClientFactory')
        self.natsClient = NATSClientFactory.getNATSClient()

        self.equipmentInterface = self.natsClient.getEquipmentInterface()

        # Get EnvironmentInterface
        self.environmentInterface = self.natsClient.getEnvironmentInterface()
        # Get AirportInterface
        self.airportInterface = self.environmentInterface.getAirportInterface()
        # Get TerminalAreaInterface
        self.terminalAreaInterface = self.environmentInterface.getTerminalAreaInterface(
        )

        self.sim = self.natsClient.getSimulationInterface()

        self.aircraftInterface = self.equipmentInterface.getAircraftInterface(
        )
Esempio n. 13
0
 def testSerialize(self):
     o = JClass("jpype.serial.SerializationTest")()
     tmp = self.tempname
     if sys.platform == 'cygwin':
         from jpype import _posix2win
         tmp = _posix2win(tmp)
     fos = java.io.FileOutputStream(tmp)
     oos = java.io.ObjectOutputStream(fos)
     oos.writeObject(o)
     oos.flush()
     oos.close()
     fos.close()
Esempio n. 14
0
    def normalizeDocument(self,document):
        '''This function normalizes a given document.'''
        Paths: JClass = JClass('java.nio.file.Paths')
        path1 = Paths.get(os.path.join('.', 'req_data'))
        path2 = Paths.get(os.path.join('.', 'req_data', 'lm.2gram.slm'))
        normalizer = self.TurkishSentenceNormalizer(self.TurkishMorphology.createWithDefaults(),path1,path2)

        normalizedDoc = normalizer.normalize(JString(document))
        if self.verbose:
            print(f'\nNoisy : {document}')
            print(f'\nNormalized : {normalizedDoc}' )

        return str(normalizedDoc)
Esempio n. 15
0
    def jdbc_name(self, jdbc_code):
        """
        Given a jdbc type code return the type name

        :param jdbc_code:
        :return:
        """
        try:
            type_name = str(JClass('java.sql.JDBCType').valueOf(jdbc_code)).upper()
        except Exception as e:
            raise ValueError('unable to resolve jdbc type code: {}'.format(jdbc_code)) from e

        return type_name
Esempio n. 16
0
 def get_qm_indices(self):
   self.result=self.adaptiveQMMM.process(self.input_file)
   #Region=JClass("org.wallerlab.yoink.api.model.regionizer.Region")
   RegionName=JClass("org.wallerlab.yoink.api.model.region.Region$Name")
   qm_atoms=self.result.getRegions().get(RegionName.valueOf("QM")).getAtoms()
   qm_atom_indices=[]
   qm_size= qm_atoms.size()
   for i in range(qm_size):
     atom=qm_atoms.get(i)
     qm_atom_indices.append(atom.getIndex())
   qm_atom_indices=np.sort(qm_atom_indices)
   qm_molecules_temp=self.result.getRegions().get(
     RegionName.valueOf("QM")).getMolecules()
   qm_molecules=java.util.ArrayList()
   qm_molecules.addAll(qm_molecules_temp)
   qm_molecule_indices=[]
   qm_size= qm_molecules.size()
   for i in range(qm_size):
     molecule=qm_molecules.get(i)
     qm_molecule_indices.append(molecule.getIndex())
   qm_molecule_indices=np.sort(qm_molecule_indices)
   return qm_atom_indices, qm_molecule_indices
Esempio n. 17
0
 def get_atoms_molecules(self):
     MoleculeList = JClass("org.xml_cml.schema.MoleculeList")
     Molecule = JClass("org.xml_cml.schema.Molecule")
     AtomArray = JClass("org.xml_cml.schema.AtomArray")
     Atom = JClass("org.xml_cml.schema.Atom")
     cmlSystem = self.jaxb_cml.getValue().getAnyCmlOrAnyOrAny()
     atoms = []
     molecules = []
     self.qm_core_fixed_indices = []
     counter = 0
     for l in range(cmlSystem.size()):
         if (cmlSystem.get(l).getValue().getClass() == MoleculeList):
             moleculeList = cmlSystem.get(
                 l).getValue().getAnyCmlOrAnyOrAny()
             for i in range(moleculeList.size()):
                 if (moleculeList.get(i).getValue().getClass() == Molecule):
                     molecules.append(moleculeList.get(i).getValue())
                     molecule_id = str(
                         moleculeList.get(i).getValue().getId())
                     qm_core = (str(moleculeList.get(i).getValue().getId())
                                == "QM_CORE_FIXED")
                     molecule = moleculeList.get(
                         i).getValue().getAnyCmlOrAnyOrAny()
                     for j in range(molecule.size()):
                         if (molecule.get(j).getValue().getClass() ==
                                 AtomArray):
                             atomArray = molecule.get(
                                 j).getValue().getAnyCmlOrAnyOrAny()
                             for k in range(atomArray.size()):
                                 if (atomArray.get(k).getValue().getClass()
                                         == Atom):
                                     atom = atomArray.get(k).getValue()
                                     atoms.append(atom)
                                     counter = counter + 1
                                     if (qm_core):
                                         self.qm_core_fixed_indices.append(
                                             counter)
     return atoms, molecules
Esempio n. 18
0
    def initializeJVM(
        self,
        client_dir='/home/dyn.datasys.swri.edu/mhartnett/NASA_ULI/NASA_ULI_InfoFusion/src/NATS/Client/'
    ):

        self.NATS_SIMULATION_STATUS_ENDED = NATS_SIMULATION_STATUS_ENDED
        NATSClientFactory = JClass('NATSClientFactory')
        self.natsClient = NATSClientFactory.getNATSClient()

        self.equipmentInterface = self.natsClient.getEquipmentInterface()

        # Get EnvironmentInterface
        self.environmentInterface = self.natsClient.getEnvironmentInterface()
        # Get AirportInterface
        self.airportInterface = self.environmentInterface.getAirportInterface()
        # Get TerminalAreaInterface
        self.terminalAreaInterface = self.environmentInterface.getTerminalAreaInterface(
        )

        self.sim = self.natsClient.getSimulationInterface()

        self.aircraftInterface = self.equipmentInterface.getAircraftInterface(
        )
Esempio n. 19
0
def getCpTransSyncSignValid():
    global CpTransSyncSignValid
    if CpTransSyncSignValid:
        return CpTransSyncSignValid
    import os
    import jpype
    from jpype import JClass
    path = os.path.join(os.environ.get("PYTHONPATH", '.'),
                        "lenovo_pay_sign-1.0.0.5.jar")
    logger.info("JVM path %s", jpype.getDefaultJVMPath())
    logger.info("class.path %s", path)
    jpype.startJVM(jpype.getDefaultJVMPath(), "-Djava.class.path=%s" % path)
    CpTransSyncSignValid = JClass("com.lenovo.pay.sign.CpTransSyncSignValid")
    return CpTransSyncSignValid
Esempio n. 20
0
 def update_input_file(self, positions=None,qm_core_fixed=None):
   Double=JClass("java.lang.Double")
   if(positions is not  None):
     for iposition, position in enumerate(positions):
       atom=self.atoms[iposition]
       atom.setX3(Double(float(position[0])))
       atom.setY3(Double(float(position[1])))
       atom.setZ3(Double(float(position[2])))
   if(qm_core_fixed != None):
     for m in self.molecules:
       m.setId(JString("MM"))
     for q in qm_core_fixed:
       self.molecules[q-1].setId(JString("QM_CORE_FIXED"))
   self.jaxbFileWriter.write(JString(self.input_file),self.jaxb_cml.getValue())
Esempio n. 21
0
def start_jvm(jvmargs=None):
    """Start the Java Virtual Machine via :mod:`JPype`.

    Parameters
    ----------
    jvmargs : str or list of str, optional
        Additional arguments for launching the JVM, passed to
        :func:`jpype.startJVM`.

        For instance, to set the maximum heap space to 4 GiB, give
        ``jvmargs=['-Xmx4G']``. See the `JVM documentation`_ for a list of
        options.

        .. _`JVM documentation`: https://docs.oracle.com/javase/7/docs
           /technotes/tools/windows/java.html)
    """
    # TODO change the jvmargs default to [] instead of None
    if jpype.isJVMStarted():
        return

    jvmargs = jvmargs or []

    # Arguments
    args = [jpype.getDefaultJVMPath()]

    # Add the ixmp root directory, ixmp.jar and bundled .jar and .dll files to
    # the classpath
    module_root = Path(__file__).parents[1]
    jarfile = module_root / 'ixmp.jar'
    module_jars = list(module_root.glob('lib/*'))
    classpath = map(str, [module_root, jarfile] + list(module_jars))

    sep = ';' if os.name == 'nt' else ':'
    args.append('-Djava.class.path={}'.format(sep.join(classpath)))

    # Add user args
    args.extend(jvmargs if isinstance(jvmargs, list) else [jvmargs])

    # For JPype 0.7 (raises a warning) and 0.8 (default is False).
    # 'True' causes Java string objects to be converted automatically to Python
    # str(), as expected by ixmp Python code.
    kwargs = dict(convertStrings=True)

    jpype.startJVM(*args, **kwargs)

    # define auxiliary references to Java classes
    global java
    for class_name in JAVA_CLASSES:
        setattr(java, class_name.split('.')[-1], JClass(class_name))
Esempio n. 22
0
def start_jvm(jvmargs=None):
    """Start the Java Virtual Machine via :mod:`JPype`.

    Parameters
    ----------
    jvmargs : str or list of str, optional
        Additional arguments for launching the JVM, passed to
        :func:`jpype.startJVM`.

        For instance, to set the maximum heap space to 4 GiB, give
        ``jvmargs=['-Xmx4G']``. See the `JVM documentation`_ for a list of
        options.

        .. _`JVM documentation`: https://docs.oracle.com/javase/7/docs
           /technotes/tools/windows/java.html)
    """
    if jvmargs is None:
        jvmargs = []
    if jpype.isJVMStarted():
        return

    # Arguments
    args = jvmargs if isinstance(jvmargs, list) else [jvmargs]

    # Base for Java classpath entries
    cp = Path(__file__).parents[1]

    # Keyword arguments
    kwargs = dict(
        # Given 'lib/*' JPype will only glob '*.jar', so glob here explicitly
        classpath=map(str, chain([cp / 'ixmp.jar'], cp.glob('lib/*'))),

        # For JPype 0.7 (raises a warning) and 0.8 (default is False).
        # 'True' causes Java string objects to be converted automatically to
        # Python str(), as expected by ixmp Python code.
        convertStrings=True,
    )

    log.debug(f"JAVA_HOME: {os.environ.get('JAVA_HOME', '(not set)')}")
    log.debug(f'jpype.getDefaultJVMPath: {jpype.getDefaultJVMPath()}')
    log.debug(f'args to startJVM: {args} {kwargs}')

    jpype.startJVM(*args, **kwargs)

    # define auxiliary references to Java classes
    global java
    for class_name in JAVA_CLASSES:
        setattr(java, class_name.split('.')[-1], JClass(class_name))
Esempio n. 23
0
 def testExceptionByJavaClass(self):
     ext = JClass('jpype.exc.ExceptionTest')
     try:
         ext.throwRuntime()
         self.fail()
     except JClass('java.lang.RuntimeException') as ex:
         self.assertIs(type(ex), JClass('java.lang.RuntimeException'))
         self.assertEqual('Foo', ex.message())
         trace = ex.stacktrace()
         self.assertTrue(
             str(trace).startswith('java.lang.RuntimeException: Foo'))
Esempio n. 24
0
    def generateVerb(self, verb):
        # ***********************This part is from Zemberek***********************
        positive_negatives: List[JString] = [JString(''), JString('Neg')]
        times: List[JString] = [
            'Imp', 'Aor', 'Past', 'Prog1', 'Prog2', 'Narr', 'Fut'
        ]
        people: List[JString] = [
            'A1sg', 'A2sg', 'A3sg', 'A1pl', 'A2pl', 'A3pl'
        ]

        verb = self.verbRootGenerator(
            verb
        )  # This function generates '-mek, -mak' type of the given verb
        TurkishMorphology: JClass = JClass(
            'zemberek.morphology.TurkishMorphology')
        morphology: TurkishMorphology = (TurkishMorphology.builder(
        ).setLexicon(verb).disableCache().build())

        # ***********************This part is from Zemberek***********************

        stem = self.verbStemGenerator(
            verb
        )  # This function generates without '-mek, -mak' type of the given verb

        # ***********************This part is from Zemberek ***********************
        for pos_neg in positive_negatives:
            for time in times:
                for person in people:
                    seq: java.util.ArrayList = java.util.ArrayList()
                    if pos_neg:
                        seq.add(JString(pos_neg))
                    if time:
                        seq.add(JString(time))
                    if person:
                        seq.add(JString(person))
                    results = list(morphology.getWordGenerator().generate(
                        JString(stem), seq))
                    if not results:
                        continue
                    # ***********************This part is from Zembere***********************
                    for result in results:
                        # After we generate new verb from source we look if this verb obeys the rule
                        self.controller(str(result.surface), recurrence=False)
                        # We call controller with recurrence = False because if we call it without giving this parameter
                        # Program will enter a recurrence relation that never ends.
        return
Esempio n. 25
0
    def controller(
        self,
        word,
        recurrence=True
    ):  # This function checks if the given input obeys the given input
        global wordCounter
        if wordCounter == numOfWords:
            exit(1)
        total = 0
        values = []
        cont = True
        for letter in word:
            if letter not in letterValue:
                cont = False
                continue
            values.append(letterValue[letter])
            total = total + letterValue[letter]
        if not cont:
            return
        if total == wordSum:
            wordCounter += 1
            if not recurrence:
                print(wordCounter, ": ", word, values, total,
                      "(Generated word!)")
            else:
                print(wordCounter, ": ", word, values, total)

        elif total < wordSum and recurrence:  # If given input's value is less then wanted value and
            # this is not an recursive call
            # we generate new words from it
            TurkishMorphology: JClass = JClass(
                'zemberek.morphology.TurkishMorphology')
            morphologyController: TurkishMorphology = TurkishMorphology.createWithDefaults(
            )
            analysis: java.util.ArrayList = (
                morphologyController.analyzeAndDisambiguate(
                    word).bestAnalysis())
            # We can only generate new nouns and verbs
            for i, analysis in enumerate(analysis, start=1):
                if str(analysis.getPos()) == 'Noun':
                    self.generateNoun(word)
                elif str(analysis.getPos()) == 'Verb':
                    self.generateVerb(word)
                break
        return
Esempio n. 26
0
 def tokenize(self, content, no_pos=True, engine='NLPTokenizer'):
     """分词
     """
     if isinstance(content, str) and len(content) > 0:
         segments = []
         if engine == 'StandardTokenizer':
             tokenizer = JClass(
                 'com.hankcs.hanlp.tokenizer.StandardTokenizer')
         elif engine == 'IndexTokenizer':
             tokenizer = JClass('com.hankcs.hanlp.tokenizer.IndexTokenizer')
         elif engine == 'SpeedTokenizer':
             tokenizer = JClass('com.hankcs.hanlp.tokenizer.SpeedTokenizer')
         else:
             # NLPTokenizer
             tokenizer = JClass('com.hankcs.hanlp.tokenizer.NLPTokenizer')
         ret = tokenizer.segment(content)
         # print(content, ret)
         for v in ret:
             if no_pos:
                 segments.append(re.sub(r'/[a-zA-Z0-9]+$', '', str(v)))
             else:
                 segments.append(str(v))
         return segments
Esempio n. 27
0
    def description(self):
        if self._description:
            return self._description
        if not self._metadata:
            return

        meta = self._metadata
        count = meta.getColumnCount()
        self._description = []
        for col in range(1, count + 1):
            size = meta.getColumnDisplaySize(col)
            jdbc_type = meta.getColumnType(col)
            if jdbc_type == 0:  # NULL
                type_desc = 'NULL'
            else:
                dbapi_type = self._type_conversion.py_type(jdbc_type)
                dbapi_type_str = getattr(dbapi_type, '__name__',
                                         None) or str(dbapi_type)
                jdbc_type_name = (self._type_conversion.jdbc_name(jdbc_type)
                                  or str(meta.getColumnTypeName(col)).upper())
                type_desc = '{} - JDBC:{}'.format(dbapi_type_str,
                                                  jdbc_type_name)

            # some drivers return Integer.MAX_VALUE when the metadata is not present
            max_int = JClass('java.lang.Integer').MAX_VALUE

            size = size if size != max_int else None
            precision = meta.getPrecision(col)
            precision = precision if precision != max_int else None
            scale = meta.getScale(col)
            scale = scale if scale != max_int else None

            col_desc = (
                meta.getColumnName(col),  # name
                type_desc,  # type_code
                size,  # display_size
                size,  # internal_size
                precision,  # precision
                scale,  # scale
                meta.isNullable(col))  # null_ok

            self._description.append(col_desc)

        return self._description
Esempio n. 28
0
def train_evaluate(ratios):
    if not os.path.isfile(msr_model):
        model = CWSTrainer().train(msr_train, msr_train, msr_model, 0, 10,
                                   8).getModel()  # 训练模型
    else:
        model = JClass('com.hankcs.hanlp.model.perceptron.model.LinearModel')(
            msr_model)
    pre = None
    scores = []
    for c in ratios:
        if pre:
            print('以压缩比{}压缩模型中...'.format(c))
            model.compress(1 - (1 - c) / pre, 0)
        pre = 1 - c
        result = CWSEvaluator.evaluate(
            PerceptronLexicalAnalyzer(model).enableCustomDictionary(False),
            msr_test, msr_output, msr_gold, msr_dict)
        # scores.append(result.F1)
        scores.append(float(str(result).split()[2][3:]))
    return scores
Esempio n. 29
0
def getOptionalInstance(x):
    if type(x) is list:
        internalObjects = list(getOptionalInstance(thing) for thing in x)
        className = JClass(internalObjects[0].getClass().getName())
        retVal = JArray(className, 1)(internalObjects)
        return retVal

    if type(x) is dict:
        # local import necessary to avoid a circular dependency - import it when you need it
        from blnx.java.util.HashMap import JHashMap
        hashMap = JHashMap()
        for key,value in x.items():
            hashMap.put(key, getOptionalInstance(value))
        return hashMap



    if hasattr(x, 'instance'):
        return x.instance
    else:
        return x
Esempio n. 30
0
class PdfJar(object):
    def __init__(self):
        self.log = Log().get_logger()
        self.path = r'C:\AProjectCode\Python\python3_interface\study_case\data\开发指南.pdf'
        self.out_path = r'C:\AProjectCode\Python\python3_interface\study_case\data\开发指南.txt'

    def startJvm(self):
        return JVMStart().start_jvm(['pdfbox-app-2.0.12.jar'])

    def get_java_objecj(self):
        self.file = JClass("java.io.File")
        self.FileOutputStream = JClass("java.io.FileOutputStream")
        self.OutputStreamWriter = JClass("java.io.OutputStreamWriter")
        self.Writer = JClass("java.io.Writer")
        self.PDDocument = JClass("org.apache.pdfbox.pdmodel.PDDocument")
        self.PDFTextStripper = JClass("org.apache.pdfbox.text.PDFTextStripper")

    def get_txt(self):
        try:
            self.get_java_objecj()
            input = self.file(self.path)  # 转换文件为File类型
            document = self.PDDocument.load(input)  # 加载pdf文件
            outputStream = self.FileOutputStream(self.out_path)
            output = self.OutputStreamWriter(outputStream, 'UTF-8')  # 文件输出流
            stripper = self.PDFTextStripper()  #  PDFTextStripper来提取文本
            stripper.setSortByPosition(False)  # 设置是否排序
            stripper.setStartPage(1)  # 设置起始页
            stripper.setEndPage(100000)  # 设置结束页
            stripper.writeText(document,
                               output)  # 调用PDFTextStripper的writeText提取并输出文本
            self.log.info(stripper.getText(document))  # 直接获取text

            output.close()  # 关闭输出流
            document.close()
        except Exception as e:
            self.log.error('出现异常:%s' % e)

    def shutdownJVM(self):
        JVMStart().shutdown_jvm()
Esempio n. 31
0
    def load_jar_class(jar_path, class_name):
        """
        Load a class at runtime directly from a jar file.
        Note that with some libraries this can cause problems because the library
        will not be *visible* to the default class loader.

        :param jar_path: Path to the `.jar` file.
        :param class_name: The fully qualified Class Name within the jar to load.
        :return:
        """
        URL = JClass('java.net.URL')
        URLClassLoader = JClass('java.net.URLClassLoader')
        Class = JClass('java.lang.Class')
        UrlArray = JArray(URL)
        urls = UrlArray(1)
        urls[0] = get_url(jar_path)
        java_class = JClass(Class.forName(class_name, True, URLClassLoader(urls)))
        return java_class
Esempio n. 32
0
 def get_model(self):
     if not self.jena_model:
         klass = JClass(self._jena_pkg_name+'.rdf.model.ModelFactory')
         self.jena_model = klass.createDefaultModel()
     return self.jena_model
Esempio n. 33
0
 def _new_submodel(self):
     model = JClass('com.hp.hpl.jena.rdf.model.ModelFactory').createDefaultModel()
     model = model.setNsPrefixes(self.jena_model.getNsPrefixMap())
     return model
    exp_uvs = []
    for i in xrange(len(xs)):
        xy = np.array((xs[i], ys[i]), dtype=np.double)
        uv = timoBeam.displacement(xy[0], xy[1], 0, None)
        if is_vs:
            exp_uvs.append(uv[1])
        else:
            exp_uvs.append(uv[0])
    if None is axis:
        axis = xs
    ax.plot(axis, act_uvs, "r", label="Numerical")
    ax.plot(axis, exp_uvs, "b", label="Precise")


if __name__ == "__main__":
    WeakformProcessor2D = JClass("net.epsilony.tsmf.process.WeakformProcessor2D")
    processor = WeakformProcessor2D.genTimoshenkoProjectProcess()
    processor.process()
    processor.solve()
    pp = processor.postProcessor()
    fig = plt.figure()

    ax = fig.add_subplot(221)
    ax.set_title("displacement $v$ along axis $x$ ($y=0$)")
    ax.set_xlabel("$x$")
    ax.set_ylabel("$v(x,0)$")

    y = 0
    plot_vs_by_y(pp, ax, y)
    ax2 = fig.add_subplot(222)
    ax2.set_title("displacement $u$\n along the left edge ($x=0$)")
Esempio n. 35
0
#!/usr/bin/env python3

from jpype import  startJVM, getDefaultJVMPath, JClass

startJVM(getDefaultJVMPath(), '-Djava.class.path=c:/tools/lucene-1.4.3/lucene-1.4.3.jar')

QueryParser = JClass("org.apache.lucene.queryParser.QueryParser")
IndexSearcher = JClass("org.apache.lucene.search.IndexSearcher")
IndexReader = JClass("org.apache.lucene.index.IndexReader")
StandardAnalyzer = JClass("org.apache.lucene.analysis.standard.StandardAnalyzer")
FSDirectory = JClass("org.apache.lucene.store.FSDirectory")
IndexWriter = JClass("org.apache.lucene.index.IndexWriter")
SimpleAnalyzer = JClass("org.apache.lucene.analysis.SimpleAnalyzer")

IndexWriter('c:/temp/lucene', SimpleAnalyzer(), True).close()

directory = FSDirectory.getDirectory("c:/temp/lucene", False)
reader = IndexReader.open(directory)
searcher = IndexSearcher(reader)
queryparser = QueryParser.parse("wenger", "contents", StandardAnalyzer())
print(queryparser.rewrite)
print(queryparser.rewrite.matchReport(reader))
qp = queryparser.rewrite(reader)
print(qp)
print(searcher.search.matchReport(qp))
hits = searcher.search(qp)
Esempio n. 36
0
def plot_jpolygon(pg, ax, *args, **kwds):
    vertes = pg.getVertes()
    xys = []
    codes = []
    for act_vs in vertes:
        atBegin = True
        for nd in act_vs:
            xys.append(nd.coord)
            if atBegin:
                codes.append(Path.MOVETO)
                atBegin = False
            else:
                codes.append(Path.LINETO)
        codes.append(Path.CLOSEPOLY)
        xys.append((0, 0))
    pp = PathPatch(Path(xys, codes), *args, **kwds)
    ax.add_patch(pp)
    
if __name__ == "__main__":
    from terse_demo.util.jvm_util import start_jvm
    from jpype import JClass
    start_jvm()
    JTestTool = JClass('net.epsilony.tsmf.util.TestTool')
    pg = JTestTool.samplePolygon(None)
    from matplotlib import pyplot as plt
    fig = plt.figure()
    ax = fig.add_subplot(111)
    plot_jpolygon(pg, ax)
    fig.show()