Example #1
0
def pRarams(context, flute, request):

    response = LinkedHashMap()
    text = request.path()
    status = None

    if request.queryParams().size() != 0:
        text = text + "?"

        params = request.queryParams().toSingleValueMap()
        theFirst = True

        for key in params.keySet():
            if theFirst != True:
                text = text + "&"
            text = text + key + "=" + params.get(key)
            theFirst = False

        status = 200
    else:
        text = "there are no params received"
        status = 422

    response.put('text', text)
    response.put('status', status)

    return ServerResponse.status(HttpStatus.valueOf(status))\
        .body(Mono.just(text), String)
    def getSuggestedNames(self):
        # search common forms
        lookupNames = []
        surname = self.__metadata.getList("surname").get(0)
        firstName = self.__metadata.getList("firstName").get(0)
        firstInitial = firstName[0].upper()
        secondName = self.__metadata.getList("secondName")
        if not secondName.isEmpty():
            secondName = secondName.get(0)
        if secondName and secondName != "":
            secondInitial = secondName[0].upper()
            lookupNames.append("%s, %s. %s." % (surname, firstInitial, secondInitial))
            lookupNames.append("%s, %s %s." % (surname, firstName, secondInitial))
            lookupNames.append("%s, %s %s" % (surname, firstName, secondName))
            lookupNames.append("%s %s %s" % (firstName, secondName, surname))
        lookupNames.append("%s, %s." % (surname, firstInitial))
        lookupNames.append("%s, %s" % (surname, firstName))
        lookupNames.append("%s %s" % (firstName, surname))
        query = '" OR dc_title:"'.join(lookupNames)

        # general word search from each part of the name
        parts = [p for p in self.getPackageTitle().split(" ") if len(p) > 0]
        query2 = " OR dc_title:".join(parts)

        req = SearchRequest('(dc_title:"%s")^2.5 OR (dc_title:%s)^0.5' % (query, query2))
        self.log.info("suggestedNames query={}", req.query)
        req.setParam("fq", 'recordtype:"author"')
        req.addParam("fq", 'item_type:"object"')
        req.setParam("rows", "9999")
        req.setParam("fl", "score")
        req.setParam("sort", "score desc")

        # Make sure 'fq' has already been set in the session
        ##security_roles = self.authentication.get_roles_list();
        ##security_query = 'security_filter:("' + '" OR "'.join(security_roles) + '")'
        ##req.addParam("fq", security_query)

        out = ByteArrayOutputStream()
        indexer = self.services.getIndexer()
        indexer.search(req, out)
        result = JsonConfigHelper(ByteArrayInputStream(out.toByteArray()))

        # self.log.info("result={}", result.toString())
        docs = result.getJsonList("response/docs")

        map = LinkedHashMap()
        for doc in docs:
            authorName = doc.getList("dc_title").get(0)
            if map.containsKey(authorName):
                authorDocs = map.get(authorName)
            else:
                authorDocs = ArrayList()
                map.put(authorName, authorDocs)
            authorDocs.add(doc)

        self.__maxScore = max(1.0, float(result.get("response/maxScore")))

        return map
Example #3
0
class ErrorResolver:
    "Resolves errors to error configs"

    def __init__(self, data=None):
        #list of keys is maintained in order to ensure the
        #predictable iteration order
        self.configsMap = LinkedHashMap()
        if data:
            self.configsMap.putAll(data)
        self.initDefaultConfigs()

    def addConfig(self, pattern, config):
        self.configsMap.put(pattern, config)

    def hasConfig(self, msg):
        iterator = self.configsMap.keySet().iterator()
        while iterator.hasNext():
            pattern = iterator.next()
            if re.search(pattern, msg, re.I | re.M):
                return 1

    def getConfig(self, msg):
        iterator = self.configsMap.keySet().iterator()
        while iterator.hasNext():
            pattern = iterator.next()
            if re.search(pattern, msg, re.I | re.M):
                return self.configsMap.get(pattern)

    def getDefaultConfig(self):
        return self.defaultConfig

    def copy(self):
        return ErrorResolver(self.configsMap)

    def __len__(self):
        return self.configsMap.size()

    def __getitem__(self, key):
        return self.configsMap.get(key)

    def __setitem__(self, key, item):
        self.addConfig(key, item)

    def keys(self):
        return self.configsMap.keySet()

    def initDefaultConfigs(self):
        self.defaultConfigWithDetails = ErrorMessageConfig(
            ERROR_GENERIC_WITH_DETAILS,
            errorcodes.INTERNAL_ERROR_WITH_PROTOCOL_DETAILS)
        self.defaultConfig = ErrorMessageConfig(ERROR_CONNECTION_FAILED,
                                                errorcodes.CONNECTION_FAILED)
        self.defaultConfigNoProtocol = ErrorMessageConfig(
            ERROR_CONNECTION_FAILED_NO_PROTOCOL,
            errorcodes.CONNECTION_FAILED_NO_PROTOCOL)
        self.defaultConfigNoProtocolWithDetails = ErrorMessageConfig(
            ERROR_CONNECTION_FAILED_NO_PROTOCOL_WITH_DETAILS,
            errorcodes.CONNECTION_FAILED_NO_PROTOCOL_WITH_DETAILS)
Example #4
0
def pyDictToJavaMap(pyDict):
    if isinstance(pyDict, OrderedDict):
        jmap = LinkedHashMap()
    else:
        jmap = HashMap()
        
    for key in pyDict:   
        jmap.put(pyValToJavaObj(key), pyValToJavaObj(pyDict[key]))
    return jmap
