Example #1
0
  /**
   * Creates a Track and adds its contents to the DB layer (adapter).
   *
   * @param json the input json object
   * @param adapter the DB layer adapter
   * @return the Track object
   * @throws JSONException parsing fails or contains unexpected properties
   * @throws ParseException if DateTime parsing fails
   */
  public static Track fromJson(JSONObject json, DbAdapter adapter)
      throws JSONException, ParseException {
    JSONObject trackProperties = json.getJSONObject("properties");
    Track t = Track.createRemoteTrack(trackProperties.getString("id"), adapter);
    String trackName = "unnamed Track #" + t.getId();
    try {
      trackName = trackProperties.getString("name");
    } catch (JSONException e) {
      logger.warn(e.getMessage(), e);
    }

    t.setName(trackName);
    String description = "";
    try {
      description = trackProperties.getString("description");
    } catch (JSONException e) {
      logger.warn(e.getMessage(), e);
    }

    t.setDescription(description);
    JSONObject sensorProperties =
        trackProperties.getJSONObject("sensor").getJSONObject("properties");

    t.setCar(Car.fromJson(sensorProperties));
    // include server properties tracks created, modified?

    t.dbAdapter.updateTrack(t);
    // Log.i("track_id",t.getId()+" "+((DbAdapterRemote)
    // dbAdapter).trackExistsInDatabase(t.getId())+" "+dbAdapter.getNumberOfStoredTracks());

    Measurement recycleMeasurement;

    List<Measurement> measurements = new ArrayList<Measurement>();
    JSONArray features = json.getJSONArray("features");
    logger.info(
        "Parsing measurements of track " + t.getRemoteID() + ". Count: " + features.length());
    for (int j = 0; j < features.length(); j++) {
      JSONObject measurementJsonObject = features.getJSONObject(j);
      recycleMeasurement = Measurement.fromJson(measurementJsonObject);

      recycleMeasurement.setTrack(t);
      measurements.add(recycleMeasurement);
    }

    t.setMeasurementsAsArrayList(measurements);
    logger.info("Storing measurements in database");
    t.storeMeasurementsInDbAdapter();
    return t;
  }
Example #2
0
 /**
  * Returns the average co2 emission for the track.
  *
  * @return
  */
 public double getCO2Average() {
   double co2Average = 0.0;
   try {
     for (Measurement measurement : measurements) {
       if (measurement.getProperty(CONSUMPTION) != null) {
         co2Average =
             co2Average
                 + consumptionAlgorithm.calculateCO2FromConsumption(
                     measurement.getProperty(CONSUMPTION));
       }
     }
     co2Average = co2Average / measurements.size();
   } catch (FuelConsumptionException e) {
     logger.warn(e.getMessage(), e);
   }
   return co2Average;
 }
Example #3
0
 /**
  * Scales a Recipe to a nutritional target. This assumes that the member will eat that one meal
  * for the day, and that's it.
  *
  * <p>If this is not the case and the member plans on eating more than one meal for the day, then
  * just call .scale(double factor) behind it with some fraction like 1.0/3.0'rd of the day.
  *
  * @param nutrientName The nutrient to scale to recipe to.
  * @param goal The member's nutritional target.
  * @return The ideal Recipe for the nutritional goal specified.
  */
 public static Recipe scaleToNutritionalTarget(
     Recipe recipe, String nutrientName, Measurement goal) {
   // get the nutrient from the recipe
   Measurement nutrient = recipe.nutritionInformation.getNutrient(nutrientName);
   // check for nutrient existance, it may not exist. if it doesn't, then there is nothing to scale
   // toward
   if (nutrient != null) {
     // gather information
     double recipeNutrientQuantity = nutrient.getQuantity();
     double goalQuantity = goal.getQuantity();
     // calculate how many times you would have to make a recipe to reach your exact goal
     double scaleFactor = goalQuantity / recipeNutrientQuantity;
     // now scale the Recipe
     return recipe.scale(scaleFactor);
   } else
     // nothing else to do here, make a copy of self and go on
     return new Recipe(recipe);
 }
Example #4
0
 private void report() {
   Measurement m = new Measurement();
   m.time = this.time;
   m.carArrived = this.carArrived;
   m.carDeparted = this.carDeparted;
   m.carOnRoad = this.carOnRoad;
   m.pedArrived = this.pedArrived;
   m.pedDeparted = this.pedDeparted;
   m.pedOnRoad = this.pedOnRoad;
   this.ms.add(m);
 }
  public void _testBlock() {
    Measurement m = new Measurement();
    final Object o = new Object();
    final Thread current = Thread.currentThread();
    Thread x =
        new Thread() {
          @Override
          public void run() {
            System.out.println("started");
            synchronized (o) {
              System.out.println("in synchronized block");
              System.out.println("state of starting thread " + current.getState());
              System.out.println("notifyAll");
              o.notifyAll();
            }
          }
        };
    m.start();

    synchronized (o) {
      System.out.println("starting");
      x.start();

      try {
        System.out.println("state of notifying thread " + x.getState());
        System.out.println("waiting");
        o.wait();
        System.out.println("done waiting");
      } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }
    }
    m.stop();

    try {
      x.join();
    } catch (InterruptedException e) {
      e.printStackTrace();
    }
    Assert.assertEquals(0, m.getBlockCountDelta());
    Assert.assertEquals(1, m.getWaitCountDelta());
  }
