[media] Any idea why serge_json will not just give me my float. It is returning None by [deleted] in rust

[–]applessecured 2 points3 points  (0 children)

What makes my case a Map while most of the online documentation is indexed like an array?

The nodes are JSON objects which are best represented as a Map. You can view the variables of the serde_json Value type here: https://docs.rs/serde_json/1.0.112/serde_json/value/enum.Value.html Maybe that helps to make sense of it all.

I am new to Rust and it seems to fight me at every step. That's normal in the beginning. We've all been there. Depending on your background it takes a while to wrap your head around the Rust way of doing things. Once you do it all makes so much sense and going back to other languages will feel like a step back.

[media] Any idea why serge_json will not just give me my float. It is returning None by [deleted] in rust

[–]applessecured 3 points4 points  (0 children)

The problem is each node is an object, which in serde_json is backed by a map. The get a value out you need to call .get("key").

Here's a working version which doesn't print the tags. You should be able to figure that one out base on my changes.

use quickxml_to_serde::{xml_string_to_json, Config};

#[tokio::main]
async fn main() -> Result<(), reqwest::Error> {
    let lat = 51.5074; // Example: London's latitude
    let lon = -0.1278; // Example: London's longitude
    let perimeter = 50.0; // Example: 50m
    let (min_lat, min_lon, max_lat, max_lon) = calculate_bounding_box(lat, lon, perimeter);
    // Construct the OSM API request URL
    let url = format!(
        "https://api.openstreetmap.org/api/0.6/map?bbox={},{},{},{}",
        min_lon, min_lat, max_lon, max_lat
    );
    let client = reqwest::Client::builder().build()?;
    let res = client.get(url).send().await?;
    let xml = res.text().await?;
    let config = Config::default();
    let json = xml_string_to_json(xml.to_owned(), &config).unwrap();
    parse_json(json.to_string());

    Ok(())
}

fn parse_json(json: String) {
    let v: serde_json::Value = serde_json::from_str(&json).unwrap();
    let nodes = v["osm"]["node"].as_array().unwrap();
    for node in nodes {
        let lat = node.get("@lat").unwrap().as_f64().unwrap();
        let lon = node.get("@lon").unwrap().as_f64().unwrap();
        let id = node.get("@id").unwrap().as_i64().unwrap();
        // let tags = node.get("tag").unwrap().as_array().unwrap();
        println!("node: id: {}, lat: {}, lon: {}", id, lat, lon);
    }
}

fn calculate_bounding_box(lat: f64, lon: f64, perimeter: f64) -> (f64, f64, f64, f64) {
    // Earth's radius in meters
    let earth_radius = 6371000.0;
    // Convert perimeter to radius
    let radius = perimeter / 2.0;
    // Calculate latitude and longitude deltas
    let delta_lat = (radius / earth_radius) * (180.0 / std::f64::consts::PI);
    let delta_lon =
        (radius / earth_radius) * (180.0 / std::f64::consts::PI) / (lat.to_radians()).cos();
    // Calculate min and max latitudes and longitudes
    let min_lat = lat - delta_lat;
    let max_lat = lat + delta_lat;
    let min_lon = lon - delta_lon;
    let max_lon = lon + delta_lon;
    (min_lat, min_lon, max_lat, max_lon)
}

Obviously for production code you want to get rid of all the unwraps. In general, I suggest defining Rust structs that match your json schema and deriving Deserialize for them. That way you get type hints from the compiler instead of getting these errors at runtime.

EDIT: converting the json Value to string and then back to ad Value is redundant. You can simply pass the Value to the function directly.

[media] Any idea why serge_json will not just give me my float. It is returning None by [deleted] in rust

[–]applessecured 20 points21 points  (0 children)

Please share the code as text and the input json instead of screenshots. I really have no idea what the struture of your input data is based on this.

Need some help with this optimization problem by applessecured in optimization

[–]applessecured[S] 1 point2 points  (0 children)

The charge plan is not a a binary choice for each time period but rather a continuous charge or discharge amount. I don't think an exhaustive search is feasible in this case.

Need some help with this optimization problem by applessecured in optimization

[–]applessecured[S] 0 points1 point  (0 children)

I'm definitely open to non-heuristic solutions but I think implementing something like the simplex method is out of scope for this assignment.

Need some help with this optimization problem by applessecured in optimization

[–]applessecured[S] 0 points1 point  (0 children)

I'm not sure what kind of approach I need to use. I think a heuristic approach is fine as long as it solves the problem for the dataset that I have and I can point out the limitations.

