当前位置: 首页>>代码示例>>Python>>正文


Python lang.String类代码示例

本文整理汇总了Python中java.lang.String的典型用法代码示例。如果您正苦于以下问题:Python String类的具体用法?Python String怎么用?Python String使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


在下文中一共展示了String类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: checkInbox

def checkInbox():
    for message in voice.sms().messages:
        if not message.isRead:
            n=message.phoneNumber
            msgtxt = str(message.messageText)
            txtarray = msgtxt.split(" ")
            print txtarray
            
            if len(txtarray) > 2:
                e = String(txtarray[0])
                #print e
                key = txtarray[1]
                #print key
                code = ' '.join([str(x) for x in txtarray[2:len(txtarray)]])
                #print code
                if e.equalsIgnoreCase("encode"):
                    coded = encrypt(code, key)
                    #print "Coded message"
                    if len(coded) < 140:
                        postToTwitter(coded)
                        returnText(n, "Posted to Twitter: "+coded)
                    else:
                        returnText(n, "Coded message too long")
                elif e.equalsIgnoreCase("decode"):
                    uncoded = decrypt(code, key)
                    #print "Decoded message"
                    returnText(n, "Uncoded text: "+uncoded)
                else:
                    returnText(n, "Unable to parse input text message")
            message.delete()            
    time.sleep(10)
开发者ID:ckohnke,项目名称:SmokeSignals,代码行数:31,代码来源:SmokeSignals.py

示例2: __activate__

    def __activate__(self, context):
        # Prepare variables
        self.index = context["fields"]
        self.object = context["object"]
        self.payload = context["payload"]
        self.params = context["params"]
        self.utils = context["pyUtils"]
        self.config = context["jsonConfig"]
        self.wfSecurityExceptions = None
        self.message_list = None

        # Because the workflow messaging system wants access to this data
        #  BEFORE it actual hits the index we are going to cache it into an
        #  object payload too.
        self.directIndex = JsonSimple()

        # Common data
        self.__newDoc()
        #print "+++ direct-files.py - itemType='%s'" % self.itemType

        # Real metadata
        if self.itemType == "object":
            self.__previews()
            self.__basicData()
            self.__metadata()
            # Update the 'direct.index' payload - BEFORE messages are sent
            directString = String(self.directIndex.toString())
            inStream = ByteArrayInputStream(directString.getBytes("UTF-8"))
            try:
                StorageUtils.createOrUpdatePayload(self.object, "direct.index", inStream)
            except StorageException, e:
                print " * direct-files.py : Error updating direct payload"
            self.__messages()
            self.__displayType()
开发者ID:the-fascinator-contrib,项目名称:builds-media-repository,代码行数:34,代码来源:direct-files.py

示例3: test_store_creation

    def test_store_creation(self):

        from com.hp.hpl.jena.tdb import TDBFactory
        from java.io import ByteArrayInputStream
        from java.lang import String

        db_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'OAC-testing.tdb')
        dataset = TDBFactory.createDataset(db_path)
        # Make sure the store was created
        assert os.path.isdir(db_path)

        # Make InputStream triples
        rdf_text = '<rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"><rdf:Description rdf:about="info:fedora/changeme:651"><rdf:type rdf:resource="oa:Annotation"></rdf:type><oa:hasBody xmlns:oa="http://www.w3.org/ns/openannotation/core/" rdf:resource="info:fedora/changeme:650"></oa:hasBody><oa:modelVersion xmlns:oa="http://www.w3.org/ns/openannotation/core/" rdf:resource="http://www.openannotation.org/spec/core/20120509.html"></oa:modelVersion><oa:generated xmlns:oa="http://www.w3.org/ns/openannotation/core/">2012-06-07T03:50:55.993000Z</oa:generated></rdf:Description><rdf:Description rdf:about="info:fedora/changeme:650"><rdf:type rdf:resource="oa:Body"></rdf:type><dc:format xmlns:dc="http://purl.org/dc/elements/1.1/">text/xml</dc:format></rdf:Description></rdf:RDF>'
        rdfxml = String(rdf_text)
        input_stream = ByteArrayInputStream(rdfxml.getBytes())

        model = dataset.getDefaultModel()
        model.begin()
        model.read(input_stream, None)
        model.commit()
        model.close()
        # Were all of the triples added?
        assert model.size() == 6

        shutil.rmtree(db_path)
        # Was the store removed?
        assert not os.path.isdir(db_path)
开发者ID:Brown-University-Library,项目名称:oac_web_service,代码行数:27,代码来源:test_store.py

示例4: test_null_pointer_exception

 def test_null_pointer_exception(self):
     try:
         # throws http://stackoverflow.com/questions/3131865/why-does-string-valueofnull-throw-a-nullpointerexception
         String.valueOf(None)
     except Exception as ex:
         # because it's not a checked exception, mapped exceptions doesn't apply here (all Runtime)            
         self.assertIn('java.lang.NullPointerException', str(ex.message))
开发者ID:bsteffensmeier,项目名称:jep,代码行数:7,代码来源:test_exceptions.py