Example #5
0
 def getFacetCounts(self, key):
     values = LinkedHashMap()
     valueList = self.__result.getList("facet_counts/facet_fields/%s" % key)
     for i in range(0,len(valueList),2):
         name = valueList[i]
         count = valueList[i+1]
         if count > 0:
             values.put(name, count)
     return values
Example #6
0
 def getFacetCounts(self, key):
     values = LinkedHashMap()
     valueList = self.__result.getList("facet_counts/facet_fields/%s" % key)
     for i in range(0,len(valueList),2):
         name = valueList[i]
         count = valueList[i+1]
         if (name.find("/") == -1 or self.hasSelectedFacets()) and count > 0:
             values.put(name, count)
     return values
Example #7
0
 def getFacetCounts(self, key):
     values = LinkedHashMap()
     valueList = self.__result.getList("facet_counts/facet_fields/%s" % key)
     for i in range(0,len(valueList),2):
         name = valueList[i]
         count = valueList[i+1]
         if count > 0:
             values.put(name, count)
     return values
Example #8
0
def parseSat(satdirs):
    rval = LinkedHashMap()
    for e in satdirs:
        if type(e) is types.TupleType:
            direct, name = check(e, (str, str),
              "Format error in SATDIRS entry", satdirs)
            rval.put(direct, name)
        else:
            raise SyntaxError, "Invalid syntax for SATDIRS" + `satdirs`
    return rval
Example #9
0
def parseSat(satdata):
    rval = LinkedHashMap()
    for e in satdata:
        if type(e) is types.TupleType:
            direct, name = check(e, (str, str),
                                 "Format error in SATDATA entry", satdata)
            rval.put(direct, name)
        else:
            raise SyntaxError, "Invalid syntax for SATDATA" + ` satdata `
    return rval
Example #10
0
def dictCheck(dictionary, value, subvalue, configName):
    map = LinkedHashMap()
    if type(dictionary) == dict:
        for k in dictionary.keys():
            if type(k) != str:
                raise TypeError, configName + " key [" + `k` + "] not a str"
            l = dictionary[k]
            if type(l) != value:
                raise TypeError, configName + " value [" + `l` + "] not a " \
                  + `value`
            if value == list or value == tuple:
                n = ArrayList()
                for m in l:
                    if type(m) != subvalue:
                        raise TypeError, configName + " value [" + `l` \
                          + "] isn't a " + `subvalue` + ": " + `m`
                    elif subvalue == int:
                        n.add(Integer(m))
                    elif subvalue == float:
                        n.add(Float(m))
                    else:
                        n.add(m)
                map.put(k, n)
            else:
                if value == int:
                    map.put(k,Integer(l))
                elif value == float:
                    map.put(k,Float(l))
                else:
                    map.put(k, l)
    else:
        raise TypeError, configName + " not a dict:" + `dictionary`
    return map
Example #11
0
def dictCheck(dictionary, value, subvalue, configName):
    map = LinkedHashMap()
    if type(dictionary) == dict:
        for k in dictionary.keys():
            if type(k) != str:
                raise TypeError, configName + " key [" + ` k ` + "] not a str"
            l = dictionary[k]
            if type(l) != value:
                raise TypeError, configName + " value [" + `l` + "] not a " \
                  + `value`
            if value == list or value == tuple:
                n = ArrayList()
                for m in l:
                    if type(m) != subvalue:
                        raise TypeError, configName + " value [" + `l` \
                          + "] isn't a " + `subvalue` + ": " + `m`
                    elif subvalue == int:
                        n.add(Integer(m))
                    elif subvalue == float:
                        n.add(Float(m))
                    else:
                        n.add(m)
                map.put(k, n)
            else:
                if value == int:
                    map.put(k, Integer(l))
                elif value == float:
                    map.put(k, Float(l))
                else:
                    map.put(k, l)
    else:
        raise TypeError, configName + " not a dict:" + ` dictionary `
    return map
Example #12
0
 def getDbUsers(self,sqlServer):
     rs = self.connection.getTable(Queries.SERVER_USERS)
     users = LinkedHashMap()
     while rs.next():
         login = rs.getString('loginname').strip()
         status = rs.getString('status')
         createDate= rs.getTimestamp('createdate')
         user = ObjectStateHolder('dbuser')
         user.setAttribute(Queries.DATA_NAME,login)
         user.setAttribute('dbuser_created',createDate)
         user.setAttribute('dbuser_accountstatus',status)
         user.setContainer(sqlServer)
         users.put(login,user)
     rs.close()
     return users
Example #13
0
def pyDictToJavaMap(pyDict):
    '''
    Going forward should use pyValToJavaObj instead.
    '''
    if pyDict is None:
        return None

    if isinstance(pyDict, OrderedDict):
        jmap = LinkedHashMap()
    else:
        jmap = HashMap()

    for key in pyDict:
        jmap.put(pyValToJavaObj(key), pyValToJavaObj(pyDict[key]))
    return jmap
Example #14
0
 def getDatabases(self,root):
     result = LinkedHashMap()
     rs = self.connection.getTable("SELECT name,crdate as createDate FROM master..sysdatabases")
     logger.debug('in get databases for root: ', root.toString())
     while rs.next():
         database = ObjectStateHolder("sqldatabase")
         database.setContainer(root)
         dbName = rs.getString("name")
         createDate = rs.getTimestamp("createDate")
         if createDate:
             database.setAttribute("createdate", Util.getSqlDateInGMT(createDate.getTime()))
             database.setAttribute("created_at", createDate)
         database.setAttribute(Queries.DATA_NAME,dbName)
         result.put(dbName,database)
     rs.close()
     return result
