コード例 #1
0
ファイル: test_numbers.py プロジェクト: codeApeFromChina/jep
 def get_values(self):
     i = Integer(-5)
     pi = i.intValue()
     j = Long(5001)
     pj = j.longValue()
     d = Double(10.001)
     pd = d.doubleValue()
     return i, pi, j, pj, d, pd
コード例 #2
0
ファイル: browserlocation.py プロジェクト: sleuthkit/autopsy
    def __findGeoLocationsInDB(self, databasePath, abstractFile):
        if not databasePath:
            return

        try:
            Class.forName("org.sqlite.JDBC") #load JDBC driver
            connection = DriverManager.getConnection("jdbc:sqlite:" + databasePath)
            statement = connection.createStatement()
        except (ClassNotFoundException) as ex:
            self._logger.log(Level.SEVERE, "Error loading JDBC driver", ex)
            self._logger.log(Level.SEVERE, traceback.format_exc())
            return
        except (SQLException) as ex:
            # Error connecting to SQL databse.
            return

        resultSet = None
        try:
            resultSet = statement.executeQuery("SELECT timestamp, latitude, longitude, accuracy FROM CachedPosition;")
            while resultSet.next():
                timestamp = Long.valueOf(resultSet.getString("timestamp")) / 1000
                latitude = Double.valueOf(resultSet.getString("latitude"))
                longitude = Double.valueOf(resultSet.getString("longitude"))

                attributes = ArrayList()
                artifact = abstractFile.newArtifact(BlackboardArtifact.ARTIFACT_TYPE.TSK_GPS_TRACKPOINT)
                attributes.add(BlackboardAttribute(BlackboardAttribute.ATTRIBUTE_TYPE.TSK_GEO_LATITUDE, general.MODULE_NAME, latitude))
                attributes.add(BlackboardAttribute(BlackboardAttribute.ATTRIBUTE_TYPE.TSK_GEO_LONGITUDE, general.MODULE_NAME, longitude))
                attributes.add(BlackboardAttribute(BlackboardAttribute.ATTRIBUTE_TYPE.TSK_DATETIME, general.MODULE_NAME, timestamp))
                attributes.add(BlackboardAttribute(BlackboardAttribute.ATTRIBUTE_TYPE.TSK_PROG_NAME, general.MODULE_NAME, "Browser Location History"))
                # artifact.addAttribute(BlackboardAttribute(BlackboardAttribute.ATTRIBUTE_TYPE.TSK_VALUE.getTypeID(),moduleName, accuracy))
                # NOTE: originally commented out

                artifact.addAttributes(attributes);
                try:
                    # index the artifact for keyword search
                    blackboard = Case.getCurrentCase().getServices().getBlackboard()
                    blackboard.indexArtifact(artifact)
                except Blackboard.BlackboardException as ex:
                    self._logger.log(Level.SEVERE, "Unable to index blackboard artifact " + str(artifact.getArtifactTypeName()), ex)
                    self._logger.log(Level.SEVERE, traceback.format_exc())
                    MessageNotifyUtil.Notify.error("Failed to index GPS trackpoint artifact for keyword search.", artifact.getDisplayName())

        except SQLException as ex:
            # Unable to execute browser location SQL query against database.
            pass
        except Exception as ex:
            self._logger.log(Level.SEVERE, "Error putting artifacts to blackboard", ex)
            self._logger.log(Level.SEVERE, traceback.format_exc())
        finally:
            try:
                if resultSet is not None:
                    resultSet.close()
                statement.close()
                connection.close()
            except Exception as ex:
                # Error closing database.
                pass
コード例 #3
0
ファイル: test_numbers.py プロジェクト: zoltansx/jep
 def test_nonzero(self):
     i, pi, j, pj, d, pd = self.get_values()
     self.assertEqual(bool(i), bool(pi))
     self.assertEqual(bool(j), bool(pj))
     self.assertEqual(bool(d), bool(pd))
     self.assertFalse(bool(Integer(0)))
     self.assertFalse(bool(Long(0)))
     self.assertFalse(bool(Double(0.0)))
     self.assertTrue(bool(Integer(1)))
     self.assertTrue(bool(Long(1)))
     self.assertTrue(bool(Double(1.0)))
コード例 #4
0
ファイル: test-twosources1.py プロジェクト: lfcanals/juant
    def update(self, ss, when):
        strLine = Long.toString(when.getTimeInMillis()).encode('utf-8')
        if 'X' in ss:
            strLine = strLine + ',' \
                + Double.toString(market.getLastPrice(0,'X-OPEN'))\
                        .encode('utf-8') + ','\
                + Double.toString(market.getLastPrice(0,'X-HIGH'))\
                        .encode('utf-8') + ',' \
                + Double.toString(market.getLastPrice(0,'X-LOW'))\
                        .encode('utf-8') + ','\
                + Double.toString(market.getLastPrice(0,'X-CLOSE'))\
                        .encode('utf-8') + ','\
                + Long.toString(market.getLastVolume(0,'X'))\
                        .encode('utf-8')
        else:
            strLine = strLine + ',-,-,-,-,-'

        if 'Y' in ss:
            strLine = strLine + ',' \
                + Double.toString(market.getLastPrice(0,'Y-OPEN'))\
                        .encode('utf-8') + ','\
                + Double.toString(market.getLastPrice(0,'Y-HIGH'))\
                        .encode('utf-8') + ',' \
                + Double.toString(market.getLastPrice(0,'Y-LOW'))\
                        .encode('utf-8') + ','\
                + Double.toString(market.getLastPrice(0,'Y-CLOSE'))\
                        .encode('utf-8') + ','\
                + Long.toString(market.getLastVolume(0,'Y'))\
                        .encode('utf-8')
        else:
            strLine = strLine + ',-,-,-,-,-'

        print strLine
コード例 #5
0
 def update(self, ss, when):
     strLine = Long.toString(when.getTimeInMillis()).encode('utf-8')
     strLine = strLine + ',' \
         + Double.toString(market.getLastPrice(0,'XAG-OPEN'))\
                 .encode('utf-8') + ','\
         + Double.toString(market.getLastPrice(0,'XAG-HIGH'))\
                 .encode('utf-8') + ',' \
         + Double.toString(market.getLastPrice(0,'XAG-LOW'))\
                 .encode('utf-8') + ','\
         + Double.toString(market.getLastPrice(0,'XAG-CLOSE'))\
                 .encode('utf-8') + ','\
         + Long.toString(market.getLastVolume(0,'XAG'))\
                 .encode('utf-8')
     print strLine
コード例 #6
0
    def update(self, ss, when):
        strLine = Long.toString(when.getTimeInMillis()).encode('utf-8')
        for s in bricSymbols:
            if s in ss:
                strLine = strLine + ',' \
                    + Double.toString(market.getLastPrice(0,s+'-OPEN'))\
                            .encode('utf-8') + ','\
                    + Double.toString(market.getLastPrice(0,s+'-HIGH'))\
                            .encode('utf-8') + ',' \
                    + Double.toString(market.getLastPrice(0,s+'-LOW'))\
                            .encode('utf-8') + ','\
                    + Double.toString(market.getLastPrice(0,s+'-CLOSE'))\
                            .encode('utf-8') + ','\
                    + Long.toString(market.getLastVolume(0,s))\
                            .encode('utf-8')
            else:
                strLine = strLine + ',-,-,-,-,-'
       
        if 'XAG' in ss:
            strLine = strLine + ',' \
                + Double.toString(market.getLastPrice(0,'XAG-OPEN'))\
                        .encode('utf-8') + ','\
                + Double.toString(market.getLastPrice(0,'XAG-HIGH'))\
                        .encode('utf-8') + ',' \
                + Double.toString(market.getLastPrice(0,'XAG-LOW'))\
                        .encode('utf-8') + ','\
                + Double.toString(market.getLastPrice(0,'XAG-CLOSE'))\
                        .encode('utf-8') + ','\
                + Long.toString(market.getLastVolume(0,'XAG'))\
                        .encode('utf-8')
        else:
            strLine = strLine + ',-,-,-,-,-'
 
        print strLine