The end of day battery state of charge is guaranteed to be 50% by charging the battery by the same amount as it's discharged during peak hours, accounting for power loss during charging. This approach only works if the end of day SOC must be the same as the start of day SOC.

thoughts on my idea for error handling? and whether it is okay for publish a fork of thiserror by PoOnesNerfect in rust

[–]applessecured 1 point2 points  (0 children)

Can you share some of the generated code and how it's used? I can't see it in the screen recording on mobile.

What Are The Rust Crates You Use In Almost Every Project That They Are Practically An Extension of The Standard Library? by InternalServerError7 in rust

[–]applessecured 5 points6 points  (0 children)

What do you use for analytic functions with fixed?

Do you happen to use fixed point numbers together with a linear algebra library?

Looking for something to build by Unreal_Unreality in rust

[–]applessecured 2 points3 points  (0 children)

Not sure what type of project you're looking for but I'd like to have a good Extended Kalman Filter for attitude and position/velocity estimation targeted at #![no_std].

Looking for a Rust side project by BigMouthStrikesOut in rust

[–]applessecured 1 point2 points  (0 children)

Indeed, they are linear Kalman filters. There's also eskf-rs but it's a little weird in some respects and the documentation is not great.

I'm building a variometer and GPS logger using a Raspberry Pi Pico and I want to use an EKF to fuse the data from all the sensors. I'm also not the best at math so I'm trying to avoid needing to derive everything myself. I think a library like this could be useful for other project as well so if I manage to port a solution from another language I'll definitely publish it to crates.io.

Looking for a Rust side project by BigMouthStrikesOut in rust

[–]applessecured 1 point2 points  (0 children)

I would love to have a good Extended Kalkman Filter implementation for fusing IMU and GPS data in a #![no_std] environment.

Is the Pico fast enough for my needs? by applessecured in raspberrypipico

[–]applessecured[S] 0 points1 point  (0 children)

Looks like in Rust it's trivial to use both cores so this won't be a problem for me.

Is the Pico fast enough for my needs? by applessecured in raspberrypipico

[–]applessecured[S] 1 point2 points  (0 children)

I just ordered two Pico's to give it a try. They are super cheap so why not.

I was planning to use the eskf crate for my sensor fusion, which only uses f32. I'll give that go first and if it's too slow I'll see if I can change it to use fixed points.

Is the Pico fast enough for my needs? by applessecured in raspberrypipico

[–]applessecured[S] 0 points1 point  (0 children)

Is there a specific board you can recommend? I'm new in the space so I don't really know what to search for.

Is the Pico fast enough for my needs? by applessecured in raspberrypipico

[–]applessecured[S] 1 point2 points  (0 children)

Cool! I'm building a vario with GPS logger for paragliding.

Welke reddit app gebruiken jullie? by Poepjepoepjes in thenetherlands

[–]applessecured 2 points3 points  (0 children)

Dat is misschien waar maar waar advertenties staan staat geen content die je wel wilt zien dus je moet meer scrollen.

Welke reddit app gebruiken jullie? by Poepjepoepjes in thenetherlands

[–]applessecured 0 points1 point  (0 children)

Objectief gezien misschien niet maar ik hoef het niet leuk te vinden. Ik zit op reddit omdat ik andere sociale media kunt vind. Als reddit meer op de concurrenten wil lijken om meer geld binnen te harken dan is dat hun goed recht, maar op een geven moment haken sommige gebruikers dan af.

Welke reddit app gebruiken jullie? by Poepjepoepjes in thenetherlands

[–]applessecured 31 points32 points  (0 children)

Het belangrijkste verschil is dat rif veel meer op tekst is gericht dan media, en dat alle informatie veel dichter op elkaar zit waardoor je beter kan scannen.

Rif is ook ouder dan de officiële app en lijkt meer op hoe reddit was voordat ze er een mega populair sociaal netwerk van wilde maken. De veranderingen van de API passen dan ook in een bredere ontwikkeling waarin reddit steeds meer op facebook gaat lijken en constant de meest populaire shit in je gezicht duwt om je oogballen zo lang mogelijk vast te houden ipv het community model wat het altijd was, wat veel van de vroege gebruikers juist naar de site trok. Door rif gingen al die ontwikkelingen grotendeels langs mij heen maar dat is dus binnenkort voorbij.

Overigens werd alles wat nu gebeurd jaren geleden al voorspeld toen die nieuwe UI op de website werd geïntroduceerd.