Example #15
0
def d2dParse(d2dmodels):
    dict = LinkedHashMap()
    for entry in d2dmodels:
        if type(entry) is types.TupleType:
            d2dModelName, gfeModelName = check(entry, (str, str),
              "Format error in D2DMODELS entry", d2dmodels)

            dict.put(d2dModelName, gfeModelName)

        elif type(entry) is types.StringType:
            d2dModelName = entry
            dict.put(d2dModelName, d2dModelName)

        else:
            raise SyntaxError, "Invalid syntax for D2DMODELS" + `d2dmodels`

    return dict
Example #16
0
    def buildPostDataFortoken(self, encodedJWT, softwareStatementId) :
		postParameters = LinkedHashMap()
		postParameters.put("scope", self.clientScopes)
		postParameters.put("client_assertion_type", "urn:ietf:params:oauth:client-assertion-type:jwt-bearer")
		postParameters.put("grant_type", "client_credentials")
		postParameters.put("client_id", softwareStatementId)
		postParameters.put("client_assertion", encodedJWT)

		postData = StringBuilder()
		for param in postParameters.entrySet():
			if postData.length() != 0:
				postData.append('&')
			postData.append(URLEncoder.encode(param.getKey(), "UTF-8"))
			postData.append('=')
			postData.append(URLEncoder.encode(String(param.getValue()), "UTF-8").replace("+", "%20"))
		print "Post data: "+postData.toString()
		return postData.toString()
Example #17
0
def d2dParse(d2dmodels):
    dict = LinkedHashMap()
    for entry in d2dmodels:
        if type(entry) is types.TupleType:
            d2dModelName, gfeModelName = check(
                entry, (str, str), "Format error in D2DMODELS entry",
                d2dmodels)

            dict.put(d2dModelName, gfeModelName)

        elif type(entry) is types.StringType:
            d2dModelName = entry
            dict.put(d2dModelName, d2dModelName)

        else:
            raise SyntaxError, "Invalid syntax for D2DMODELS" + ` d2dmodels `

    return dict
    def buildImagesCSVTable(fileName, logger):

        # Initialize the table
        csvTable = LinkedHashMap()

        # Header
        isHeader = True

        # Read the CSV file
        br = BufferedReader(FileReader(fileName))

        # Read the first line from the text file
        line = br.readLine()

        # loop until all lines are read
        while line is not None:

            if isHeader:

                # We are past the header
                isHeader = False

                # Read next line
                line = br.readLine()

                continue

            # Get all values for current row
            row = line.split(";")

            # Remove '"' and '\' characters if needed
            for i in range(len(row)):
                row[i] = row[i].replace("\"", "")
                row[i] = row[i].replace("\\\\", "\\")
                row[i] = row[i].replace("\\", "/")

            # Add the row with the file name as key
            csvTable.put(row[6], row)

            # Read next line
            line = br.readLine()

        return csvTable
    def buildImagesCSVTable(fileName, logger):

        # Initialize the table
        csvTable = LinkedHashMap()

        # Header
        isHeader = True

        # Read the CSV file
        br = BufferedReader(FileReader(fileName))

        # Read the first line from the text file
        line = br.readLine()

        # loop until all lines are read 
        while line is not None:

            if isHeader:

                # We are past the header
                isHeader = False

                # Read next line 
                line = br.readLine()

                continue

            # Get all values for current row
            row = line.split(";")

            # Remove '"' and '\' characters if needed
            for i in range(len(row)):
                row[i] = row[i].replace("\"", "")
                row[i] = row[i].replace("\\\\", "\\")
                row[i] = row[i].replace("\\", "/")

            # Add the row with the file name as key
            csvTable.put(row[6], row)

            # Read next line 
            line = br.readLine()

        return csvTable
Example #20
0
class WorkflowsData:
    def __activate__(self, context):
        self.roles = context["page"].authentication.get_roles_list()
        self.config = context["systemConfig"]
        workflows = JsonSimple.toJavaMap(self.config.getObject(["uploader"]))
        self.uploaders = LinkedHashMap()
        
        for workflow in workflows.keySet():
            if workflows.get(workflow).getString("", ["upload-template"]):
                for role in workflows.get(workflow).getArray(["security"]):
                    if str(role) in self.roles:
                        self.uploaders.put(workflow, workflows.get(workflow))
    
    def getUploaders(self):
        return self.uploaders
    
    def getStageInfo(self, workflowId):
        uploader = self.uploaders.get(workflowId)
        config = JsonSimple(File(StrSubstitutor.replaceSystemProperties(uploader.getString("", ["json-config"]))))
        return StageInfo(config.getArray(["stages"]))
Example #21
0
class WorkflowsData:
    def __activate__(self, context):
        self.roles = context["page"].authentication.get_roles_list()
        self.config = context["systemConfig"]
        workflows = JsonSimple.toJavaMap(self.config.getObject(["uploader"]))
        self.uploaders = LinkedHashMap()
        
        for workflow in workflows.keySet():
            if workflows.get(workflow).getString("", ["upload-template"]):
                for role in workflows.get(workflow).getArray(["security"]):
                    if str(role) in self.roles:
                        self.uploaders.put(workflow, workflows.get(workflow))
    
    def getUploaders(self):
        return self.uploaders
    
    def getStageInfo(self, workflowId):
        uploader = self.uploaders.get(workflowId)
        config = JsonSimple(File(StrSubstitutor.replaceSystemProperties(uploader.getString("", ["json-config"]))))
        return StageInfo(config.getArray(["stages"]))
            