コード例 #7
0
ファイル: GFEPainter.py プロジェクト: ricadieg/awips2
 def addMapBackground(self,
                      mapName,
                      color=None,
                      lineWidth=None,
                      linePattern=None,
                      xOffset=None,
                      yOffset=None,
                      labelAttribute=None,
                      fontOffset=None):
     from com.raytheon.uf.viz.core.maps import MapManager
     rsc = MapManager.getInstance(
         self.getDescriptor()).loadMapByBundleName(mapName).getResource()
     if color is not None:
         rsc.getCapability(ColorableCapability).setColor(
             RGBColors.getRGBColor(color))
     if lineWidth is not None:
         rsc.getCapability(OutlineCapability).setOutlineWidth(lineWidth)
     if linePattern is not None:
         rsc.getCapability(OutlineCapability).setLineStyle(linePattern)
     if xOffset is not None:
         rsc.getCapability(LabelableCapability).setxOffset(xOffset)
     if yOffset is not None:
         rsc.getCapability(LabelableCapability).setyOffset(yOffset)
     rsc.getCapability(LabelableCapability).setLabelField(labelAttribute)
     if fontOffset is not None:
         mag = Double(1.26**fontOffset)
         rsc.getCapability(MagnificationCapability).setMagnification(mag)
コード例 #8
0
  def XML_endElement(self, uri, localName, qName, sourceHandler):
    
    try:
        
      if (qName == SELM_Eulerian.getSimpleName()):
        #/* check all entries set */
        x = 0;
      elif (qName == SELM_Eulerian.tagXML_EulerianName):
        x = 0;
      elif (qName == SELM_Eulerian.tagXML_EulerianTypeStr):
        x = 0;
      elif (qName == SELM_Eulerian_CUSTOM1.tagXML_testVariable):
        self.testVariable = Double.parseDouble(self.xmlAttributes.getValue("value"));
        print("WARNING: SELM_Eulerian_CUSTOM1.py : XML_endElement()");
        print("testVariable = " + str(self.testVariable));

    except Exception, e:
      self.exception_value = e;
      
      print("Error: SELM_Eulerian_CUSTOM1.py : XML_endElement()");                  
      if type(e) is java.lang.Exception:
        print(e.getMessage());
        e.printStackTrace();
      else:
        print(e);  
コード例 #9
0
ファイル: loadConfig.py プロジェクト: tiffanycmeyer13/awips2
def getGlobals(mod):
    mp = HashMap()
    for attrName in mod.__dict__:
        if not attrName.startswith('__'):
            attr = mod.__getattribute__(attrName)
            t = type(attr)
            if t is not list:
                if t is str:
                    mp.put(attrName, attr)
                elif t is int:
                    mp.put(attrName, Integer(attr))
                elif t is float:
                    mp.put(attrName, Double(attr))
                elif t is bool:
                    mp.put(attrName, Boolean(attr))
            else:
                arr = None
                if len(attr) > 0:
                    t = type(attr[0])
                    if t is int:
                        arr = __fillArray(attr, Integer)
                    elif t is float:
                        arr = __fillArray(attr, Double)
                    elif t is str:
                        arr = __fillArray(attr, String)
                mp.put(attrName, arr)
    return mp
コード例 #10
0
    def XML_endElement(self, uri, localName, qName, sourceHandler):

        try:

            if (qName == SELM_Lagrangian.getSimpleName()):
                #/* check all entries set */
                x = 0
            elif (qName == SELM_Lagrangian.tagXML_LagrangianName):
                x = 0
            elif (qName == SELM_Lagrangian.tagXML_LagrangianTypeStr):
                x = 0
            elif (qName == SELM_Lagrangian_CUSTOM1.tagXML_testVariable):
                self.testVariable = Double.parseDouble(
                    self.xmlAttributes.getValue("value"))
                print("WARNING: SELM_Lagrangian_CUSTOM1.py : XML_endElement()")
                print("testVariable = " + str(self.testVariable))

        except Exception, e:
            self.exception_value = e

            print("Error: SELM_Lagrangian_CUSTOM1.py : XML_endElement()")
            if type(e) is java.lang.Exception:
                print(e.getMessage())
                e.printStackTrace()
            else:
                print(e)
コード例 #11
0
def linear_fit():
    global Plot2
    valid = []
    vaxes = []
    for i in xrange(peak_res.size):
        if not Double.isNaN(peak_res[i]):
            valid.append(peak_res[i] * -1)
            vaxes.append(h2k2l2[i])
    if len(valid) == 0:
        slog('Error: there is no available peak.')
        return
    ds2 = Dataset(valid, axes=[vaxes])
    Plot2.set_dataset(ds2)
    ds = Plot2.ds
    if ds is None or len(ds) == 0:
        print 'Error: no curve to fit in Plot2'
        return
    for d in ds:
        if d.title == 'linear_fitting':
            Plot2.remove_dataset(d)
    d0 = ds[0]
    fitting = Fitting(LINEAR_FITTING)
    fitting.set_histogram(d0)
    if linear_slope.value == 0:
        fitting.set_param('a', 1)
    else:
        fitting.set_param('a', linear_slope.value)
    res = fitting.fit()
    res.var[:] = 0
    res.title = 'linear_fitting'
    Plot2.add_dataset(res)
    linear_slope.value = fitting.a
    print fitting.params
コード例 #12
0
ファイル: test_numbers.py プロジェクト: zoltansx/jep
    def test_compare(self):
        pfive = 5
        jfive = Integer(5)
        ptwosix = 2.6
        jtwosix = Double(2.6)

        # Need to check with same values on opposite sides of the operator due
        # to Python's richcompare behavior.

        # check the trues first
        self.assertTrue(pfive > jtwosix)
        self.assertTrue(jtwosix < pfive)
        self.assertTrue(ptwosix < jfive)
        self.assertTrue(jfive > ptwosix)
        self.assertTrue(ptwosix == jtwosix)
        self.assertTrue(jtwosix == ptwosix)
        self.assertTrue(pfive == jfive)
        self.assertTrue(jfive == pfive)

        # check the falses next
        self.assertFalse(pfive < jtwosix)
        self.assertFalse(jtwosix > pfive)
        self.assertFalse(ptwosix > jfive)
        self.assertFalse(jfive < ptwosix)
        self.assertFalse(pfive != jfive)
        self.assertFalse(jfive != pfive)
        self.assertFalse(ptwosix != jtwosix)
        self.assertFalse(jtwosix != ptwosix)
コード例 #13
0
    def getTableModel(self, book):
#        print "getTableModel book",book
        import java.util.Vector as Vector
        import java.util.Arrays as Arrays
        import java.util.Calendar as Calendar
        import com.infinitekind.moneydance.model.CurrencyType as CurrencyType
        import java.lang.Double as Double

        ct = book.getCurrencies()
        allCurrencies = ct.getAllCurrencies()
        data = Vector()
        today = Calendar.getInstance()
        balances = self.sumBalancesByCurrency(book) # HashMap<CurrencyType, Long>  contains no account info
        accounts = self.getCurrencyAccounts(book) # HashMap<CurrencyType, Accounts>
        self.totalBalance = 0.0
#        StockGlance75.totalBalance = 0.0
        for curr in allCurrencies:
            if not curr.getHideInUI() and curr.getCurrencyType() == CurrencyType.Type.SECURITY:
                price = self.priceOrNaN(curr, today, 0)
                price1 = self.priceOrNaN(curr, today, 1)
                price7 = self.priceOrNaN(curr, today, 7)
                price30 = self.priceOrNaN(curr, today, 30)
                price365 = self.priceOrNaN(curr, today, 365)
	      
                if not Double.isNaN(price) and (not Double.isNaN(price1) or not Double.isNaN(price7) or not Double.isNaN(price30) or not Double.isNaN(price365)):
		    entry = Vector(len(self.names))
                    bal = balances.get(curr)
                    balance = (0.0 if (bal == None) else curr.getDoubleValue(bal) * price)
