Skip to content
The Chat Archive
gpt-4o-mini-2024-07-18· OpenAI WildChat-4.8M (AI2)

#!/usr/bin/python3.1 import os import sys import http.client version = “1.22.0” def…

  1. User

    #!/usr/bin/python3.1

    import os import sys import http.client

    version = “1.22.0”

    def main(argv): c_begin = [158200, 81900] c_end = [158801, 82501]

    total = (c_end[0]-c_begin[0])*(c_end[1]-c_begin[1]) print (total) c = 0 for x in range(c_begin[0], c_end[0]): for y in range(c_begin[1], c_end[1]): c += 1 result = GetTile(x, y) flag = " " if result == 1 else “+” if flag == “+”: print(“GET {: >10} {: >10} | {:.2f}% {: ^1}”.format(x, y, round((c/total)*100,2), flag)) return 0

    def GetTile(x, y):

    filename = “./map/{x}_{y}_18.jpg”.format(x = x, y = y) if os.path.isfile(filename): return 1 url = “/tiles?l=sat&v={ver}&x={x}&y={y}&z=18&g=Gagarin”.format(x = x, y = y, ver = version) conn = http.client.HTTPConnection(“sat02.maps.yandex.ru”) conn.request(“GET”, url) response = conn.getresponse() if response.status == 200: data = response.read() f = open(filename, “wb”) f.write(data) f.close()

    return 0

    if name == “main”: sys.exit(main(sys.argv))

    Перепеши этот код для rust

  2. Assistant

    Here's a Rust version of your Python script, which fetches tiles from a specific server, checking if they exist locally and downloading them if not. Keep in mind that there are some differences in error handling and syntax between Python and Rust.

    This Rust program uses the reqwest crate for HTTP requests and the std::fs module for file operations. Make sure to add reqwest in your Cargo.toml file:

    [dependencies]
    reqwest = { version = "0.11", features = ["blocking", "json"] }
    

    Now, here's how you can rewrite your Python code into Rust:

    use reqwest::blocking::Client;
    use std::fs;
    use std::io::Write;
    
    const VERSION: &str = "1.22.0";
    
    fn main() {
        let c_begin = [158200, 81900];
        let c_end = [158801, 82501];
    
        let total = (c_end[0] - c_begin[0]) * (c_end[1] - c_begin[1]);
        println!("{}", total);
    
        let mut c = 0;
    
        let client = Client::new();
    
        for x in c_begin[0]..c_end[0] {
            for y in c_begin[1]..c_end[1] {
                c += 1;
                let result = get_tile(&client, x, y);
                let flag = if result == 1 { " " } else { "+" };
                if flag == "+" {
                    println!(
                        "GET {:>10} {:>10} | {:.2}% {:^1}",
                        x,
                        y,
                        (c as f64 / total as f64) * 100.0,
                        flag
                    );
                }
            }
        }
    }
    
    fn get_tile(client: &Client, x: i32, y: i32) -> i32 {
        let filename = format!("./map/{}_{}_18.jpg", x, y);
        
        if fs::metadata(&filename).is_ok() {
            return 1;
        }
        
        let url = format!(
            "/tiles?l=sat&v={}&x={}&y={}&z=18&g=Gagarin",
            VERSION, x, y
        );
    
        let response = client.get(&format!("http://sat02.maps.yandex.ru{}", url))
            .send();
    
        match response {
            Ok(res) if res.status().is_success() => {
                if let Ok(data) = res.bytes() {
                    let mut file = fs::File::create(&filename).expect("Unable to create file");
                    file.write_all(&data).expect("Unable to write data to file");
                    return 0;
                }
            }
            Err(e) => {
                eprintln!("Error fetching tile: {}", e);
            }
            _ => {
                eprintln!("Failed to retrieve tile for coordinates ({}, {})", x, y);
            }
        }
    
        return -1; // Indicate that the tile was not successfully retrieved.
    }
    

    Key Changes and Considerations:

    1. Library for HTTP Requests: Rust does not have built-in libraries for HTTP requests like Python; hence, we use the reqwest crate.
    2. Error Handling: Rust emphasizes safety, and thus, error handling is more explicit. Instead of just returning an error code, we check for Ok and Err variants.
    3. Variable Naming: By convention, Rust uses snake_case for variable names.
    4. Formatting Strings: Rust uses the format! macro similarly to Python's str.format.
    5. File Handling: Rust requires explicit closure of file handles or using the write_all method.

    Before running this code, ensure you have a proper Rust environment set up and the necessary dependencies installed.