Example #6
0
  /** Seed the conversion using a last measurement */
  public Measurement convert(Reading r, Measurement last) {
    if (last != null) {
      this.Xt = last.getX();
      this.Yt = last.getY();
      this.Zt = last.getZ();
    }

    // if the last measurement failed, set back to origin
    if (this.Xt > 9.E99) {
      this.Xt = 0;
    }
    if (this.Yt > 9.E99) {
      this.Yt = 0;
    }
    if (this.Zt > 9.E99) {
      this.Zt = 0;
    }

    return convert(r);
  }
Example #7
0
 public boolean pass(Measurement measurement) {
   boolean pass = false;
   if (measurement.location == null) {
     // ignore
   } else if (lastMeasurement == null) {
     pass = true;
   } else {
     if (measurement.distance(lastMeasurement) > minDistance) pass = true;
     if (!measurement.cell.equals(lastMeasurement.cell)) pass = true;
   }
   if (pass) lastMeasurement = measurement;
   return pass;
 }
  private void processWeatherStation(WeatherStation weatherStation)
      throws IOException, HttpException {

    List<Measurement> measurements = weatherStation.fetchMeasurement();

    for (Measurement measurement : measurements) {
      httpClient.sendHttpRequest(measurement);

      DateTime now = new DateTime();
      DateTimeFormatter fmt = DateTimeFormat.mediumDateTime();

      String name =
          (measurements.size() == 1) ? weatherStation.getName() : measurement.getStationName();

      log(
          fmt.print(now)
              + " Executed HTTP request, for "
              + name
              + " : "
              + measurement.toVindSidenUrl());
    }
  }
Example #9
0
 /**
  * Use this method only to insert "fresh" measurements, not to recreate a Track from the database
  * Use {@code insertMeasurement(ArrayList<Measurement> measurements)} instead Inserts measurments
  * into the Track and into the database!
  *
  * @param measurement
  * @throws TrackAlreadyFinishedException
  * @throws MeasurementsException
  */
 public void addMeasurement(Measurement measurement) throws TrackAlreadyFinishedException {
   measurement.setTrack(Track.this);
   this.measurements.add(measurement);
   if (this.dbAdapter != null) {
     try {
       this.dbAdapter.insertNewMeasurement(measurement);
     } catch (MeasurementsException e) {
       logger.severe("This should never happen", e);
       return;
     }
   } else {
     logger.warn("DbAdapter was null! Could not insert measurement");
   }
 }
Example #10
0
  public void testLasix() {
    Measurement m = parser.parse(20d, "Lasix 20 mg p.o.", 9);
    assertNotNull(m);

    assertEquals("mass", m.getDimension());

    assertEquals(20d, m.getValue());
    assertEquals("mg", m.getUnit());
    assertEquals("mg", m.getParsedText());

    assertEquals(2.0E-5, m.getNormalizedValue());
    assertEquals("kg", m.getNormalizedUnit());
  }
Example #11
0
  public void test6Inches() {
    Measurement m = parser.parse(6d, "Mark was 6 feet 6 inches tall.", 18);
    assertNotNull(m);

    assertEquals("length", m.getDimension());

    assertEquals(6d, m.getValue());
    assertEquals("inches", m.getUnit());
    assertEquals("inches", m.getParsedText());

    assertEquals(0.1524, m.getNormalizedValue());
    assertEquals("m", m.getNormalizedUnit());
  }
  public void measurement(boolean count, boolean time, int c) {
    Measurement m = new Measurement();
    m.start();
    Measurement t = new Measurement(time, count);

    for (int i = 0; i < c; i++) {
      t.start();
      t.stop();
    }
    m.stop();
    System.out.println(
        time
            + "/"
            + count
            + " "
            + c
            + " measurements took: "
            + Long.toString(m.getElapsedTime() / 1000)
            + " us, on average "
            + Double.toString(m.getElapsedTime() / c)
            + " ns");
  }
  public void testMeasure() throws InterruptedException {

    Measurement m = new Measurement();
    m.start();
    Object o = new Object();
    synchronized (o) {
      o.wait(500);
    }
    long j = 0;
    for (int i = 0; i < 6000000; i++) {
      j = j + (j * i);
    }
    m.stop();
    long t = m.getElapsedTime();
    System.out.println("elapsed: " + t);
    long c = m.getElapsedCpuTime();
    System.out.println(c);
    long u = m.getElapsedUserTime();
    System.out.println(u);
    long b = m.getBlockCountDelta();
    System.out.println(b);
    long w = m.getWaitCountDelta();
    System.out.println(w);
  }