# ?                    Double balance = (bal == null) ? 0.0 : curr.getDoubleValue(bal) * price;		        
                    self.totalBalance += balance
#                    StockGlance75.totalBalance += balance
                    entry.add(curr.getTickerSymbol())
                    entry.add(curr.getName())
                    entry.add(price)
                    entry.add(price - price1)
                    entry.add(balance)
                    entry.add((price - price1) / price1)
                    entry.add((price - price7) / price7)
                    entry.add((price - price30) / price30)
                    entry.add((price - price365) / price365)
                    entry.add(accounts.get(curr))
                    data.add(entry)
                    self.rowCurrencies.add(curr)
#                    StockGlance75.rowCurrencies.add(curr)
        self.data = data            
#        StockGlance75.data = data            
        return self.SGTableModel(self.data, self.columnNames, self.rowCurrencies)
コード例 #14
0
ファイル: documents.py プロジェクト: coady/lupyne
def convert(value):
    "Return python object from java Object."
    if util.BytesRef.instance_(value):
        return util.BytesRef.cast_(value).utf8ToString()
    if not Number.instance_(value):
        return value.toString() if Object.instance_(value) else value
    value = Number.cast_(value)
    return value.doubleValue() if Float.instance_(value) or Double.instance_(value) else int(value.longValue())
コード例 #15
0
  def createChartDataSet (self, xyPoints, name='data'):

    #autoSort = 0
    #allowDuplicateXValues = 0
    
    xySeries = UnsortedXYSeries (name) #, autoSort, allowDuplicateXValues) 
    for i in range (len (xyPoints)):
      point = xyPoints [i]
      x = point.getX ()
      y = point.getY ()
      if (Double.isNaN (x) or Double.isNaN (y)):
        continue
      xySeries.add (x, y)
      self.pointNames.append (point.getName ())


    return XYSeriesCollection (xySeries)
コード例 #16
0
 def visitAwsEbs(self, ebs):
     r'@types: aws_store.Ebs -> ObjectStateHolder'
     osh = ObjectStateHolder('logical_volume')
     osh.setAttribute('logical_volume_global_id', ebs.getId())
     if ebs.sizeInMb and ebs.sizeInMb.value() is not None:
         size = Double.valueOf(ebs.sizeInMb.value())
         osh.setAttribute('logicalvolume_size', size)
     return osh
コード例 #17
0
ファイル: aws_store.py プロジェクト: ddonnelly19/dd-git
 def visitAwsEbs(self, ebs):
     r'@types: aws_store.Ebs -> ObjectStateHolder'
     osh = ObjectStateHolder('logical_volume')
     osh.setAttribute('logical_volume_global_id', ebs.getId())
     if ebs.sizeInMb and ebs.sizeInMb.value() is not None:
         size = Double.valueOf(ebs.sizeInMb.value())
         osh.setAttribute('logicalvolume_size', size)
     return osh
コード例 #18
0
def convert(value):
    """Return python object from java Object."""
    if util.BytesRef.instance_(value):
        return util.BytesRef.cast_(value).utf8ToString()
    if not Number.instance_(value):
        return value.toString() if Object.instance_(value) else value
    value = Number.cast_(value)
    return value.doubleValue() if Float.instance_(value) or Double.instance_(
        value) else int(value.longValue())
コード例 #19
0
 def __init__(self):
     head = 'Byte,Double,Float,Integer,Long,Short'.split(',')
     self.data = [[
         Byte(Byte.MIN_VALUE),
         Double(Double.MIN_VALUE),
         Float(Float.MIN_VALUE),
         Integer(Integer.MIN_VALUE),
         Long(Long.MIN_VALUE),
         Short(Short.MIN_VALUE)
     ],
                  [
                      Byte(Byte.MAX_VALUE),
                      Double(Double.MAX_VALUE),
                      Float(Float.MAX_VALUE),
                      Integer(Integer.MAX_VALUE),
                      Long(Long.MAX_VALUE),
                      Short(Short.MAX_VALUE)
                  ]]
     DefaultTableModel.__init__(self, self.data, head)
コード例 #20
0
 def _makeInstance(self, i, instances=None):
     inst = Instance(len(i))
     if instances is not None:
         inst.setDataset(instances)
     for (attName, value) in i.iteritems():
         if attName in self.numericAttributes: value = Double(value)
         else: value = String(value)
         attr = self.attName2Obj[attName]
         #print self.attName2Domain
         #print "attName, value", attName, value
         inst.setValue(attr, value)
     return inst
コード例 #21
0
 def __init__(self, data, headings):
     info = []
     df = DateFormat.getDateInstance(DateFormat.SHORT)
     for tf, date, size, f, d in data:
         info.append([
             Boolean(tf == '1'),
             df.parse(date),
             Integer(size.strip().replace(',', '')),
             Float(f),
             Double(d)
         ])
     DefaultTableModel.__init__(self, info, headings)
コード例 #22
0
def upload_rt_as_omero_table(rt, ctx, target_id, target_type, roivec=[]):
    "Convert results into an OMERO table"
    roivec_cols = ['ROI-id', 'Shape-id', 'Z', 'C', 'T']
    length = len(roivec_cols)
    no_of_columns = rt.getLastColumn() + length
    no_of_rows = rt.size()

    data = [[Double(0) for x in range(no_of_rows)]
            for y in range(no_of_columns)]
    columns = [TableDataColumn] * no_of_columns

    for c in range(0, no_of_columns):
        if c < length:
            colname = roivec_cols[c]
            rows = [Double(i[c]) for i in roivec]
            columns[c] = TableDataColumn(colname, c, Double)
        else:
            colname = rt.getColumnHeading(c - length)
            rows = rt.getColumnAsDoubles(c - length)
            columns[c] = TableDataColumn(colname, c, Double)

        if rows is None:
            continue
        for r in range(0, len(rows)):
            data[c][r] = rows[r]

    table_data = TableData(columns, data)
    browse = gateway.getFacility(BrowseFacility)
    # use the appropriate target DataObject and attach the MapAnnotationData object to it
    if target_type == "Project":
        target_obj = ProjectData(ProjectI(target_id, False))
    elif target_type == "Dataset":
        target_obj = DatasetData(DatasetI(target_id, False))
    elif target_type == "Image":
        target_obj = browse.getImage(ctx, long(target_id))

    table_facility = gateway.getFacility(TablesFacility)
    table_facility.addTable(ctx, target_obj, "Table_from_Fiji", table_data)
コード例 #23
0
 def draw_state(self, state, treward, creward):
     # declarations
     apos = [None] * NUM_AGENTS
     # clear cells
     for i in range(len(self.cells)):
         self.cells[i].removeAll()        
     # get agents' positions
     for i in range(NUM_AGENTS):
         apos[i] = ROWS * COLS  - state[i]
     # last element in the array is wumpus' position
     wpos = ROWS * COLS  - state[NUM_AGENTS]
     # add agents
     for i in range(NUM_AGENTS):
         self.cells[apos[i]].add(JLabel(self.scale(self.aIcon.getImage(), 0.6)))
     # add the wumpus
     self.cells[wpos].add(JLabel(self.scale(self.wIcon.getImage(), 0.6)))
     # gray-out illegal positions and update all cells
     for i in range(len(self.cells)):
         if gp.isLegalPosition(i) == False:
             self.cells[i].setBackground(Color.BLACK)
         self.cells[i].updateUI()
     # display total and cum rew on ctrl panel
     self.rewLbl.setText(Double.toString(treward))
     self.crewLbl.setText(Double.toString(creward))