Example #22
0
def netcdfParse(netcdfDirs):
    dict = LinkedHashMap()
    for entry in netcdfDirs:
        if type(entry) is types.TupleType:
            direct, modelName = check(entry, (str, str),
              "Format error in NETCDFDIRS entry", netcdfDirs)

            if direct[-1] == '/':
                direct = direct[0:-1]
            dict.put(direct, modelName)

        elif type(entry) is types.StringType:
            direct = entry
            if direct[-1] == '/':
                direct = direct[0:-1]
            dict.put(direct,  '')

        else:
            raise SyntaxError, "Invalid syntax for NETCDFDIRS" + `netcdfDirs`

    return dict
Example #23
0
def random_tick():
    hmm = LinkedHashMap()
    hmm.put("symbol", 'AAPL')
    p = Double(gen.nextInt(18))
    hmm.put("price", p)
    hmm.put("ts", Date(System.currentTimeMillis()))
    return hmm
Example #24
0
def netcdfParse(netcdfDirs):
    dict = LinkedHashMap()
    for entry in netcdfDirs:
        if type(entry) is types.TupleType:
            direct, modelName = check(entry, (str, str),
                                      "Format error in NETCDFDIRS entry",
                                      netcdfDirs)

            if direct[-1] == '/':
                direct = direct[0:-1]
            dict.put(direct, modelName)

        elif type(entry) is types.StringType:
            direct = entry
            if direct[-1] == '/':
                direct = direct[0:-1]
            dict.put(direct, '')

        else:
            raise SyntaxError, "Invalid syntax for NETCDFDIRS" + ` netcdfDirs `

    return dict
Example #25
0
File: refine.py Project: alclp/jCAE
algo.compute();
#MeshWriter.writeObject3D(algo.getOutputMesh(), outDir, String())
if options.recordFile:
	liaison.getMesh().getTrace().finish()

# Now compute beams
bgroupMap = LinkedHashMap()
newMesh = algo.getOutputMesh()
#print "beams size: "+str(mesh.getBeams().size())
for i in xrange(newMesh.getBeams().size() / 2):
	bId = newMesh.getBeamGroup(i)
	listBeamId = bgroupMap.get(bId)
	if listBeamId is None:
		listBeamId = TIntArrayList(100)
		bgroupMap.put(bId, listBeamId)
	listBeamId.add(i)

vertices = ArrayList(newMesh.getBeams())
newMesh.resetBeams()
mapGroupToListOfPolylines = LinkedHashMap()
for bId in bgroupMap.keySet():
	listBeamId = bgroupMap.get(bId)
	listOfPolylines = ArrayList()
	polyline = ArrayList()
	lastVertex = None
	for i in xrange(listBeamId.size()):
		b = listBeamId.get(i) 
		if lastVertex != vertices.get(2*b):
			# New polyline
			polyline = ArrayList()
 def getSuggestedNames(self):
     # search common forms
     lookupNames = []
     surname = self.__metadata.getList("surname").get(0)
     firstName = self.__metadata.getList("firstName").get(0)
     firstInitial = firstName[0].upper()
     secondName = self.__metadata.getList("secondName")
     if not secondName.isEmpty():
         secondName = secondName.get(0)
     if secondName and secondName != "":
         secondInitial = secondName[0].upper()
         lookupNames.append("%s, %s. %s." % (surname, firstInitial, secondInitial))
         lookupNames.append("%s, %s %s." % (surname, firstName, secondInitial))
         lookupNames.append("%s, %s %s" % (surname, firstName, secondName))
         lookupNames.append("%s %s %s" % (firstName, secondName, surname))
     lookupNames.append("%s, %s." % (surname, firstInitial))
     lookupNames.append("%s, %s" % (surname, firstName))
     lookupNames.append("%s %s" % (firstName, surname))
     query = '" OR dc_title:"'.join(lookupNames)
     
     # general word search from each part of the name
     parts = [p for p in self.getPackageTitle().split(" ") if len(p) > 0]
     query2 = " OR dc_title:".join(parts)
     
     #filter out the linked citation
     linkedCitations = self.__manifest.getList("//children//id")
     query3 = ""
     if linkedCitations:
         query3 = " OR ".join(linkedCitations)
         query3 = " AND -id:(%s)" % query3
     
     req = SearchRequest('(dc_title:"%s")^2.5 OR (dc_title:%s)^0.5%s' % (query, query2, query3))
     self.log.info("suggestedNames query={}", req.query)
     req.setParam("fq", 'recordtype:"author"')
     req.addParam("fq", 'item_type:"object"')
     req.setParam("rows", "9999")
     req.setParam("fl", "score")
     req.setParam("sort", "score desc")
     
     # Make sure 'fq' has already been set in the session
     ##security_roles = self.authentication.get_roles_list();
     ##security_query = 'security_filter:("' + '" OR "'.join(security_roles) + '")'
     ##req.addParam("fq", security_query)
     
     out = ByteArrayOutputStream()
     self.__indexer.search(req, out)
     result = JsonConfigHelper(ByteArrayInputStream(out.toByteArray()))
     
     #self.log.info("result={}", result.toString())
     docs = result.getJsonList("response/docs")
     
     exactMatchRecords = LinkedHashMap()
     map = LinkedHashMap()
     
     idList = []
     
     for doc in docs:
         authorName = doc.getList("dc_title").get(0)
         rank = self.getRank(doc.getList("score").get(0))
         id = doc.get("id")
         idList.append(id)
         #try to do automatch
         if float(rank) == 100.00 and self.isModified() == "false":
             if exactMatchRecords.containsKey(authorName):
                 authorMatchDocs = exactMatchRecords.get(authorName)
             else:
                 authorMatchDocs = ArrayList()
                 exactMatchRecords.put(authorName, authorMatchDocs)
             authorMatchDocs.add(doc)
         elif id not in linkedCitations:
             if map.containsKey(authorName):
                 authorDocs = map.get(authorName)
             else:
                 authorDocs = ArrayList()
                 map.put(authorName, authorDocs)
             authorDocs.add(doc)
     
     self.__maxScore = max(1.0, float(result.get("response/maxScore")))
     
     if idList:
         self.__isLinked(idList, map)
     
     # Do not auto save if record is live
     if self.__workflowMetadata.get("modified") == "false":
         self.__autoSaveExactRecord(exactMatchRecords)
     
     return map