Example #14
0
  public String toString() {
    String str = "";

    str +=
        "Name: "
            + mName
            + "\n"
            + "Yield: "
            + mYield.getValue()
            + " "
            + mYield.getUnit()
            + "\n"
            + "Prep time: "
            + mPrepTime
            + "\n"
            + "Cook time: "
            + mCookTime
            + "\n"
            + "Overall time: "
            + mOverallTime
            + "\n"
            + "Ingredients list: \n";

    // Iterate through the ingredients
    Vector<MeasurementAndIngredient> measAndIngs = mIngredients.getIngredients();

    MeasurementAndIngredient curMeasAndIng;
    Measurement curMeas;
    Measurement curMeas2;
    Ingredient curIng;
    for (int i = 0; i < measAndIngs.size(); i++) {
      curMeasAndIng = measAndIngs.get(i);
      curMeas = curMeasAndIng.getMeasurement();
      curMeas2 = curMeasAndIng.getMeasurement2();
      curIng = curMeasAndIng.getIngredient();
      str += i + ") ";
      if (curMeas != null) {
        str +=
            "Measurment = "
                + curMeas.getAmount()
                + " "
                + curMeas.getSpecifier()
                + " "
                + curMeas.getUnit();
      }
      if (curMeas2 != null) {
        str +=
            "Measurment 2 = "
                + curMeas2.getAmount()
                + " "
                + curMeas2.getSpecifier()
                + " "
                + curMeas2.getUnit();
      }
      if (curIng != null) {
        str += "    Ingredient = " + curIng.getName();
        String specDir = curIng.getSpecialDirections();
        if (specDir != null && !specDir.equals("")) {
          if (specDir.charAt(0) == ',') {
            str += curIng.getSpecialDirections();
          } else {
            str += " " + curIng.getSpecialDirections();
          }
        }
        str += "\n";
      }
    }

    // Cool! All that's left is directions.
    str += "Directions: \n" + mDirections;

    // Return that new string.
    return str;
  }
Example #15
0
 public int getId() {
   return iId.getId();
 }
Example #16
0
  Collection<MeasurementSite> process(File tmp, String stateCode, String countyCode)
      throws Exception {
    HashMap<String, MeasurementSite> data = new HashMap<String, MeasurementSite>();

    String source = downloadSiteInfo1(tmp, stateCode, countyCode.replaceAll(":", "%3A"));

    BufferedReader readbuffer1 = new BufferedReader(new FileReader(new File(tmp, "sites.txt")));
    String line1;
    boolean first1 = true;
    int counter = 0;
    while ((line1 = readbuffer1.readLine()) != null) {
      if (first1) {
        first1 = false;
        continue;
      }
      counter++;
      String parts[];
      parts = split(line1, "\t");
      String loc_id = parts[2];
      String label = parts[3];
      String lat = parts[11];
      String longitude = parts[12];
      String country_code = parts[24];
      String state_code = parts[25];
      String county_code = parts[26];
      MeasurementSite x =
          new MeasurementSite(
              loc_id,
              label,
              Double.parseDouble(lat),
              Double.parseDouble(longitude),
              country_code,
              Integer.parseInt(state_code),
              Integer.parseInt(county_code));
      x.setSourceDocument(source, counter);
      data.put(x.getID(), x);
    }

    source = downloadSiteInfo2(tmp, stateCode, countyCode.replaceAll(":", "%3A"));
    BufferedReader readbuffer2 = new BufferedReader(new FileReader(new File(tmp, "data.txt")));
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    String line2;
    boolean first2 = true;
    counter = 0;
    while ((line2 = readbuffer2.readLine()) != null) {
      if (first2) {
        first2 = false;
        continue;
      }
      String parts[];
      parts = split(line2, "\t");
      String ID = parts[21];
      String date = parts[6];
      String time = parts[7];
      String chemical = parts[31];
      String value = parts[33];
      String unit = parts[34];

      MeasurementSite temp = data.get(ID);
      if (value.equals("")) value = "0";
      if (date.equals("") || time.equals("")) continue;
      Measurement x =
          new Measurement(
              ID, counter++, sdf.parse(date), time, chemical, Double.parseDouble(value), unit);
      x.setSourceDocument(source, counter);
      temp.addData(x);
    }
    return data.values();
  }