示例5: getDistributors

 def getDistributors(self,oshv,sqlServerId):
     #is there is a chance that we have more than one distributor?
     rs = self.connection.doCall(Queries.SERVER_DIST_CALL)
     distributor = None
     databaseName = None
     while rs.next():
         name = rs.getString('distributor')
         if(name is None):
             rs.close()
             return None
         databaseName = rs.getString('distribution database')
         max = int(rs.getInt('max distrib retention'))
         min = int(rs.getInt('min distrib retention'))
         history = int(rs.getInt('history retention'))
         cleanup = String(rs.getString('history cleanup agent'))
         idx = cleanup.indexOf('Agent history clean up:')
         if(idx>=0):
             cleanup=cleanup.substring(len("Agent history clean up:"))
         distributor = ObjectStateHolder('sqlserverdistributor')
         sqlServer = self.createSqlServer(name,oshv,sqlServerId)
         distributor.setContainer(sqlServer)
         distributor.setAttribute(Queries.DATA_NAME,name)
         distributor.setIntegerAttribute('maxTxRetention',max)
         distributor.setIntegerAttribute('minTxRetention',min)
         distributor.setIntegerAttribute('historyRetention',history)
         distributor.setAttribute('cleanupAgentProfile',cleanup)
         oshv.add(sqlServer)
         oshv.add(distributor)        
         database = self.getDatabase(sqlServer,databaseName)
         oshv.add(database)
         oshv.add(modeling.createLinkOSH('use',distributor,database))
     rs.close()
     if(distributor!=None):
         logger.debug('we got a distributor')
     return [distributor,databaseName]
开发者ID:ddonnelly19,项目名称:dd-git,代码行数:35,代码来源:ClusterConfiguration.py

示例6: __saveManifest

 def __saveManifest(self, oid):
     object = self.services.getStorage().getObject(oid)
     sourceId = object.getSourceId()
     manifestStr = String(self.__manifest.toString())
     object.updatePayload(sourceId,
                          ByteArrayInputStream(manifestStr.getBytes("UTF-8")))
     object.close()
开发者ID:Paul-Nguyen,项目名称:mint,代码行数:7,代码来源:nameAuthority.py

示例7: __formData

    def __formData(self):
        # Find our workflow form data
        packagePid = None
        try:
            self.pidList = self.object.getPayloadIdList()
            for pid in self.pidList:
                if pid.endswith(self.packagePidSuffix):
                    packagePid = pid
        except StorageException:
            self.log.error("Error accessing object PID list for object '{}' ", self.oid)
            return
        if packagePid is None:
            self.log.debug("Object '{}' has no form data", self.oid)
            return

        # Retrieve our form data
        workflowData = None
        try:
            payload = self.object.getPayload(packagePid)
            try:
                workflowData = JsonSimple(payload.open())
            except Exception:
                self.log.error("Error parsing JSON '{}'", packagePid)
            finally:
                payload.close()
        except StorageException:
            self.log.error("Error accessing '{}'", packagePid)
            return

        # Test our version data
        self.version = workflowData.getString("{NO VERSION}", ["redbox:formVersion"])
        oldData = String(workflowData.toString(True))
        if self.version != self.redboxVersion:
            self.log.info("OID '{}' requires an upgrade: '{}' => '{}'", [self.oid, self.version, self.redboxVersion])
            # The version data is old, run our upgrade
            #   function to see if any alterations are
            #   required. Most likely at least the
            #   version number will change.
            newWorkflowData = self.__upgrade(workflowData)
        else:
            newWorkflowData = self.__hotfix(workflowData)
            if newWorkflowData is not None:
                self.log.debug("OID '{}' was hotfixed for v1.2 'dc:type' bug", self.oid)
            else:
                self.log.debug("OID '{}' requires no work, skipping", self.oid)
                return

        # Backup our data first
        backedUp = self.__backup(oldData)
        if not backedUp:
            self.log.error("Upgrade aborted, data backup failed!")
            return

        # Save the newly modified data
        jsonString = String(newWorkflowData.toString(True))
        inStream = ByteArrayInputStream(jsonString.getBytes("UTF-8"))
        try:
            self.object.updatePayload(packagePid, inStream)
        except StorageException, e:
            self.log.error("Error updating workflow payload: ", e)
开发者ID:andrewbrazzatti,项目名称:redbox-core-dev-build,代码行数:60,代码来源:redboxMigration1.5.py

示例8: __init__

    def __init__(self, Framework):
        Netlinks_Service.NetlinksService.__init__(self, Framework)
        shouldIgnoreLocal = self.getParameterValue('ignoreLocalConnections')
        if shouldIgnoreLocal == None:
            shouldIgnoreLocal = 'false'
        self.ignoreLocalConnections = Boolean.parseBoolean(shouldIgnoreLocal)
        self.dependencyNameIsKey = modeling.checkIsKeyAttribute('dependency', 'dependency_name')
        self.dependencySourceIsKey = modeling.checkIsKeyAttribute('dependency', 'dependency_source')
        ignoredIpsList = self.getParameterValue('ignoredIps')
        self.ignoredIps = None
        if ignoredIpsList != None:
            ipPatterns = ignoredIpsList.split(',')
            if (len(ipPatterns) > 0) and (ipPatterns[0] != ''):
                for ipPattern in ipPatterns:
                    pattern = String(ipPattern)
                    pattern = String(pattern.replaceAll("\.", "\\\."))
                    pattern = String(pattern.replaceAll("\*", "\\\d+"))
                    try:
                        m = Pattern.compile(pattern)
                        if self.ignoredIps == None:
                            self.ignoredIps = ArrayList()
                        self.ignoredIps.add(m)
                    except:
                        logger.debug('Failed to compile ip pattern:', ipPattern)


        self.initializeServices()