Example #27
0
    def getSuggestedNames(self):
        # search common forms
        lookupNames = []
        surname = self.__metadata.getList("surname").get(0)
        firstName = self.__metadata.getList("firstName").get(0)
        firstInitial = firstName[0].upper()
        secondName = self.__metadata.getList("secondName")
        if not secondName.isEmpty():
            secondName = secondName.get(0)
        if secondName and secondName != "":
            secondInitial = secondName[0].upper()
            lookupNames.append("%s, %s. %s." %
                               (surname, firstInitial, secondInitial))
            lookupNames.append("%s, %s %s." %
                               (surname, firstName, secondInitial))
            lookupNames.append("%s, %s %s" % (surname, firstName, secondName))
            lookupNames.append("%s %s %s" % (firstName, secondName, surname))
        lookupNames.append("%s, %s." % (surname, firstInitial))
        lookupNames.append("%s, %s" % (surname, firstName))
        lookupNames.append("%s %s" % (firstName, surname))
        query = '" OR dc_title:"'.join(lookupNames)

        # general word search from each part of the name
        parts = [p for p in self.getPackageTitle().split(" ") if len(p) > 0]
        query2 = " OR dc_title:".join(parts)

        req = SearchRequest('(dc_title:"%s")^2.5 OR (dc_title:%s)^0.5' %
                            (query, query2))
        self.log.info("suggestedNames query={}", req.query)
        req.setParam("fq", 'recordtype:"author"')
        req.addParam("fq", 'item_type:"object"')
        req.setParam("rows", "9999")
        req.setParam("fl", "score")
        req.setParam("sort", "score desc")

        # Make sure 'fq' has already been set in the session
        ##security_roles = self.authentication.get_roles_list();
        ##security_query = 'security_filter:("' + '" OR "'.join(security_roles) + '")'
        ##req.addParam("fq", security_query)

        out = ByteArrayOutputStream()
        indexer = self.services.getIndexer()
        indexer.search(req, out)
        result = JsonConfigHelper(ByteArrayInputStream(out.toByteArray()))

        #self.log.info("result={}", result.toString())
        docs = result.getJsonList("response/docs")

        map = LinkedHashMap()
        for doc in docs:
            authorName = doc.getList("dc_title").get(0)
            if map.containsKey(authorName):
                authorDocs = map.get(authorName)
            else:
                authorDocs = ArrayList()
                map.put(authorName, authorDocs)
            authorDocs.add(doc)

        self.__maxScore = max(1.0, float(result.get("response/maxScore")))

        return map
Example #28
0
else:
	size = 1.0

mtb = MeshTraitsBuilder.getDefault3D()
mtb.addNodeList()
mesh = Mesh(mtb)
MeshReader.readObject3D(mesh, xmlDir)

bgroupMap = LinkedHashMap()
#print "beams size: "+str(mesh.getBeams().size())
for i in xrange(mesh.getBeams().size() / 2):
	bId = mesh.getBeamGroup(i)
	listBeamId = bgroupMap.get(bId)
	if listBeamId is None:
		listBeamId = TIntArrayList(100)
		bgroupMap.put(bId, listBeamId)
	listBeamId.add(i)