コード例 #24
0
ファイル: MeasuresCells_.py プロジェクト: leec13/MorphoBactPy
	def __measureVelocity(self, img, name) :
		measure = "velocity"
		dico=self.__dictCells[name]
		for cellname in dico.keys() :
			roitemp=dico[cellname].getRoi(0)
			xc = self.__dictMeasures[dico[cellname]]["XC"]
			yc = self.__dictMeasures[dico[cellname]]["YC"]
			d=[]
			for i in range(len(xc)-1) :
				tempseq = [ xc[i], xc[i+1], yc[i], yc[i+1] ]
				if not any(Double.isNaN(val)==True for val in tempseq ) :
					d.append(Morph.distMorph([[1, xc[i], xc[i+1]],[1, yc[i], yc[i+1]]]))
				else : d.append(Double.NaN)
			d.append(Double.NaN)
			self.__dictMeasures[dico[cellname]][measure]=d
			del(d)					
コード例 #25
0
        def setValue(self, value):
	    import java.lang.Double as Double
	    import com.infinitekind.util.StringUtils as StringUtils
	    import java.awt.Color as Color
            if value == None:
                self.setText("")
            elif Double.isNaN(float(value)):
                setText("")
            else:
                if self.isZero(float(value)):
                    value = 0.0
                self.setText(StringUtils.formatPercentage(float(value), self.decimalSeparator) + "%")
                if float(value) < 0.0:
                    self.setForeground(Color.RED)
                else:
                    self.setForeground(Color.BLACK)
コード例 #26
0
def map_to_vertx(value):
    """Converts a Jython type to a Vert.x type."""
    if value is None:
        return value
    if isinstance(value, (list, tuple)):
        return org.vertx.java.core.json.JsonArray(map_seq_to_java(value))
    elif isinstance(value, dict):
        return org.vertx.java.core.json.JsonObject(map_dict_to_java(value))
    elif isinstance(value, Buffer):
        return value._to_java_buffer()
    elif isinstance(value, long):
        return Long(value)
    elif isinstance(value, float):
        return Double(value)
    elif isinstance(value, int):
        return Integer(value)
    return map_to_java(value)
コード例 #27
0
ファイル: Gatan_Renamer.py プロジェクト: m-entrup/EFTEMj
 def __init__(self, imp):
     '''Get the metadata from the given dm3 image.
     '''
     extractor = GatanMetadataExtractor(imp)
     self.exposure = extractor.getExposure()
     self.magnification = extractor.getMagnification()
     self.mag_factor = extractor.getActualMagnification() / self.magnification
     self.mag_unit = 'x'
     if not Double.isNaN(extractor.getEnergyloss()):
         self.energyloss = extractor.getEnergyloss()
     else:
         self.energyloss = 0
     self.date = extractor.getDateAndTime()
     date_formater = SimpleDateFormat('yyyyMMdd')
     self.date_string = date_formater.format(self.date)
     self.name = extractor.getName()
     self.prop_dict = {}
コード例 #28
0
ファイル: GDA_Matrix.py プロジェクト: openGDA/gda-core
	def __str__(self):
		output =  ""
		for i in range(self.theMatrix.getRowDimension()):
			if i == 0:
				output = output +"["
			for j in range(self.theMatrix.getColumnDimension()):
				if j == 0:
					output = output +"["
				output = output + Double.toString(self.theMatrix.get(i,j))
				if (j == (self.theMatrix.getColumnDimension() -1)):
					output = output +"]"
				else:
					output = output + ", "
			if (i == (self.theMatrix.getRowDimension() -1)):
				output = output +"]"
			else:
				output = output + ", "
		return output
コード例 #29
0
ファイル: GDA_Matrix.py プロジェクト: kusamau/gda-core
 def __str__(self):
     output = ""
     for i in range(self.theMatrix.getRowDimension()):
         if i == 0:
             output = output + "["
         for j in range(self.theMatrix.getColumnDimension()):
             if j == 0:
                 output = output + "["
             output = output + Double.toString(self.theMatrix.get(i, j))
             if (j == (self.theMatrix.getColumnDimension() - 1)):
                 output = output + "]"
             else:
                 output = output + ", "
         if (i == (self.theMatrix.getRowDimension() - 1)):
             output = output + "]"
         else:
             output = output + ", "
     return output
コード例 #30
0
ファイル: MeasuresCells_.py プロジェクト: leec13/MorphoBactPy
	def __measurecumulDist(self, img, name) :
		measure = "cumulatedDist"
		dico=self.__dictCells[name]
		for cellname in dico.keys() :
			roitemp=dico[cellname].getRoi(0)
			xc = self.__dictMeasures[dico[cellname]]["XC"]
			yc = self.__dictMeasures[dico[cellname]]["YC"]
			d=[]
			d.append(0)
			for i in range(1,len(xc)-1) :
				tempseq = [ xc[i], xc[i+1], yc[i], yc[i+1] ]
				if not any(Double.isNaN(val)==True for val in tempseq ) :
					lastdist = Morph.distMorph([[1, xc[i], xc[i+1]],[1, yc[i], yc[i+1]]])
					d.append(d[-1]+lastdist)
				else : d.append(Double.NaN)
			d.append(Double.NaN)
			self.__dictMeasures[dico[cellname]][measure]=d
			del(d)		
コード例 #31
0
 def warn(self):
     bboxString = self.textfield.getText()
     if bboxString == "":
         self.textfield.setBorder(self.defaultborder)
         return
     if len(bboxString.split(",")) != 4:
         self.wrongEntry()
     else:
         for i, coordString in enumerate(bboxString.split(",")):
             try:
                 coord = Double.parseDouble(coordString)
             except NumberFormatException:
                 self.wrongEntry()
                 return
             minmax = {0: (-180, 180), 1: (-90, 90),
                       2: (-180, 180), 3: (-90, 90)}
             if not minmax[i][0] <= coord <= minmax[i][1]:
                 self.wrongEntry()
                 return
         self.textfield.setBorder(self.defaultborder)
         self.dlg.bboxPreviewTextField.setText(bboxString)
コード例 #32
0
ファイル: NewZoneDialog.py プロジェクト: alex85k/qat_script
 def warn(self):
     bboxString = self.textfield.getText()
     if bboxString == "":
         self.textfield.setBorder(self.defaultborder)
         return
     if len(bboxString.split(",")) != 4:
         self.wrongEntry()
     else:
         for i, coordString in enumerate(bboxString.split(",")):
             try:
                 coord = Double.parseDouble(coordString)
             except NumberFormatException:
                 self.wrongEntry()
                 return
             minmax = {0: (-180, 180), 1: (-90, 90),
                       2: (-180, 180), 3: (-90, 90)}
             if not minmax[i][0] <= coord <= minmax[i][1]:
                 self.wrongEntry()
                 return
         self.textfield.setBorder(self.defaultborder)
         self.dlg.bboxPreviewTextField.setText(bboxString)
コード例 #33
0
        def setValue(self, value):
	    import java.lang.Double as Double
	    import java.awt.Color as Color
            if value == None:
                self.setText("")
            elif Double.isNaN(float(value)):
                self.setText("")
            else:
                if self.isZero(float(value)):
                    value = 0.0
                if self.noDecimals:
		    # MD format functions can't print comma-separated values without a decimal point so
                    # we have to do it ourselves
                    scaledValue = float(value) * self.relativeTo.getUserRate();		  
                    self.setText(self.relativeTo.getPrefix() + " " + self.noDecimalFormatter.format(scaledValue) + self.relativeTo.getSuffix())
                else:
		    scaledValue = self.relativeTo.convertValue(self.relativeTo.getLongValue(float(value)))
                    self.setText(self.relativeTo.formatFancy(scaledValue, self.decimalSeparator))
                if float(value) < 0.0:
                    self.setForeground(Color.RED)
                else:
                    self.setForeground(Color.BLACK)