开发者ID:ddonnelly19,项目名称:dd-git,代码行数:27,代码来源:Netlinks_Services.py

示例9: __call__

    def __call__(self):
        """
        A Python object is callable if it defines a __call__ method. Each worker thread performs a
        number of runs of the test script, as configured by the property grinder.runs. For each run,
        the worker thread calls its TestRunner; thus the __call__ method can be thought of as the
        definition of a run.
        """

        # Normally test results are reported automatically when the test returns. If you want to
        # alter the statistics after a test has completed, you must set delayReports = 1 to delay
        # the reporting before performing the test. This only affects the current worker thread.
        grinder.statistics.delayReports = 1

        msg = te_message.Message(
            "1.0", "20111020153610", 200, None, "GPE-111", 111, "OPERATOR-111", "00000000001", None, request_msgbody
        )
        # print("******hello" + str(type(msg)))
        # print("msg.raw_body" + msg.raw_body)
        # print("des:" + msg.encrypted_body)
        body = String(msg.encrypted_body)
        response = request.POST(CONF_url, body.getBytes(), msg.assemble_nvpairs())

        code = int(response.getHeader("X-Response-Code"))
        # verify response status
        if 200 != code:
            print("------------------------------------ERROR: %d" % code)
            # Set success = 0 to mark the test as a failure.
            grinder.statistics.forLastTest.setSuccess(0)
        else:
            print("------------------------------------PASS!")
开发者ID:ramonli,项目名称:eGame_TE,代码行数:30,代码来源:test_lotto_sale.py

示例10: getTFPackagePid

 def getTFPackagePid(self,oid):
     digitalObject = StorageUtils.getDigitalObject(self.storage,oid)
     for pid in digitalObject.getPayloadIdList():
         pidString = String(pid)
         if pidString.endsWith("tfpackage"):
             return pid
     return None 
开发者ID:ozej8y,项目名称:redbox,代码行数:7,代码来源:get.py

示例11: read_methods

def read_methods(file):
   names = {}
   for line in file:
      nline = line.strip()
      jstr = String(nline)
      hcode = jstr.hashCode()
      names[hcode] = nline
   return names
开发者ID:lucadt,项目名称:memoizeit,代码行数:8,代码来源:depths.py

示例12: test_null_pointer_exception

 def test_null_pointer_exception(self):
     try:
         # throws http://stackoverflow.com/questions/3131865/why-does-string-valueofnull-throw-a-nullpointerexception
         String.valueOf(None)
     except Exception as ex:
         # because it's not a checked exception, mapped exceptions doesn't apply here (all Runtime)
         if not jep.USE_MAPPED_EXCEPTIONS:
             self.assertEquals(ex.java_name, 'java.lang.NullPointerException')
开发者ID:Kroisse,项目名称:jep,代码行数:8,代码来源:test_exceptions.py

示例13: sortResultsByCode

 def sortResultsByCode(self):
     tempMap = HashMap()
     for result in self.__results:
         uri = String(self.getValue(result, "dc_identifier"))
         lastIndex = uri.lastIndexOf('/') + 1 
         code = uri.substring(lastIndex)
         tempMap.put(code, result)
     self.resultsByCode = TreeMap(tempMap)
开发者ID:Paul-Nguyen,项目名称:mint,代码行数:8,代码来源:lookup.py

示例14: _getXmlRootFromString

 def _getXmlRootFromString(self, xmlString):
     """
     Parses string xml representation and returns root element
     str->Element
     @raise JavaException: XML parsing failed
     """
     xmlString = ''.join([line.strip() for line in xmlString.split('\n') if line])
     strContent = String(xmlString)
     return SAXBuilder().build(ByteArrayInputStream(strContent.getBytes('utf-8'))).getRootElement()
开发者ID:ddonnelly19,项目名称:dd-git,代码行数:9,代码来源:sharepoint_win_shell.py

示例15: __saveWorkflowMetadata

 def __saveWorkflowMetadata(self, oid):
     object = self.services.getStorage().getObject(oid)
     manifestStr = String(self.__workflowMetadata.toString())
     object.updatePayload("workflow.metadata",
                          ByteArrayInputStream(manifestStr.getBytes("UTF-8")))
     object.close()
     
     self.__indexer.index(oid)
     self.__indexer.commit()
开发者ID:redbox-mint-contrib,项目名称:z-defunct-lacs,代码行数:9,代码来源:nameAuthority.py


注:本文中的java.lang.String类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。