vertices = ArrayList(mesh.getBeams())
mesh.resetBeams()
mapGroupToListOfPolylines = LinkedHashMap()
for bId in bgroupMap.keySet():
	listBeamId = bgroupMap.get(bId)
	listOfPolylines = ArrayList()
	polyline = ArrayList()
	lastVertex = None
	for i in xrange(listBeamId.size()):
		b = listBeamId.get(i) 
		if lastVertex != vertices.get(2*b):
			# New polyline
			polyline = ArrayList()
    def __workflow(self):
        # Workflow data
        WORKFLOW_ID = "relay"
        wfChanged = False
        workflow_security = []
        self.message_list = None
        try:
            wfPayload = self.object.getPayload("workflow.metadata")
            wfMeta = self.utils.getJsonObject(wfPayload.open())
            wfPayload.close()

            # Are we indexing because of a workflow progression?
            targetStep = wfMeta.getString(None, ["targetStep"])
            if targetStep is not None and targetStep != wfMeta.getString(None, ["step"]):
                wfChanged = True
                # Step change
                wfMeta.getJsonObject().put("step", targetStep)
                wfMeta.getJsonObject().remove("targetStep")

            # This must be a re-index then
            else:
                targetStep = wfMeta.getString(None, ["step"])

            # Security change
            stages = self.config.getJsonSimpleList(["stages"])
            for stage in stages:
                if stage.getString(None, ["name"]) == targetStep:
                    wfMeta.getJsonObject().put("label", stage.getString(None, ["label"]))
                    self.item_security = stage.getStringList(["visibility"])
                    workflow_security = stage.getStringList(["security"])
                    if wfChanged == True:
                        self.message_list = stage.getStringList(["message"])

            # Form processing
            formData = wfMeta.getObject(["formData"])
            if formData is not None:
                formData = JsonSimple(formData)
            else:
                formData = None
            coreFields = ["title", "creator", "contributor", "description", "format", "creationDate"]
            if formData is not None:
                # Core fields
                title = formData.getStringList(["title"])
                if title:
                    self.titleList = title
                creator = formData.getStringList(["creator"])
                if creator:
                    self.creatorList = creator
                contributor = formData.getStringList(["contributor"])
                if contributor:
                    self.contributorList = contributor
                description = formData.getStringList(["description"])
                if description:
                    self.descriptionList = description
                format = formData.getStringList(["format"])
                if format:
                    self.formatList = format
                creation = formData.getStringList(["creationDate"])
                if creation:
                    self.creationDate = creation
                # Course security - basic
                course = formData.getStringList(["course_code"])
                if course:
                    self.item_security.add(course)
                # Course security - moodle
                moodle_courses = formData.getString(None, ["moodleSecurity"])
                if moodle_courses:
                    moodleList = moodle_courses.split(",")
                    for course in moodleList:
                        if course != "":
                            self.item_security.add(course)
                # Course facets - Peoplesoft
                psMoodle_courses = formData.getString(None, ["psMoodle"])
                if psMoodle_courses:
                    psMoodleList = psMoodle_courses.split(",")
                    for course in psMoodleList:
                        if course != "":
                            self.__indexCourse(course)

                # Non-core fields
                data = formData.getJsonObject()
                for field in data.keySet():
                    if field not in coreFields:
                        data = formData.getStringList([field])
                        if field.startswith("dc_subject."):
                            subjectField = "dc_subject"
                            if self.customFields.has_key(subjectField):
                                subjectList = self.customFields[subjectField]
                                if subjectList:
                                   for subject in subjectList:
                                       data.add(subject)
                            field = subjectField
                        self.customFields[field] = data


        except StorageException, e:
            # No workflow payload, time to create
            wfChanged = True
            wfMeta = JsonSimple()
            wfMetaObj = wfMeta.getJsonObject()
            wfMetaObj.put("id", WORKFLOW_ID)
            wfMetaObj.put("step", "pending")
            wfMetaObj.put("pageTitle", "Camtasia Relay Files - Management")
            
            metaMap = LinkedHashMap();
            if self.relayTitle is not None:
                metaMap.put("title", self.relayTitle);
            if self.relayDescription is not None:
                metaMap.put("description", self.relayDescription);
    
            if not metaMap.isEmpty():
                wfMetaObj.put("formData", metaMap);

            stages = self.config.getJsonSimpleList(["stages"])
            for stage in stages:
                if stage.getString(None, ["name"]) == "pending":
                    wfMetaObj.put("label", stage.getString(None, ["label"]))
                    self.item_security = stage.getStringList(["visibility"])
                    workflow_security = stage.getStringList(["security"])
                    self.message_list = stage.getStringList(["message"])
  return FixedCouponSwap(fixed,floating)

mktInstruments = []
mktValues = []
for i in range(nMats):
  iswap = makeSwap(ccy,mats[i],rates[i],crvName)
  mktInstruments.append(iswap)
  mktValues.append(0.0) # !!! By definition, on-market swaps have zero value

# Market Data Bundle likes maps
from java.util import LinkedHashMap
mapCrvMat = LinkedHashMap()
mapCrvInterp = LinkedHashMap()
mapSensInterp = LinkedHashMap()
aMats = array.array('d',mats) # HashMaps like arrays
mapCrvMat.put(crvName,aMats)
print mapCrvMat.values()
mapCrvInterp.put(crvName,interp)
mapSensInterp.put(crvName,interpSens)

crvFinderDataBundle = IR.MultipleYieldCurveFinderDataBundle(mktInstruments, mktValues,None, mapCrvMat, mapCrvInterp, mapSensInterp)

# The function itself
func = IR.MultipleYieldCurveFinderFunction(crvFinderDataBundle, pvCalc);

# Compute Jacobian Analytically. We could also use FD to approximate the sensitivities from our Calculator
jacobian = IR.MultipleYieldCurveFinderJacobian(crvFinderDataBundle,  sensCalc)