コード例 #34
0
ファイル: import_utils.py プロジェクト: deezeesms/dd-git
    def getJavaValue(self, value, type):
        try:
            if type == AppilogTypes.LONG_DEF:
                return Long(value)

            if type == AppilogTypes.INTEGER_DEF:
                return Integer(value)

            if type == AppilogTypes.FLOAT_DEF:
                return Float(value)

            if type == AppilogTypes.DOUBLE_DEF:
                return Double(value)

            if type == AppilogTypes.BOOLEAN_DEF:
                return Boolean(value)
            return value
        except JavaException, ex:
            msg = ex.getMessage()
            info = logger.prepareJavaStackTrace()
            logger.debug(info)
            raise CiImportException, self.makeConversionMessage(
                'Error while converting to type %s ' % type, msg)
コード例 #35
0
ファイル: nuctrack.py プロジェクト: cmci/ijmacros
def write2ResultsTable(rt, heading, dataA):
	for i in range(len(dataA)):
		rt.setValue(heading, i, Double.valueOf(dataA[i]))
コード例 #36
0
r = Random()

# Series 1 Outputs
#@OUTPUT Double[] series1_values
#@OUTPUT String series1_strokeColor
#@OUTPUT Integer series1_strokeWidth

series1_strokeColor = "rgb(" + str(r.nextInt(255)) + "," + str(
    r.nextInt(255)) + "," + str(r.nextInt(255)) + ")"
series1_strokeWidth = 2

series1_values = []

for i in range(999):
    series1_values.append(Double.valueOf(r.nextGaussian()))

# Series 2 Outputs
#@OUTPUT Double[] series2_values
#@OUTPUT String series2_strokeColor
#@OUTPUT Integer series2_strokeWidth

series2_strokeColor = "rgb(" + str(r.nextInt(255)) + "," + str(
    r.nextInt(255)) + "," + str(r.nextInt(255)) + ")"
series2_strokeWidth = 2

series2_values = []

for i in range(999):
    series2_values.append(Double.valueOf(r.nextGaussian() - 5))
コード例 #37
0
 def convertGeo(s):
     length = len(s)
     if length > 6:
         return Double.valueOf(s[0 : length-6] + "." + s[length-6 : length])
     else:
         return Double.valueOf(s)
コード例 #38
0
 def getTemperatureHumiditySensor(self):
     result = grovepi.get(lambda: self.__temperatureHumiditySensor.get())
     if Double.isNaN(result.temperature) or Double.isNaN(result.humidity):
         # Read error.
         return None
     return result
コード例 #39
0
import math
from java.util import Random
from java.lang import Double

r = Random()

# Series 1 Outputs
#@OUTPUT Double[] series1_xvalues
#@OUTPUT Double[] series1_yvalues
#@OUTPUT Double[] series1_size
#@OUTPUT String[] series1_label
#@OUTPUT String[] series1_color
#@OUTPUT String series1_markerColor

series1_markerColor = "lightgreen"

series1_xvalues = []
series1_yvalues = []
series1_size = []
series1_color = []
series1_label = []

for i in range(99):
    series1_xvalues.append(Double.valueOf(r.nextGaussian()))
    series1_yvalues.append(Double.valueOf(r.nextGaussian()))
    series1_size.append(
        Double.valueOf(4 / math.sqrt(series1_xvalues[i] * series1_xvalues[i] +
                                     series1_yvalues[i] * series1_yvalues[i])))
    series1_color.append("rgb(" + str(r.nextInt(255)) + "," +
                         str(r.nextInt(255)) + "," + str(r.nextInt(255)) + ")")
    series1_label.append("point " + str(i))
コード例 #40
0
def stringToDouble(value):
	return Double.parseDouble(value.strip())
コード例 #41
0
ファイル: values.py プロジェクト: varialus/jython-legacy
                   ['foo', 'subfoo', 'subfoo2', 'n']):
    d[_v] = _id

from java.lang import Long, Integer, Short, Character, Byte, Boolean, Double, Float, String
from java.math import BigInteger

values = [
    0, 0L, 0.0, 'c', "string", (), o, c, foo, subfoo, subfoo2, n, Object,
    Class, Foo, SubFoo, C, SubFoo2, N, Integer,
    Long(0),
    Integer(0),
    Short(0),
    Character('c'),
    Byte(0),
    Boolean(0),
    Double(0),
    Float(0),
    String("js"),
    BigInteger("0")
]


def pp(v):
    inst = d.get(v, None)
    if inst is not None:
        return inst
    if hasattr(v, '__name__'):
        return v.__name__
    if isinstance(v, (String, Number, Character, Boolean)):
        n = v.__class__.__name__
        return "%s[%s]" % (n[n.rfind('.') + 1:], v)
コード例 #42
0
ファイル: scan_1d.py プロジェクト: thiyagavit/passerelle
def parameterScan():
	global scan_device_server_name	
	global scan_1d_front
	global scan_2d_front
	global path 
	global data_file 
	global file_extension 
	global actuators
	global sensors 
	global n_steps 
	global integration_time 
	global start_position_actuators_1D 
	global end_position_actuators_1D 
	global n_steps2 
	global start_position_actuators_2D 
	global end_position_actuators_2D 
	global timebase 
	global scan_number 
	global scan_type 
	global has_trajectory	
	global file_path
	global actuators2D
	#open the file in read only mode
	#file = DataInputStream(FileInputStream("D:\eclipse\workspace\passerelle-soleil\sample-models\paramscan.txt"))
	file =  open(file_path,'r')
	parameters = {}
	for line in file.readlines():
		#print "line ",line
		tokens = line.split('=')
		#print "tokens ",tokens
		if(len(tokens) == 2):
			tok0 = String(tokens[0])
			tok1 = String(tokens[1])
			tok0 = tok0.trim()
			tok1 = tok1.trim()
			parameters[tok0] = tok1
			print tok0,":",tok1
	
	if(parameters.has_key("scan_device_server_name")):
		scan_device_server_name = parameters["scan_device_server_name"]
		
	if(parameters.has_key("scan_1d_front")):
		scan_1d_front = parameters["scan_1d_front"]
		
	if(parameters.has_key("scan_2d_front")):
		scan_2d_front = parameters["scan_2d_front"]
	
	if(parameters.has_key("path")):
		path = parameters["path"]
	
	if(parameters.has_key("data_file")):
		data_file = parameters["data_file"]
	
	if(parameters.has_key("file_extension")):
		file_extension = parameters["file_extension"]
	
	if(parameters.has_key("actuators")):
		actuators = parameters["actuators"].split(",")
		#print  "parameterScan actuators ",parameters["actuators"].split(",")
   	
   	if(parameters.has_key("sensors")):
		sensors = parameters["sensors"].split(",")
  	
  	#if(parameters.has_key("n_steps")):
		#n_steps = Integer.parseInt(parameters["n_steps"])
   	
   	#if(parameters.has_key("integration_time")):
		#integration_time = Double.parseDouble(parameters["integration_time"])
	
	#if(parameters.has_key("start_position_actuators_1D")):	
	#	stringTable = parameters["start_position_actuators_1D"].split(",")
	#	start_position_actuators_1D = []
	#	for i in stringTable:
	#		start_position_actuators_1D.append(Double.parseDouble(i))
   	
   	if(parameters.has_key("end_position_actuators_1D")):
		stringTable = parameters["end_position_actuators_1D"].split(",")
		end_position_actuators_1D = []
		for i in stringTable:
			end_position_actuators_1D.append(Double.parseDouble(i))
	
	if(parameters.has_key("actuators2D")):
		actuators2D = parameters["actuators2D"].split(",")
		#print  "parameterScan actuators ",parameters["actuators"].split(",")
	
	if(parameters.has_key("n_steps2")):
		n_steps2 = Integer.parseInt(parameters["n_steps2"])
	
	if(parameters.has_key("start_position_actuators_2D")):	
		stringTable = parameters["start_position_actuators_2D"].split(",")
		start_position_actuators_2D = []
		for i in stringTable:
			start_position_actuators_2D.append(Double.parseDouble(i))
   	
   	if(parameters.has_key("end_position_actuators_2D")):
		stringTable = parameters["end_position_actuators_2D"].split(",")
		end_position_actuators_2D = []
		for i in stringTable:
			end_position_actuators_2D.append(Double.parseDouble(i))
   	
   	if(parameters.has_key("timebase")):
		timebase = parameters["timebase"]
	
	if(parameters.has_key("scan_number")):
		scan_number = Integer.parseInt(parameters["scan_number"])
   	
   	if(parameters.has_key("scan_type")):
		scan_type = Integer.parseInt(parameters["scan_type"])
   	
   	if(parameters.has_key("has_trajectory")):
		has_trajectory = Integer.parseInt(parameters["has_trajectory"])
