Example usage for org.json JSONObject getDouble

List of usage examples for org.json JSONObject getDouble

Introduction

In this page you can find the example usage for org.json JSONObject getDouble.

Prototype

public double getDouble(String key) throws JSONException 

Source Link

Document

Get the double value associated with a key.

Usage

From source file:com.andrew67.ddrfinder.adapters.MapLoaderV1.java

@Override
protected ApiResult doInBackground(LatLngBounds... boxes) {
    // Fetch machine data in JSON format
    JSONArray jArray = new JSONArray();
    try {/* w w  w  .ja  v  a 2 s. c o  m*/
        if (boxes.length == 0)
            throw new IllegalArgumentException("No boxes passed to doInBackground");
        final LatLngBounds box = boxes[0];

        final OkHttpClient client = new OkHttpClient();
        final String LOADER_API_URL = sharedPref.getString(SettingsActivity.KEY_PREF_API_URL, "");
        final HttpUrl requestURL = HttpUrl.parse(LOADER_API_URL).newBuilder()
                .addQueryParameter("source", "android")
                .addQueryParameter("latupper", "" + box.northeast.latitude)
                .addQueryParameter("longupper", "" + box.northeast.longitude)
                .addQueryParameter("latlower", "" + box.southwest.latitude)
                .addQueryParameter("longlower", "" + box.southwest.longitude).build();

        Log.d("api", "Request URL: " + requestURL);
        final Request get = new Request.Builder().header("User-Agent", BuildConfig.APPLICATION_ID + " "
                + BuildConfig.VERSION_NAME + "/Android?SDK=" + Build.VERSION.SDK_INT).url(requestURL).build();

        final Response response = client.newCall(get).execute();
        final int statusCode = response.code();
        Log.d("api", "Status code: " + statusCode);

        // Data loaded OK
        if (statusCode == 200) {
            final String jResponse = response.body().string();
            Log.d("api", "Raw API result: " + jResponse);
            jArray = new JSONArray(jResponse);
        }
        // Code used for invalid parameters; in this case exceeding
        // the limits of the boundary box
        else if (statusCode == 400) {
            return new ApiResultV1(ApiResultV1.ERROR_ZOOM);
        }
        // Unexpected error code
        else {
            return new ApiResultV1(ApiResultV1.ERROR_API);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

    // Return list
    ArrayList<ArcadeLocation> out = new ArrayList<>();
    try {
        for (int i = 0; i < jArray.length(); ++i) {
            final JSONObject obj = (JSONObject) jArray.get(i);
            final String name = obj.getString("name");

            boolean closed = false;
            if (ArcadeLocation.CLOSED.matcher(name).matches()) {
                closed = true;
            }
            // Fields added after ddr-finder 1.0 API should be
            // explicitly tested for, in order to maintain
            // compatibility with deployments of older versions
            boolean hasDDR = false;
            if (obj.has("hasDDR") && obj.getInt("hasDDR") == 1) {
                hasDDR = true;
            }

            out.add(new ArcadeLocationV1(obj.getInt("id"), name, obj.getString("city"),
                    new LatLng(obj.getDouble("latitude"), obj.getDouble("longitude")), hasDDR, closed));
        }
    } catch (Exception e) {
        out.clear();
    }
    return new ApiResultV1(out, boxes[0]);
}

From source file:com.lhings.java.http.WebServiceCom.java

public static Map<String, Object> getStatus(LhingsDevice lhingsDevice, String uuid)
        throws LhingsException, IOException {
    String url = LHINGS_V1_API_PREFIX + "devices/" + uuid + "/states";
    String json = executeGet(url, lhingsDevice.apiKey());
    Map<String, Object> returnValue = new HashMap<String, Object>();
    JSONArray array = new JSONArray(json);
    for (int j = 0; j < array.length(); j++) {
        JSONObject statusComponent = array.getJSONObject(j);
        String statusCompName = statusComponent.getString("name");
        String statusCompType = statusComponent.getString("type");
        Object statusCompValue;// ww  w  .j a  v a 2  s  .c o m
        if (statusCompType.equals("integer"))
            statusCompValue = statusComponent.getInt("value");
        else if (statusCompType.equals("float"))
            statusCompValue = (float) statusComponent.getDouble("value");
        else if (statusCompType.equals("timestamp"))
            statusCompValue = new Date((long) statusComponent.getInt("value") * 1000);
        else if (statusCompType.equals("boolean"))
            statusCompValue = statusComponent.getBoolean("value");
        else
            statusCompValue = statusComponent.getString("value");
        returnValue.put(statusCompName, statusCompValue);
    }
    return returnValue;
}

From source file:org.mixare.data.convert.MixareDataProcessor.java

@Override
public List<Marker> load(String rawData, int taskId, int colour) throws JSONException {
    List<Marker> markers = new ArrayList<Marker>();
    JSONObject root = convertToJSON(rawData);
    JSONArray dataArray = root.getJSONArray("results");
    int top = Math.min(MAX_JSON_OBJECTS, dataArray.length());

    for (int i = 0; i < top; i++) {
        JSONObject jo = dataArray.getJSONObject(i);

        Marker ma = null;/*from w ww .  ja  va  2  s  . c  om*/
        if (jo.has("title") && jo.has("lat") && jo.has("lng") && jo.has("elevation")) {

            String id = "";
            if (jo.has("id"))
                id = jo.getString("id");

            Log.v(MixView.TAG, "processing Mixare JSON object");
            String link = null;

            if (jo.has("has_detail_page") && jo.getInt("has_detail_page") != 0 && jo.has("webpage"))
                link = jo.getString("webpage");

            ma = new POIMarker(id, HtmlUnescape.unescapeHTML(jo.getString("title"), 0), jo.getDouble("lat"),
                    jo.getDouble("lng"), jo.getDouble("elevation"), link, taskId, colour);
            markers.add(ma);
        }
    }
    return markers;
}

From source file:com.whalesocks.sunshine.FetchWeatherTask.java

/**
 * Take the String representing the complete forecast in JSON Format and
 * pull out the data we need to construct the Strings needed for the wireframes.
 *
 * Fortunately parsing is easy:  constructor takes the JSON string and converts it
 * into an Object hierarchy for us.//from w ww.  j a v a  2  s.  c  om
 */
private void getWeatherDataFromJson(String forecastJsonStr, String locationSetting) throws JSONException {

    // Now we have a String representing the complete forecast in JSON Format.
    // Fortunately parsing is easy:  constructor takes the JSON string and converts it
    // into an Object hierarchy for us.

    // These are the names of the JSON objects that need to be extracted.

    // Location information
    final String OWM_CITY = "city";
    final String OWM_CITY_NAME = "name";
    final String OWM_COORD = "coord";

    // Location coordinate
    final String OWM_LATITUDE = "lat";
    final String OWM_LONGITUDE = "lon";

    // Weather information.  Each day's forecast info is an element of the "list" array.
    final String OWM_LIST = "list";

    final String OWM_PRESSURE = "pressure";
    final String OWM_HUMIDITY = "humidity";
    final String OWM_WINDSPEED = "speed";
    final String OWM_WIND_DIRECTION = "deg";

    // All temperatures are children of the "temp" object.
    final String OWM_TEMPERATURE = "temp";
    final String OWM_MAX = "max";
    final String OWM_MIN = "min";

    final String OWM_WEATHER = "weather";
    final String OWM_DESCRIPTION = "main";
    final String OWM_WEATHER_ID = "id";

    try {
        JSONObject forecastJson = new JSONObject(forecastJsonStr);
        JSONArray weatherArray = forecastJson.getJSONArray(OWM_LIST);

        JSONObject cityJson = forecastJson.getJSONObject(OWM_CITY);
        String cityName = cityJson.getString(OWM_CITY_NAME);

        JSONObject cityCoord = cityJson.getJSONObject(OWM_COORD);
        double cityLatitude = cityCoord.getDouble(OWM_LATITUDE);
        double cityLongitude = cityCoord.getDouble(OWM_LONGITUDE);

        long locationId = addLocation(locationSetting, cityName, cityLatitude, cityLongitude);

        // Insert the new weather information into the database
        Vector<ContentValues> cVVector = new Vector<ContentValues>(weatherArray.length());

        // OWM returns daily forecasts based upon the local time of the city that is being
        // asked for, which means that we need to know the GMT offset to translate this data
        // properly.

        // Since this data is also sent in-order and the first day is always the
        // current day, we're going to take advantage of that to get a nice
        // normalized UTC date for all of our weather.

        Time dayTime = new Time();
        dayTime.setToNow();

        // we start at the day returned by local time. Otherwise this is a mess.
        int julianStartDay = Time.getJulianDay(System.currentTimeMillis(), dayTime.gmtoff);

        // now we work exclusively in UTC
        dayTime = new Time();

        for (int i = 0; i < weatherArray.length(); i++) {
            // These are the values that will be collected.
            long dateTime;
            double pressure;
            int humidity;
            double windSpeed;
            double windDirection;

            double high;
            double low;

            String description;
            int weatherId;

            // Get the JSON object representing the day
            JSONObject dayForecast = weatherArray.getJSONObject(i);

            // Cheating to convert this to UTC time, which is what we want anyhow
            dateTime = dayTime.setJulianDay(julianStartDay + i);

            pressure = dayForecast.getDouble(OWM_PRESSURE);
            humidity = dayForecast.getInt(OWM_HUMIDITY);
            windSpeed = dayForecast.getDouble(OWM_WINDSPEED);
            windDirection = dayForecast.getDouble(OWM_WIND_DIRECTION);

            // Description is in a child array called "weather", which is 1 element long.
            // That element also contains a weather code.
            JSONObject weatherObject = dayForecast.getJSONArray(OWM_WEATHER).getJSONObject(0);
            description = weatherObject.getString(OWM_DESCRIPTION);
            weatherId = weatherObject.getInt(OWM_WEATHER_ID);

            // Temperatures are in a child object called "temp".  Try not to name variables
            // "temp" when working with temperature.  It confuses everybody.
            JSONObject temperatureObject = dayForecast.getJSONObject(OWM_TEMPERATURE);
            high = temperatureObject.getDouble(OWM_MAX);
            low = temperatureObject.getDouble(OWM_MIN);

            ContentValues weatherValues = new ContentValues();

            weatherValues.put(WeatherEntry.COLUMN_LOC_KEY, locationId);
            weatherValues.put(WeatherEntry.COLUMN_DATE, dateTime);
            weatherValues.put(WeatherEntry.COLUMN_HUMIDITY, humidity);
            weatherValues.put(WeatherEntry.COLUMN_PRESSURE, pressure);
            weatherValues.put(WeatherEntry.COLUMN_WIND_SPEED, windSpeed);
            weatherValues.put(WeatherEntry.COLUMN_DEGREES, windDirection);
            weatherValues.put(WeatherEntry.COLUMN_MAX_TEMP, high);
            weatherValues.put(WeatherEntry.COLUMN_MIN_TEMP, low);
            weatherValues.put(WeatherEntry.COLUMN_SHORT_DESC, description);
            weatherValues.put(WeatherEntry.COLUMN_WEATHER_ID, weatherId);

            cVVector.add(weatherValues);
        }

        int inserted = 0;
        // add to database
        if (cVVector.size() > 0) {
            // Student: call bulkInsert to add the weatherEntries to the database here
            ContentValues[] cvArray = new ContentValues[cVVector.size()];
            cVVector.toArray(cvArray);
            inserted = mContext.getContentResolver().bulkInsert(WeatherEntry.CONTENT_URI, cvArray);
        }

        //            // Sort order:  Ascending, by date.
        //            String sortOrder = WeatherEntry.COLUMN_DATE + " ASC";
        //            Uri weatherForLocationUri = WeatherEntry.buildWeatherLocationWithStartDate(
        //                    locationSetting, System.currentTimeMillis());
        //
        //            // Students: Uncomment the next lines to display what what you stored in the bulkInsert
        //
        //            Cursor cur = mContext.getContentResolver().query(weatherForLocationUri,
        //                    null, null, null, sortOrder);
        //
        //            cVVector = new Vector<ContentValues>(cur.getCount());
        //            if ( cur.moveToFirst() ) {
        //                do {
        //                    ContentValues cv = new ContentValues();
        //                    DatabaseUtils.cursorRowToContentValues(cur, cv);
        //                    cVVector.add(cv);
        //                } while (cur.moveToNext());
        //            }

        Log.d(LOG_TAG, "FetchWeatherTask Complete. " + cVVector.size() + " Inserted");

        //            String[] resultStrs = convertContentValuesToUXFormat(cVVector);
        //            return resultStrs;

    } catch (JSONException e) {
        Log.e(LOG_TAG, e.getMessage(), e);
        e.printStackTrace();
    }
    //        return null;
}

From source file:com.maya.portAuthority.googleMaps.LocationTracker.java

/**
 * Case 1: Request returns list of Coordinates
 * Proceed to Step 2/* w  w w . j a va 2  s  . c o  m*/
 * 
 * Case 2: Unable to understand source location
 * Ask user to try again.
        
 * 
 * @param json returned by striking the Google maps API
 * @param limit set limit to the number of places returned by the API
 * @return
 * @throws JSONException 
 */
public static List<Location> getLatLngDetails(JSONObject json, int limit)
        throws JSONException, InvalidInputException {
    List<Location> output = new ArrayList<>();

    JSONArray results = json.getJSONArray("results");
    log.debug("JSON Results Size={}", results.length());
    if (results.length() == 0) {
        throw new InvalidInputException("No results from JSON", "I did not understand the source location");
    }
    int numResultsToReturn = Math.min(limit, results.length());

    JSONObject result;
    JSONObject location;

    for (int i = 0; i < numResultsToReturn; i++) {
        result = results.getJSONObject(i);

        location = result.getJSONObject("geometry").getJSONObject("location");
        Location c = new Location(result.getString("name"), location.getDouble("lat"),
                location.getDouble("lng"), result.getString("formatted_address"),
                makeList(result.getJSONArray("types")));

        output.add(c);
    }
    return output;
}

From source file:com.maya.portAuthority.googleMaps.LocationTracker.java

public static List<Stop> getStopDetails(JSONObject json) throws JSONException {
    List<Stop> stops = new ArrayList<>();
    JSONArray stopsResponse = json.getJSONObject("bustime-response").getJSONArray("stops");

    if (stopsResponse != null) {
        for (int i = 0; i < stopsResponse.length(); i++) {
            JSONObject stop = stopsResponse.getJSONObject(i);
            double lat = stop.getDouble("lat");
            double lon = stop.getDouble("lon");
            String stopID = stop.getString("stpid");
            String stpnm = stop.getString("stpnm");
            Stop s = new Stop(stopID, stpnm, lat, lon);
            stops.add(s);//from   w w  w . j a  va  2s  . c  o  m
        }
    }
    return stops;
}

From source file:com.panduka.weatherforecast.utils.DataResolver.java

private HourlyData createHourlyData(JSONObject jsonObject) throws JSONException {
    HourlyData hourlyData = new HourlyData();
    hourlyData.time = jsonObject.getLong("time");
    hourlyData.summary = jsonObject.getString("summary");
    hourlyData.icon = jsonObject.getString("icon");
    hourlyData.precipIntensity = jsonObject.getDouble("precipIntensity");
    hourlyData.precipProbability = jsonObject.getDouble("precipProbability");
    hourlyData.temperature = jsonObject.getDouble("temperature");
    hourlyData.apparentTemperature = jsonObject.getDouble("apparentTemperature");
    hourlyData.dewPoint = jsonObject.getDouble("dewPoint");
    hourlyData.humidity = jsonObject.getDouble("humidity");
    hourlyData.windSpeed = jsonObject.getDouble("windSpeed");
    hourlyData.windBearing = jsonObject.getInt("windBearing");
    hourlyData.cloudCover = jsonObject.getDouble("cloudCover");
    hourlyData.pressure = jsonObject.getDouble("pressure");
    hourlyData.ozone = jsonObject.getDouble("ozone");
    return hourlyData;
}

From source file:com.panduka.weatherforecast.utils.DataResolver.java

private DailyData createDailyData(JSONObject jsonObject) throws JSONException {
    DailyData dailyData = new DailyData();
    dailyData.time = jsonObject.getLong("time");
    dailyData.summary = jsonObject.getString("summary");
    dailyData.icon = jsonObject.getString("icon");
    dailyData.sunriseTime = jsonObject.getLong("sunriseTime");
    dailyData.sunsetTime = jsonObject.getLong("sunsetTime");
    dailyData.moonPhase = jsonObject.getDouble("moonPhase");
    dailyData.precipIntensity = jsonObject.getDouble("precipIntensity");
    dailyData.precipIntensityMax = jsonObject.getDouble("precipIntensityMax");

    if (jsonObject.has("precipIntensityMaxTime")) {
        dailyData.precipIntensityMaxTime = jsonObject.getLong("precipIntensityMaxTime"); //Service is inconsistent
    }//from  www.  j  a  va 2  s  . c  om

    dailyData.precipProbability = jsonObject.getDouble("precipProbability");

    if (jsonObject.has("precipType")) {
        dailyData.precipType = jsonObject.getString("precipType"); //Service is inconsistent
    }

    dailyData.temperatureMin = jsonObject.getDouble("temperatureMin");
    dailyData.temperatureMinTime = jsonObject.getLong("temperatureMinTime");
    dailyData.temperatureMax = jsonObject.getDouble("temperatureMax");
    dailyData.temperatureMaxTime = jsonObject.getLong("temperatureMaxTime");
    dailyData.apparentTemperatureMin = jsonObject.getDouble("apparentTemperatureMin");
    dailyData.apparentTemperatureMinTime = jsonObject.getLong("apparentTemperatureMinTime");
    dailyData.apparentTemperatureMax = jsonObject.getDouble("apparentTemperatureMax");
    dailyData.apparentTemperatureMaxTime = jsonObject.getLong("apparentTemperatureMaxTime");
    dailyData.dewPoint = jsonObject.getDouble("dewPoint");
    dailyData.humidity = jsonObject.getDouble("humidity");
    dailyData.windSpeed = jsonObject.getDouble("windSpeed");
    dailyData.windBearing = jsonObject.getInt("windBearing");
    dailyData.cloudCover = jsonObject.getDouble("cloudCover");
    dailyData.pressure = jsonObject.getDouble("pressure");
    dailyData.ozone = jsonObject.getDouble("ozone");
    return dailyData;
}

From source file:br.unicamp.cst.learning.glas.LearnerCodelet.java

@Override
public void proc() {

    if (enabled) {

        if ((first_run || (SOLUTION_TREE_MO.getEvaluation() < this.getGoal_fitness()))
                && !((String) EVENTS_SEQUENCE_MO.getI()).isEmpty()) {

            //         System.out.println("Init proc ... ");

            try {
                JSONArray sequence_json = new JSONArray(EVENTS_SEQUENCE_MO.getI());

                System.out.print(".");
                int sequence_lenght = sequence_json.length();
                //If (maxEventsSequenceLenght==Integer.MAX_VALUE), it tries to learn a new tree as soon as possible (if it has new events and previous learning is over)
                //TODO Increment this condition for it to start learning only if it makes a mistake?
                //If maxEventsSequenceLenght is a finite integer (set by the user) it waits until maxEventsSequenceLenght new events are presented to the current solution. Only then does it start learning a new sequence.
                if (maxEventsSequenceLenght == Integer.MAX_VALUE
                        || (sequence_lenght - last_number_of_events) >= maxEventsSequenceLenght) {

                    while (sequence_json.length() > maxEventsSequenceLenght) { // learns only with the last MAX_EVENTS_SEQUENCE_LENGHT events
                        sequence_json.remove(0);
                    }//from   ww w .ja  va  2s.  c o  m
                    if (this.printSequenceUsedForLearning) {
                        System.out.println("");
                    }
                    GlasSequence mySequence = new GlasSequence();
                    if (this.printSequenceUsedForLearning) {
                        System.out.println("Sequence used for learning: ");
                    }
                    for (int e = 0; e < sequence_json.length(); e++) {
                        //TODO Should be inside GlasSequence?            
                        JSONObject event_json = sequence_json.getJSONObject(e);
                        int stim = event_json.getInt(GlasSequenceElements.SENSED_STIMULUS.toString());
                        int act = event_json.getInt(GlasSequenceElements.EXPECTED_ACTION.toString());
                        double rew = event_json.getDouble(GlasSequenceElements.REWARD_RECEIVED.toString());

                        //                     Sequence used for learning: 
                        //                        0,2,0,-1.0 //TODO

                        if (this.printSequenceUsedForLearning) {
                            System.out.println(e + "," + stim + "," + act + "," + rew);
                        }

                        mySequence.addEvent(new GlasEvent(stim, act, rew));
                    }

                    //TODO Store WHO acted on this sequence, and its results

                    JSONArray solution_tree_phenotype_jsonarray = new JSONArray(SOLUTION_TREE_MO.getI());
                    int[] solution_tree_phenotype_int = new int[solution_tree_phenotype_jsonarray.length()];
                    for (int i = 0; i < solution_tree_phenotype_jsonarray.length(); i++) {
                        solution_tree_phenotype_int[i] = solution_tree_phenotype_jsonarray.getInt(i);
                    }

                    int[] genotype_int = this.getGenotypeFromPhenotype(solution_tree_phenotype_int);

                    int nNodesIndi = (solution_tree_phenotype_int.length / 3);
                    Individual indi = new Individual(nNodesIndi, nStimuli, nActions);
                    indi.setChromossome(genotype_int);

                    double max_fit = this.getMaxFitnessForSequence(mySequence);
                    double fit = indi.getFitness(mySequence);
                    indi.setNormalizedFitness(fit / max_fit);

                    indi_list.add(indi);
                    if (this.printLearnedSolutionTree) {
                        //                     System.out.println("");
                        System.out.print(fit + ",");
                        System.out.print(fit / max_fit + ",");
                        System.out.print(nNodesIndi + ",");
                        for (int i = 0; i < genotype_int.length; i++) {
                            System.out.print(genotype_int[i] + ",");
                        }
                        System.out.print(indi_list.size());
                        System.out.println("");
                    }

                    //LEARNING PHASE
                    System.out.println("I just started learning from a new sequence...");
                    int[] temp_best_found_int = { 1, 1, 1 };
                    double temp_best_found_fit = Double.NEGATIVE_INFINITY;
                    double normalized_fitness = Double.NEGATIVE_INFINITY;

                    GlasLearner myLearner = new GlasLearner(nNodes, nStimuli, nActions);
                    for (int local_nNodes = minNumberOfNodes; local_nNodes <= maxNumberOfNodes; local_nNodes++) {

                        myLearner = new GlasLearner(local_nNodes, nStimuli, nActions);
                        boolean show_gui = false;
                        myLearner.setShow_gui(show_gui);
                        myLearner.setnReRuns(nReRuns);
                        //      int max_number_reRuns=500;  //int max_number_reRuns=500;
                        //      int nParticles = 1000;            //int nParticles = 1000;
                        //      myLearner.setMax_number_reRuns(max_number_reRuns);
                        //      myLearner.setnParticles(nParticles);

                        //                     
                        myLearner.learnSequence(mySequence);
                        //                     
                        if (myLearner.getBest_found_fit() > temp_best_found_fit) {
                            temp_best_found_int = myLearner.getBest_found_solution();
                            temp_best_found_fit = myLearner.getBest_found_fit();
                        }

                        if (this.printLearnedSolutionTree) {
                            double temp_max_fit = this.getMaxFitnessForSequence(mySequence);
                            //                        System.out.println("");
                            System.out.print(temp_best_found_fit + ",");
                            normalized_fitness = temp_best_found_fit / temp_max_fit;
                            System.out.print(normalized_fitness + ",");
                            System.out.print(local_nNodes + ",");
                            for (int i = 0; i < temp_best_found_int.length - 1; i++) {
                                System.out.print(temp_best_found_int[i] + ",");
                            }
                            System.out.println(temp_best_found_int[temp_best_found_int.length - 1]);

                        }

                    }
                    System.out.println("...finished learning.");
                    int[] best_found_int = temp_best_found_int; //TODO Unnecessary?

                    int[] new_solution_tree_int = this.getPhenotypeFromGenotype(best_found_int);

                    double best_found_fit = temp_best_found_fit; //TODO Unnecessary?

                    best_solution_tree = new JSONArray();
                    for (int i = 0; i < new_solution_tree_int.length; i++) {
                        best_solution_tree.put(new_solution_tree_int[i]);
                    }

                    SOLUTION_TREE_MO.updateI(best_solution_tree.toString());
                    //                  SOLUTION_TREE_MO.setEvaluation(best_found_fit);
                    SOLUTION_TREE_MO.setEvaluation(normalized_fitness);
                    first_run = false;

                    //                  }
                    if (SOLUTION_TREE_MO.getEvaluation() >= this.getGoal_fitness()) {
                        System.out.println("Found goal fitness = " + SOLUTION_TREE_MO.getEvaluation());
                    }

                    if (plot_solution) {

                        double[] best_found_double = new double[best_found_int.length];

                        for (int i = 0; i < best_found_double.length; i++) {
                            best_found_double[i] = ((double) best_found_int[i]);
                        }

                        double[] sol = new double[nNodes * 3];
                        int count = 0;
                        for (int i = 0; i < sol.length; i++) {
                            if ((i % nNodes) == 0) {
                                sol[i] = 0;

                            } else {
                                sol[i] = best_found_double[count];
                                count++;
                            }

                        }

                        //                     ploter = new GlasPlot(sol);

                        //                     ploter.plot();

                    }

                    sequence_json = new JSONArray(EVENTS_SEQUENCE_MO.getI());
                    last_number_of_events = sequence_json.length();

                    //                  System.out.println("##########################################");

                } //if(sequence_json.length()>=MAX_EVENTS_SEQUENCE_LENGHT)

            } catch (JSONException e) {
                System.out.println("This should not happen! (at LearnerCodelet)");
                e.printStackTrace();
            }

        }

        if (indi_list.size() >= this.maxNumberOfSolutions) {
            System.out.println("Stopped learning.");
            this.setEnabled(false);
        }
    } else {//if enabled
            //         System.out.println("Learning is halted."); //Do nothing
    }

}

From source file:ch.ethz.twimight.net.opportunistic.ScanningService.java

/**
 * Creates content values for a Tweet from a JSON object TODO: Move this to
 * where it belongs/*from w  ww.  jav a 2s  .  c  om*/
 * 
 * @param o
 * @return
 * @throws JSONException
 */
protected ContentValues getTweetCV(JSONObject o) throws JSONException {

    ContentValues cv = new ContentValues();

    if (o.has(Tweets.COL_CERTIFICATE))
        cv.put(Tweets.COL_CERTIFICATE, o.getString(Tweets.COL_CERTIFICATE));

    if (o.has(Tweets.COL_SIGNATURE))
        cv.put(Tweets.COL_SIGNATURE, o.getString(Tweets.COL_SIGNATURE));

    if (o.has(Tweets.COL_CREATED_AT))
        cv.put(Tweets.COL_CREATED_AT, o.getLong(Tweets.COL_CREATED_AT));

    if (o.has(Tweets.COL_TEXT)) {
        cv.put(Tweets.COL_TEXT, o.getString(Tweets.COL_TEXT));
        cv.put(Tweets.COL_TEXT_PLAIN, Html.fromHtml(o.getString(Tweets.COL_TEXT)).toString());
    }

    if (o.has(Tweets.COL_USER_TID)) {
        cv.put(Tweets.COL_USER_TID, o.getLong(Tweets.COL_USER_TID));
    }

    if (o.has(Tweets.COL_TID)) {
        cv.put(Tweets.COL_TID, o.getLong(Tweets.COL_TID));
    }

    if (o.has(Tweets.COL_REPLY_TO_TWEET_TID))
        cv.put(Tweets.COL_REPLY_TO_TWEET_TID, o.getLong(Tweets.COL_REPLY_TO_TWEET_TID));

    if (o.has(Tweets.COL_LAT))
        cv.put(Tweets.COL_LAT, o.getDouble(Tweets.COL_LAT));

    if (o.has(Tweets.COL_LNG))
        cv.put(Tweets.COL_LNG, o.getDouble(Tweets.COL_LNG));

    if (o.has(Tweets.COL_SOURCE))
        cv.put(Tweets.COL_SOURCE, o.getString(Tweets.COL_SOURCE));

    if (o.has(Tweets.COL_MEDIA_URIS)) {
        String userID = cv.getAsString(Tweets.COL_USER_TID);
        photoPath = PHOTO_PATH + "/" + userID;
        String photoFileName = o.getString(Tweets.COL_MEDIA_URIS);
        File targetFile = sdCardHelper.getFileFromSDCard(photoPath, photoFileName);

        cv.put(Tweets.COL_MEDIA_URIS, Uri.fromFile(targetFile).toString());

    }

    if (o.has(Tweets.COL_HTML_PAGES))
        cv.put(Tweets.COL_HTML_PAGES, o.getString(Tweets.COL_HTML_PAGES));

    if (o.has(TwitterUsers.COL_SCREEN_NAME)) {
        cv.put(Tweets.COL_SCREEN_NAME, o.getString(TwitterUsers.COL_SCREEN_NAME));
    }

    return cv;
}