# Choose a root finder
import com.opengamma.math.rootfinding.newton as rootfinders # TODO Ugly warning sent out here
rootFinder = rootfinders.BroydenVectorRootFinder()
Example #31
0
def otherParse(serverhost, mhsid, port,  
  initmodules, accumElem,
  initskips, d2ddbver, logfilepurge, prddir, home,
  extraWEPrec, vtecRequestTime, autoConfigureNotifyTextProd,
  iscRoutingTableAddress, requestedISCsites, requestISC, sendiscOnSave,
  sendiscOnPublish, requestedISCparms, transmitScript):
    if type(serverhost) != str:
        raise TypeError, "GFESUITE_HOST not an str: " + `serverhost`
    if type(mhsid) != str:
        raise TypeError, "GFESUITE_MHSID not an str: " + `mhsid`
    if type(vtecRequestTime) != int:
        raise TypeError, "VTECPartners: VTEC_REMOTE_TABLE_FETCH_TIME " + \
          "not an int: " + `vtecRequestTime`
    if type(port) != int:
        raise TypeError, "GFESUITE_PORT not an int: " + `port`
    initmodules = dictCheck(initmodules, list, str, "INITMODULES")
    accumElem = dictCheck(accumElem, list, str, "D2DAccumulativeElements")
    initskips = dictCheck(initskips, list, int, "INITSKIPS")
    d2ddbver = dictCheck(d2ddbver, int, None, "D2DDBVERSIONS")
    if type(logfilepurge) != int:
        raise TypeError, "LOG_FILE_PURGE_AFTER not an int: " + `logfilepurge`
    if type(autoConfigureNotifyTextProd) != int:
        raise TypeError, "AUTO_CONFIGURE_NOTIFYTEXTPROD not an int: " + \
          `logfilepurge`
    if type(prddir) != str:
        raise TypeError, "GFESUITE_PRDDIR not an str: " + `prddir`
    if type(home) != str:
        raise TypeError, "GFESUITE_HOME not an str: " + `home`
    if type(extraWEPrec) != list:
        raise TypeError, "ExtraWEPrec not an list: " + `extraWEPrec`
    else:
        extraWEPrecision = LinkedHashMap()
        for e in extraWEPrec:
            if type(e) == str:
                extraWEPrecision.put(e, Integer(1))
            elif type(e) == tuple and len(e) == 2 and type(e[0]) == str and \
              type(e[1]) == int:
                extraWEPrecision.put(e[0], Integer(e[1]))
            else:
                raise TypeError, \
                  "Entry in ExtraWEPrec not str or (str, int): " + `e`

    iscRoutingTableAddress = dictCheck(iscRoutingTableAddress,str,str,"ISC_ROUTING_TABLE_ADDRESS")
    #if type(iscRoutingTableAddress) not in [str, types.NoneType]:
    #    raise TypeError, "ISC_ROUTING_TABLE_ADDRESS not None or a str: " + \
    #      `iscRoutingTableAddress`
    #elif iscRoutingTableAddress is None:
    #    iscRoutingTableAddress = ""

    reqISCsites = ArrayList()
    if type(requestedISCsites) not in [list, types.NoneType]:
        raise TypeError, "REQUESTED_ISC_SITES not None or a list: " + \
          `requestedISCsites`
    elif type(requestedISCsites) is list:
        for r in requestedISCsites:
            if type(r) != str:
                raise TypeError, "REQUESTED_ISC_SITES not list of strings: " + \
                  `requestedISCsites`
            else:
                reqISCsites.add(r);

    reqISCparms = ArrayList()
    if type(requestedISCparms) not in [list, types.NoneType]:
        raise TypeError, "REQUESTED_ISC_PARMS not None or a list: " + \
          `requestedISCparms`
    elif type(requestedISCparms) is list:
        for r in requestedISCparms:
            if type(r) != str:
                raise TypeError, "REQUESTED_ISC_PARMS not list of strings: " + \
                  `requestedISCparms`
            else:
                reqISCparms.add(r)

    if type(requestISC) != int:
        raise TypeError, "REQUEST_ISC not an int: " + `requestISC`
    if type(sendiscOnSave) != int:
        raise TypeError, "SEND_ISC_ON_SAVE not an int: " + `sendiscOnSave`
    if type(sendiscOnPublish) != int:
        raise TypeError, "SEND_ISC_ON_PUBLISH not an int: " + `sendiscOnPublish`

    if type(transmitScript) not in [str, types.NoneType]:
        raise TypeError, "TRANSMIT_SCRIPT not None or str: " + `transmitScript`
    elif transmitScript is None:
        transmitScript = ""

    return serverhost, mhsid, \
      port, initmodules, accumElem, \
      initskips, d2ddbver, logfilepurge, prddir, home,\
      extraWEPrecision, vtecRequestTime, \
      autoConfigureNotifyTextProd, \
      iscRoutingTableAddress, reqISCsites, requestISC, sendiscOnSave, \
      sendiscOnPublish, reqISCparms, transmitScript