コード例 #43
0
    def __findGeoLocationsInDB(self, databasePath, abstractFile):
        if not databasePath:
            return

        try:
            Class.forName("org.sqlite.JDBC")  #load JDBC driver
            connection = DriverManager.getConnection("jdbc:sqlite:" +
                                                     databasePath)
            statement = connection.createStatement()
        except (ClassNotFoundException) as ex:
            self._logger.log(Level.SEVERE, "Error loading JDBC driver", ex)
            self._logger.log(Level.SEVERE, traceback.format_exc())
            return
        except (SQLException) as ex:
            # Error connecting to SQL databse.
            return

        resultSet = None
        try:
            resultSet = statement.executeQuery(
                "SELECT timestamp, latitude, longitude, accuracy FROM CachedPosition;"
            )
            while resultSet.next():
                timestamp = Long.valueOf(
                    resultSet.getString("timestamp")) / 1000
                latitude = Double.valueOf(resultSet.getString("latitude"))
                longitude = Double.valueOf(resultSet.getString("longitude"))

                attributes = ArrayList()
                artifact = abstractFile.newArtifact(
                    BlackboardArtifact.ARTIFACT_TYPE.TSK_GPS_TRACKPOINT)
                attributes.add(
                    BlackboardAttribute(
                        BlackboardAttribute.ATTRIBUTE_TYPE.TSK_GEO_LATITUDE,
                        general.MODULE_NAME, latitude))
                attributes.add(
                    BlackboardAttribute(
                        BlackboardAttribute.ATTRIBUTE_TYPE.TSK_GEO_LONGITUDE,
                        general.MODULE_NAME, longitude))
                attributes.add(
                    BlackboardAttribute(
                        BlackboardAttribute.ATTRIBUTE_TYPE.TSK_DATETIME,
                        general.MODULE_NAME, timestamp))
                attributes.add(
                    BlackboardAttribute(
                        BlackboardAttribute.ATTRIBUTE_TYPE.TSK_PROG_NAME,
                        general.MODULE_NAME, "Browser Location History"))
                # artifact.addAttribute(BlackboardAttribute(BlackboardAttribute.ATTRIBUTE_TYPE.TSK_VALUE.getTypeID(),moduleName, accuracy))
                # NOTE: originally commented out

                artifact.addAttributes(attributes)
                try:
                    # index the artifact for keyword search
                    blackboard = Case.getCurrentCase().getServices(
                    ).getBlackboard()
                    blackboard.indexArtifact(artifact)
                except Blackboard.BlackboardException as ex:
                    self._logger.log(
                        Level.SEVERE, "Unable to index blackboard artifact " +
                        str(artifact.getArtifactTypeName()), ex)
                    self._logger.log(Level.SEVERE, traceback.format_exc())
                    MessageNotifyUtil.Notify.error(
                        "Failed to index GPS trackpoint artifact for keyword search.",
                        artifact.getDisplayName())

        except SQLException as ex:
            # Unable to execute browser location SQL query against database.
            pass
        except Exception as ex:
            self._logger.log(Level.SEVERE,
                             "Error putting artifacts to blackboard", ex)
            self._logger.log(Level.SEVERE, traceback.format_exc())
        finally:
            try:
                if resultSet is not None:
                    resultSet.close()
                statement.close()
                connection.close()
            except Exception as ex:
                # Error closing database.
                pass
コード例 #44
0
ファイル: import_converters.py プロジェクト: deezeesms/dd-git
def stringToDouble(value):
    return Double.parseDouble(value.strip())
コード例 #45
0
import be.isencia.passerelle.message.MessageFactory as MessageFactory
import java.lang.Double as Double
import java.lang.reflect.Array as Array
import be.isencia.passerelle.message.ManagedMessage as ManagedMessage

# get content of port 0
message = container.getInputMessage(0)
messageBody = message.getBodyContent()
print "Message: ", messageBody

#process content of input
test = range(messageBody.__len__())
test[0] = 12
print test
test[0] = Double.parseDouble(messageBody[0])

j=0
while j < messageBody.__len__():
	test[j] = Double.parseDouble(messageBody[j])
	j = j+1
print test
i=0
while i < messageBody.__len__():
	test[i] = test[i]+1
	
	i = i+1
	
array(test, Double)
print test
#put result in a passerelle message
コード例 #46
0
    def _getIndex(self, even, odd):

        mergePolicy = LogDocMergePolicy()
        mergePolicy.setMergeFactor(1000)
        directory = RAMDirectory()
        self.dirs.append(directory)

        writer = self.getWriter(directory=directory,
                                analyzer=SimpleAnalyzer(Version.LUCENE_CURRENT),
                                maxBufferedDocs=2, mergePolicy=mergePolicy)

        if self.dvStringSorted:
            # Index sorted
            stringDVType = FieldInfo.DocValuesType.SORTED
        elif self.notSorted:
            # Index non-sorted
            stringDVType = FieldInfo.DocValuesType.BINARY
        else:
            # sorted anyway
            stringDVType = FieldInfo.DocValuesType.SORTED

        ft1 = FieldType()
        ft1.setStored(True)
        ft2 = FieldType()
        ft2.setIndexed(True)

        for i in xrange(len(self.data)):
            if (i % 2 == 0 and even) or (i % 2 == 1 and odd):
                doc = Document()
                doc.add(Field("tracer", self.data[i][0], ft1))
                doc.add(TextField("contents", self.data[i][1], Field.Store.NO))
                if self.data[i][2] is not None:
                    doc.add(StringField("int", self.data[i][2], Field.Store.NO))
                    if self.supportsDocValues:
                        doc.add(NumericDocValuesField("int_dv", Long.parseLong(self.data[i][2])))
                if self.data[i][3] is not None:
                    doc.add(StringField("float", self.data[i][3], Field.Store.NO))
                    if self.supportsDocValues:
                        doc.add(FloatDocValuesField("float_dv", Float.parseFloat(self.data[i][3])))

                if self.data[i][4] is not None:
                    doc.add(StringField("string", self.data[i][4], Field.Store.NO))
                    if self.supportsDocValues:
                        if stringDVType == FieldInfo.DocValuesType.SORTED:
                            doc.add(SortedDocValuesField("string_dv", BytesRef(self.data[i][4])))
                        elif stringDVType == FieldInfo.DocValuesType.BINARY:
                            doc.add(BinaryDocValuesField("string_dv", BytesRef(self.data[i][4])))
                        else:
                            raise ValueError("unknown type " + stringDVType)

                if self.data[i][5] is not None:
                    doc.add(StringField("custom", self.data[i][5], Field.Store.NO))
                if self.data[i][6] is not None:
                    doc.add(StringField("i18n", self.data[i][6], Field.Store.NO))
                if self.data[i][7] is not None:
                    doc.add(StringField("long", self.data[i][7], Field.Store.NO))
                if self.data[i][8] is not None:
                    doc.add(StringField("double", self.data[i][8], Field.Store.NO))
                    if self.supportsDocValues:
                        doc.add(NumericDocValuesField("double_dv", Double.doubleToRawLongBits(Double.parseDouble(self.data[i][8]))))
                if self.data[i][9] is not None:
                    doc.add(StringField("short", self.data[i][9], Field.Store.NO))
                if self.data[i][10] is not None:
                    doc.add(StringField("byte", self.data[i][10], Field.Store.NO))
                if self.data[i][11] is not None:
                    doc.add(StringField("parser", self.data[i][11], Field.Store.NO))

                for f in doc.getFields():
                    if f.fieldType().indexed() and not f.fieldType().omitNorms():
                        Field.cast_(f).setBoost(2.0)

                writer.addDocument(doc)

        reader = writer.getReader()
        writer.close()

        return self.getSearcher(reader=reader)