Example #32
0
def otherParse(validSites, serverhost, mhsid, port, initmodules, accumElem,
               initskips, d2ddbver, logfilepurge, prddir, home, extraWEPrec,
               vtecRequestTime, autoConfigureNotifyTextProd,
               iscRoutingTableAddress, requestedISCsites, requestISC,
               sendiscOnSave, sendiscOnPublish, requestedISCparms,
               transmitScript):
    if type(serverhost) != str:
        raise TypeError, "GFESUITE_HOST not an str: " + ` serverhost `
    if type(mhsid) != str:
        raise TypeError, "GFESUITE_MHSID not an str: " + ` mhsid `
    if type(vtecRequestTime) != int:
        raise TypeError, "VTECPartners: VTEC_REMOTE_TABLE_FETCH_TIME " + \
          "not an int: " + `vtecRequestTime`
    if type(port) != int:
        raise TypeError, "GFESUITE_PORT not an int: " + ` port `
    initmodules = dictCheck(initmodules, list, str, "INITMODULES")
    accumElem = dictCheck(accumElem, list, str, "D2DAccumulativeElements")
    initskips = dictCheck(initskips, list, int, "INITSKIPS")
    d2ddbver = dictCheck(d2ddbver, int, None, "D2DDBVERSIONS")
    if type(logfilepurge) != int:
        raise TypeError, "LOG_FILE_PURGE_AFTER not an int: " + ` logfilepurge `
    if type(autoConfigureNotifyTextProd) != int:
        raise TypeError, "AUTO_CONFIGURE_NOTIFYTEXTPROD not an int: " + \
          `logfilepurge`
    if type(prddir) != str:
        raise TypeError, "GFESUITE_PRDDIR not an str: " + ` prddir `
    if type(home) != str:
        raise TypeError, "GFESUITE_HOME not an str: " + ` home `
    if type(extraWEPrec) != list:
        raise TypeError, "ExtraWEPrec not an list: " + ` extraWEPrec `
    else:
        extraWEPrecision = LinkedHashMap()
        for e in extraWEPrec:
            if type(e) == str:
                extraWEPrecision.put(e, Integer(1))
            elif type(e) == tuple and len(e) == 2 and type(e[0]) == str and \
              type(e[1]) == int:
                extraWEPrecision.put(e[0], Integer(e[1]))
            else:
                raise TypeError, \
                  "Entry in ExtraWEPrec not str or (str, int): " + `e`

    iscRoutingTableAddress = dictCheck(iscRoutingTableAddress, str, str,
                                       "ISC_ROUTING_TABLE_ADDRESS")
    #if type(iscRoutingTableAddress) not in [str, types.NoneType]:
    #    raise TypeError, "ISC_ROUTING_TABLE_ADDRESS not None or a str: " + \
    #      `iscRoutingTableAddress`
    #elif iscRoutingTableAddress is None:
    #    iscRoutingTableAddress = ""

    reqISCsites = ArrayList()
    if type(requestedISCsites) not in [list, types.NoneType]:
        raise TypeError, "REQUESTED_ISC_SITES not None or a list: " + \
          `requestedISCsites`
    elif type(requestedISCsites) is list:
        for r in requestedISCsites:
            if type(r) != str:
                raise TypeError, "REQUESTED_ISC_SITES not list of strings: " + \
                  `requestedISCsites`
                #Verify requested ISC site is of desired pattern
            elif r not in validSites:
                raise ValueError, "Requested ISC site: " + str(
                    r) + " could not be found in serverConfig.py."
            else:
                reqISCsites.add(r)

    reqISCparms = ArrayList()
    if type(requestedISCparms) not in [list, types.NoneType]:
        raise TypeError, "REQUESTED_ISC_PARMS not None or a list: " + \
          `requestedISCparms`
    elif type(requestedISCparms) is list:
        for r in requestedISCparms:
            if type(r) != str:
                raise TypeError, "REQUESTED_ISC_PARMS not list of strings: " + \
                  `requestedISCparms`
                #Verify requested ISC parm is of desired pattern
            elif not re.match(configProps.ISC_PARM_PATTERN, str(r)):
                raise ValueError, "Requested ISC parm: " + str(
                    r
                ) + " does not match desired pattern: " + configProps.ISC_PARM_PATTERN
            else:
                reqISCparms.add(r)

    if type(requestISC) != bool:
        #If the type is boolean, it is already a valid value
        #If the type is not boolean, and is not int, then it is not valid
        if type(requestISC) != int:
            raise TypeError, "REQUEST_ISC not an int or boolean: " + ` requestISC `
        #Verify request ISC is of valid value
        elif not ((requestISC == 0) or (requestISC == 1)):
            raise ValueError, "REQUEST_ISC is: " + ` requestISC ` + ", but expected True, False, 0 or 1"

    if type(sendiscOnSave) != bool:
        #If the type is boolean, it is already a valid value
        #If the type is not boolean, and is not int, then it is not valid
        if type(sendiscOnSave) != int:
            raise TypeError, "SEND_ISC_ON_SAVE not an int or boolean: " + ` sendiscOnSave `
        #Verify send ISC on save is of valid value
        elif not ((sendiscOnSave == 0) or (sendiscOnSave == 1)):
            raise ValueError, "SEND_ISC_ON_SAVE is: " + ` sendiscOnSave ` + ", but expected True, False, 0 or 1"

    if type(sendiscOnPublish) != bool:
        #If the type is boolean, it is already a valid value
        #If the type is not boolean, and is not int, then it is not valid
        if type(sendiscOnPublish) != int:
            raise TypeError, "SEND_ISC_ON_PUBLISH not an int or boolean: " + ` sendiscOnPublish `
        #Verify send ISC on publish is of valid value
        elif not ((sendiscOnPublish == 0) or (sendiscOnPublish == 1)):
            raise ValueError, "SEND_ISC_ON_PUBLISH is: " + ` sendiscOnPublish ` + ", but expected True, False, 0 or 1"

    if type(transmitScript) not in [str, types.NoneType]:
        raise TypeError, "TRANSMIT_SCRIPT not None or str: " + ` transmitScript `
    elif transmitScript is None:
        transmitScript = ""

    return serverhost, mhsid, \
      port, initmodules, accumElem, \
      initskips, d2ddbver, logfilepurge, prddir, home,\
      extraWEPrecision, vtecRequestTime, \
      autoConfigureNotifyTextProd, \
      iscRoutingTableAddress, reqISCsites, requestISC, sendiscOnSave, \
      sendiscOnPublish, reqISCparms, transmitScript
Example #33
0
# Simple Jython example inspired by:
# http://coffeeonesugar.wordpress.com/2009/07/21/getting-started-with-esper-in-5-minutes/
from java.util import Random, Date, LinkedHashMap
from java.lang import String, Double, System
import com.espertech.esper.client as C

type_map = LinkedHashMap()
type_map.put("symbol", String)
type_map.put("price", Double)
type_map.put("ts", Date)

gen = Random()

def random_tick():
    hmm = LinkedHashMap()
    hmm.put("symbol", 'AAPL')
    p = Double(gen.nextInt(18))
    hmm.put("price", p)
    hmm.put("ts", Date(System.currentTimeMillis()))
    return hmm

class Listener(C.UpdateListener):
    def update(*args, **kwargs):
        a = args[1][0]
        print "Symbol: %s Price: %5.2f  Ts: %s" % (a.get("symbol"),
            a.get("price"), a.get("ts"))

def main():
    conf = C.Configuration()
    conf.addEventType("StockTick", type_map)
    cep = C.EPServiceProviderManager.getProvider("myCEPEngine", conf)