コード例 #47
0
ファイル: CatchExecGUI.py プロジェクト: gturovsky/libpomdp
    def run_sim(self):
        episoderunning = True

        # starting belief state
        currbelief = initBelief
        factoredS = initState
        instance = 1
        cumrew = 0
        run = 1
        # execution loop
        # while(episoderunning):
        while run <= 100:
            # draw current state
            # self.draw_state(factoredS)

            # extract action from direct controller - ie., 0-step LA
            exreward = valueFunction.V(currbelief)
            action = valueFunction.directControl(currbelief)
            print "value of b %f and selected action %d" % (exreward, action)

            # show action that we are about to execute
            self.nactLbl.setText(pomdpProblem.getactStr(action))
            time.sleep(1)

            # sample new state, observation, and calculate reward
            print factoredS
            factoredS1 = pomdpProblem.sampleNextState(factoredS, action)
            print " sampled state is"
            print factoredS1
            factoredO = pomdpProblem.sampleObservation(factoredS, factoredS1, action)
            print " sampled o is"
            print factoredO
            reward = pomdpProblem.getReward(factoredS, action)
            print reward

            # draw new state, and display what's happening
            self.draw_state(factoredS1)
            self.lactLbl.setText(pomdpProblem.getactStr(action))
            self.nactLbl.setText("nil")
            self.rewLbl.setText(Double.toString(reward))
            cumrew = cumrew + reward * gamma ** instance
            self.crewLbl.setText(Double.toString(cumrew))
            self.obsLbl.setText(
                pomdpProblem.getobsStr(
                    pomdpProblem.sencode(factoredO, pomdpProblem.getnrObsV(), pomdpProblem.getobsArity()) - 1
                )
            )

            # iterate
            nextbelief = pomdpProblem.tao(
                currbelief,
                action,
                pomdpProblem.sencode(factoredO, pomdpProblem.getnrObsV(), pomdpProblem.getobsArity()) - 1,
            )
            currbelief = nextbelief
            factoredS = factoredS1
            instance = instance + 1

            # step button
            if self.stepChk.isSelected() == True:
                self.stepBtn.setEnabled(True)
            while self.stepBtn.isEnabled() == True:
                time.sleep(1)

            # check whether this episode has ended
            # if reward == CATCH_REWARD - 1:
            #    print "Episode ended!"
            #    episoderunning = false

            # smooth the sim a little in case we're not stepping
            time.sleep(1)

            # stop after 100 iterations
            if instance == 100:
                run = run + 1
                stats.append(cumrew)
                currbelief = initBelief
                factoredS = initState
                cumrew = 0
                instance = 1

        print stats
コード例 #48
0
ファイル: MeasuresCells_.py プロジェクト: leec13/MorphoBactPy
		def graphbuttonPressed(event) :
			
			colors=[]
			#img=IJ.getImage()
			#nbslices=self.__img.getImageStackSize()
			nbslices=self.__maxLife

			acell=dico.values()[0]
			if self.__useTime : 
				x = acell.getListTimes()
				namex="Time sec"
			else : 
				x = range(1,nbslices+1)
				namex = "Frame"
			maxx=max(x)
			minx=min(x)
			
			#x=[i for i in range(1,nbslices+1)]
			font=Font("new", Font.BOLD, 14)
			tempname = WindowManager.getUniqueName(self.__img.getShortTitle())
			for i in range(len(self.__measures)) :
				#print "i", i, self.__measures[i]
				yarray=[]
				flag=True
				miny=10000000000
				maxy=-1000000000
				#we find the min and max values in order to set the scale.
				for cellname in self.__listcellname :	
					colors.append(dico[cellname].getColor())
					yarray.append(self.__dictMeasures[dico[cellname]][self.__measures[i]])
					#for meas in self.__dictMeasures[dico[cellname]][self.__measures[i]] :
					for meas in yarray[-1] :
						if (meas<miny) and (Double.isNaN(meas)==False) :
							miny=meas
					if max(yarray[-1])>maxy : maxy=max(yarray[-1])
				
				miny-=0.1*miny
				maxy+=0.1*maxy
				count=0.05
				
				for j in range(len(yarray)) :
					if j==0 :
						if len(self.__measures)>1 :
							plot=Plot("Plots-"+str(self.__measures[i]),namex,str(self.__measures[i]),x,yarray[j])
							
						else : 
							plot=Plot("Plot-"+tempname,namex,str(self.__measures[i]),x,yarray[j])
							
						plot.setLimits(minx,maxx,miny,maxy)
						plot.setColor(colors[j])
						plot.changeFont(font)
						plot.addLabel(0.05, count, self.__listcellname[j])
					else :
						plot.setColor(colors[j])
						plot.setLineWidth(3)
						plot.addPoints(x,yarray[j],Plot.LINE)
						plot.addLabel(0.05, count, self.__listcellname[j])

					count+=0.05
						
				plot.setColor(colors[0])
				plot.show()
				
			if len(self.__measures)>1 :
				IJ.run("Images to Stack", "name="+tempname+"-plots title=Plots- use")
コード例 #49
0
 def convertGeo(s):
     length = len(s)
     if length > 6:
         return Double.valueOf(s[0 : length-6] + "." + s[length-6 : length])
     else:
         return Double.valueOf(s)
コード例 #50
0
ファイル: scan_1d.py プロジェクト: thiyagavit/passerelle
message = container.getInputMessage(0)
messageBody = message.getBodyContentAsString()

#if inputPortNr == 0:
print "input 0: ",messageBody
file_path = messageBody
	
message = container.getInputMessage(1)
messageBody = Long.parseLong(message.getBodyContentAsString())
#if inputPortNr == 1:
print "input 1: ",messageBody
n_steps = messageBody


message = container.getInputMessage(2)
messageBody = Double.parseDouble(message.getBodyContentAsString())
print "input 2: ",messageBody
integration_time = messageBody

message = container.getInputMessage(3)
messageBody = message.getBodyContentAsString()
print "input 3: ",messageBody
stringTable = messageBody.split(",")
start_position_actuators_1D = []
for i in stringTable:
		start_position_actuators_1D.append(Double.parseDouble(i))
#===============================================
# Get all parameters from file
#===============================================
parameterScan()
		
コード例 #51
0
import sys

if sys.platform.startswith('java'):
    from java.lang import String, Integer, Long, Float, Short, Double

    varz = {
        'java_string_int': String('1'),
        'java_string_float': String('1.1'),
        'java_string_hex': String('F00'),
        'java_string_embedded_base': String('0xf00'),
        'java_string_invalid': String('foobar'),
        'java_integer': Integer(1),
        'java_long': Long(1),
        'java_short': Short(1),
        'java_float': Float(1.1),
        'java_double': Double(1.1)
    }

else:
    varz = {}


class MyObject:
    def __init__(self, value):
        self.value = value

    def __int__(self):
        return 42 / self.value

    def __str__(self):
        return 'MyObject'
コード例 #52
0
def spireMonoBeamSrc(freqx,beamRad,beamProfs,beamConst,effFreq,gamma,srcProf,array):
    """
    ========================================================================
    Implements the full beam model, convolved with a source profile,
    to generate the monochromatic beam profile and corresponding monochromatic
    beam solid angle at a given frequency.

    Inputs:
      freqx:     (float) frequency [Hz] for which monochromatic beam
                   profile and area should be calculated
      beamRad:   (array float) radius vector from the input beam profiles
      beamProfs: (dataset) PhotRadialCorrBeam object
                   [used to retrieve core beam profile]
      beamConst: (array float) constant part of beam profile for "array"
                       [passed to prevent repeated calls]
      effFreq:   (float) effective frequency [Hz] of array
      gamma:     (float) Exponent of powerlaw describing FWHM dependence
                   on frequency
      srcProf:   (array float) source density profile, corresponding to
                   radius column in beamProfs
      array:     (string) spire array ('Psw'|'Pmw'|'Plw')

    Outputs:     (list of objects)
                (float) Beam area [arcsec^2] at frequency freqx

    Calculation:
      Scales the core beam profile width as (freqx/effFreq)^gamma.
      Queries the calibration file to generate new core beam profile.
      Uses constant beam profile where it is larger than core profile.
      Multiplies by a source profile
      Integrates over radius to calculate beam area.

    Dependencies:
      herschel.ia.numeric.toolbox.interp.LinearInterpolator
      herschel.ia.numeric.toolbox.integr.TrapezoidalIntegrator
      
    2013/12/19  C. North  initial version

    """

    
    #calculate the "scaled" radius, as nu^-gamma
    radNew=beamRad*(freqx/effFreq)**-gamma
    maxRad=max(beamRad)
    nRad=len(beamRad)
    #ensure it doesn't go out of range
    radNew[radNew.where(radNew > maxRad)]=maxRad
    #get the corresponding beam profiles
    beamNew=Double1d(nRad)
    for r in range(nRad):
        beamNew[r]=beamProfs.getCoreCorrection(radNew[r],array)
    #apply the "constant" beam where appropriate
    #beamConst=beamProfs.getConstantCorrectionTable().getColumn(array).data
    isConst=beamNew.where(beamNew < beamConst)
    beamNew[isConst]=beamConst[isConst]

    #copy source Profile and multiply by beam
    beamNew = srcProf.copy().mult(beamNew,key='Src x Beam')
    beamMonoArea = beamNew.calcArea()
    
    if beamMonoArea==0:
        print 'calculated area=0'
        #try just the source
        srcArea=srcProf.calcArea(forceAnalytical=True)
        if Double.isNaN(srcArea):
            #no analytical source
            print 'Source is very small. No analytical area for source'
        else:
            print 'Source is very small. Replacing area with analytical area of source'
            beamMonoArea=srcArea


    ## THIS IS ONLY VALID FOR AREA
    ## FULL PROFILE OF CONVOLUTION REQUIRES PROPER CONVOLUTION

    #integrate to get solid angle (in arcsec^2)    
    #beamNew=beamNew * srcProf.profile
    #beamInterp=LinearInterpolator(beamRad,beamNew * 2. * PI * beamRad)
    #integrator=TrapezoidalIntegrator(0,maxRad)
    #beamMonoArea=integrator.integrate(beamInterp)

    return (beamMonoArea,beamNew.profile)
コード例 #53
0
    def run_sim(self):
        episoderunning = True

        # starting belief state
        currbelief = initBelief
        factoredS = initState
        instance = 1
        cumrew = 0
        run = 1
        # execution loop
        # while(episoderunning):
        while (run <= 100):
            # draw current state
            # self.draw_state(factoredS)

            # extract action from direct controller - ie., 0-step LA
            exreward = valueFunction.V(currbelief)
            action = valueFunction.directControl(currbelief)
            print "value of b %f and selected action %d" % (exreward, action)

            # show action that we are about to execute
            self.nactLbl.setText(pomdpProblem.getactStr(action))
            time.sleep(1)

            # sample new state, observation, and calculate reward
            print factoredS
            factoredS1 = pomdpProblem.sampleNextState(factoredS, action)
            print " sampled state is"
            print factoredS1
            factoredO = pomdpProblem.sampleObservation(factoredS, factoredS1,
                                                       action)
            print " sampled o is"
            print factoredO
            reward = pomdpProblem.getReward(factoredS, action)
            print reward

            # draw new state, and display what's happening
            self.draw_state(factoredS1)
            self.lactLbl.setText(pomdpProblem.getactStr(action))
            self.nactLbl.setText("nil")
            self.rewLbl.setText(Double.toString(reward))
            cumrew = cumrew + reward * gamma**instance
            self.crewLbl.setText(Double.toString(cumrew))
            self.obsLbl.setText(
                pomdpProblem.getobsStr(
                    pomdpProblem.sencode(factoredO, pomdpProblem.getnrObsV(),
                                         pomdpProblem.getobsArity()) - 1))

            # iterate
            nextbelief = pomdpProblem.tao(
                currbelief, action,
                pomdpProblem.sencode(factoredO, pomdpProblem.getnrObsV(),
                                     pomdpProblem.getobsArity()) - 1)
            currbelief = nextbelief
            factoredS = factoredS1
            instance = instance + 1

            # step button
            if self.stepChk.isSelected() == True:
                self.stepBtn.setEnabled(True)
            while self.stepBtn.isEnabled() == True:
                time.sleep(1)

            # check whether this episode has ended
            #if reward == CATCH_REWARD - 1:
            #    print "Episode ended!"
            #    episoderunning = false

            # smooth the sim a little in case we're not stepping
            time.sleep(1)

            # stop after 100 iterations
            if instance == 100:
                run = run + 1
                stats.append(cumrew)
                currbelief = initBelief
                factoredS = initState
                cumrew = 0
                instance = 1

        print stats
コード例 #54
0
def nonlinear_fit():
    global Plot3
    valid = []
    vaxes = []
    for i in xrange(peak_res.size):
        if not Double.isNaN(peak_res[i]):
            valid.append(peak_res[i] * -1)
            vaxes.append(twod[i])
    if len(valid) == 0:
        slog('Error: there is not any available peak.')
        return
    ds3 = Dataset(valid, axes=[vaxes])
    Plot3.set_dataset(ds3)
    ds = Plot3.ds
    if len(ds) == 0:
        print 'Error: no curve to fit in Plot3'
        return
    for d in ds:
        if d.title == 'nonlinear_fit':
            Plot3.remove_dataset(d)
    d3 = ds[0]
    cur = d3 * math.pi / 180
    function = '2*asin(k1/x[0])+k2'
    fitting = UndefinedFitting(function, 'Energy')
    fitting.set_histogram(cur)
    m = 1.67492861e-027
    h = 6.626068e-034
    eV = 1.60217646e-019
    pl = 1.0e10
    l = h * pl * 100 / math.sqrt(linear_slope.value * eV * 20 * m)
#    if lambda_fit.value == 0 and s2_offset.value == 0:
#        fitting.set_param('k1', 0)
##        fitting.set_param('k2', 0)
#    else:
#        fitting.set_param('k1', lambda_fit.value)
#        fitting.set_param('k2', s2_offset.value)
    try:
        v_lmd = lmd.value
    except:
        v_lmd = 0
    fitting.set_param('k1', v_lmd)
    fitting.set_param('k2', 0)
    fitting.fitter.setResolutionMultiple(10)
#    fitting.fitter.getRawFitter().fitParameterSettings("k1").setStepSize(0.00001);
#    fitting.fitter.getRawFitter().fitParameterSettings("k2").setStepSize(0.00001);
    for i in xrange(5):
        res = fitting.fit()
        lambda_fit.value = fitting.k1
        s2_offset.value = fitting.k2 * 180 / math.pi
        fit_quality.value = fitting.fitter.getQuality()
        fitting = UndefinedFitting(function, 'Energy')
        fitting.set_histogram(cur)
        fitting.set_param('k1', lambda_fit.value)
    res.var[:] = 0
    res.title = 'nonlinear_fit'
    res = res * 180 / math.pi
    Plot3.add_dataset(res)
#    lambda_fit.value = fitting.k1
#    s2_offset.value = fitting.k2 * 180 / math.pi
#    fit_quality.value = fitting.fitter.getQuality()
    m1_new.value = math.asin(lambda_fit.value / 2 / D_space) * 180 / math.pi
    m2_new.value = 2 * m1_new.value
    slog('Chi2 = ' + str(fit_quality.value))
    slog('lambda = ' + str(lambda_fit.value))
    slog('meV = ' + str((h * pl / lambda_fit.value / m) ** 2 * m * 500 / eV))
    slog('two-theta_offset = ' + str(s2_offset.value))