dontblink

joined 1 year ago
 

Let's say I have a struct Event which implements the method permalink:

struct Event {
    base_url: String,
    rel_permalink: String,
    permalink: String,
    title: String,
}

impl Event {
    fn permalink(&self) -> String {
        let permalink = format!("{}{}", self.base_url, self.rel_permalink);
        permalink
    }
}

The method takes 2 fields of the struct and the target would be to return the definition of another field.

Later I instantiate an event1: Event:

let event1 = Event {
                base_url: base_url,
                rel_permalink: rel_permalink.to_string(),
                title: node.value().name().to_string(),
                permalink = permalink(),
            };

Essentially I would like the field permalink to be the value returned by the method permalink, is something like this possible, is this correct? I couldn't find something similar in the docs..

Pheraps using an associated function as constructor would be a better way to handle a similar situation?

Thank you so much!

16
submitted 4 days ago* (last edited 4 days ago) by [email protected] to c/[email protected]
 

Hi!

First of all sorry if this is the wrong place to ask, if it is, please point me to a better suited channel!

Anyway I've got this old 2TB HDD attached to a rpi 4b, it worked flawlessly until now, the last few days it started disconnecting randomly..

If i reboot it mounts back again.

This is the df output:

/dev/sdb1       1.8T  535G  1.2T  31% /mnt/2tb

And this is sudo dmesg | grep sdb (the device is sdb ofc).

[   14.970908] sd 1:0:0:0: [sdb] 3907029168 512-byte logical blocks: (2.00 TB/1.82 TiB)
[   14.978857] sd 1:0:0:0: [sdb] 4096-byte physical blocks
[   14.984484] sd 1:0:0:0: [sdb] Write Protect is off
[   14.989382] sd 1:0:0:0: [sdb] Mode Sense: 43 00 00 00
[   14.989684] sd 1:0:0:0: [sdb] Write cache: enabled, read cache: enabled, doesn't support DPO or FUA
[   15.044802] sd 1:0:0:0: [sdb] Preferred minimum I/O size 4096 bytes
[   15.051196] sd 1:0:0:0: [sdb] Optimal transfer size 33553920 bytes not a multiple of preferred minimum block size (4096 bytes)
[   15.065585]  sdb: sdb1
[   15.068403] sd 1:0:0:0: [sdb] Attached SCSI disk
[   22.631983] EXT4-fs (sdb1): recovery complete
[   22.660922] EXT4-fs (sdb1): mounted filesystem with ordered data mode. Quota mode: none.

The device has an external power supply of its own, so it's not a power issue.. This setup worked for a couple of years.

I cannot see anything wrong here, pheraps is the HDD which is going bad?

[–] [email protected] 1 points 5 days ago

Thank you so much, You are taking a lot of effort to answer my doubts and I really appreciate!

So essentially match can return different types, but of course I have to specify it in the function signature, wheter using an enum or other ways, this makes sense! This was a missing piece in my puzzle, I didn't consider the fact that the match return here was the function return type as well, and i had encoded -> String as return type.

[–] [email protected] 1 points 1 week ago (10 children)

Hi! First of all thank you so much for the detailed explanation!

What I'm trying to do is scraping some content.

Yes I'm trying to return all links (maybe in a vector), I have a list of elements (Select, which actually is scraper::html::Select<'_, '_>) which contain essentially html nodes selections, and I would like to grab each of them, extract the actual link value (&str), convert it into an actual String and push it firstly into a vector containing all the links and then in an istance of a struct which will contain several datas about the scraped page later.

I was trying to use a for loop because that was the first structure that came to my mind, I'm finding it hard to wrap my head around ownership and error handling with rust, using the if let construct can be a good idea, and I didn't consider the use of break!

I also managed to build the "match version" of what I was trying to achieve:

fn get_links(link_nodes: scraper::html::Select<'_, '_>) -> Vec<String> {
        let mut links = vec![];

        for node in link_nodes {
            match node.value().attr("href") {
                Some(link) => {
                    links.push(link.to_string());
                }
                None => (),
            }
        }

        dbg!(&links);
        links
    }

I didn't understand that I had to return the same type for each of the Option match arms, I thought enum variants could have different types, so if the Some match arm returns (), also None has to do the same..

If I try with a simpler example I still cannot understand why I cannot do something like:

enum OperativeSystem {
            Linux,
            Windows,
            Mac,
            Unrecognised,
        }

        let absent_os = OperativeSystem::Unrecognised;
        find_os(absent_os);

        fn find_os(os: OperativeSystem) -> String {
            match os {
                debian => {
                    let answer = "This pc uses Linux";
                    answer.to_string()
                }
                windows10home => {
                    let answer = "This pc uses Windows, unlucky you!";
                    answer.to_string()
                }
                ios15 => {
                    let answer = "This pc uses Mac, I'm really sorry!";
                    answer.to_string()
                }
                _ => {
                    let is_unrecognised = true;
                    is_unrecognised
                }
            }
        }

match is much more intuitive for a beginner, there's a lot of stuff which go under the hood with ?

 
fn get_links(link_nodes: Select) -> Option<String> {

        let mut rel_permalink: Option<String> = for node in link_nodes {
            link = String::from(node.value().attr("href")?);

            return Some(link);
        };

        Some(rel_permalink)
    }

This is what I'm trying to do, and I've been stuck with this code for an hour, I simply don't know how to put this function togheter.. Essentially I would like to take some link_nodes and just return the link String, but I'm stuck in the use of Option with the ? operator.. Pheraps trying to write it with match would clear things out(?)

Also I come from JavaScript in which expressions do not have their own scope, meaning I'm having troubles to understand how to get out a variable from a for loop, should I initialize the rel_permalink variable as the for loop result?

This are the errors i get:

error[E0308]: mismatched types
  --> src/main.rs:55:49
   |
55 |           let mut rel_permalink: Option<String> = for node in link_nodes {
   |  _________________________________________________^
56 | |             link = String::from(node.value().attr("href")?);
57 | |
58 | |             return Some(link);
59 | |         };
   | |_________^ expected `Option<String>`, found `()`
   |
   = note:   expected enum `Option<String>`
           found unit type `()`
note: the function expects a value to always be returned, but loops might run zero times
  --> src/main.rs:55:49
   |
55 |         let mut rel_permalink: Option<String> = for node in link_nodes {
   |                                                 ^^^^^^^^^^^^^^^^^^^^^^ this might have zero elements to iterate on
56 |             link = String::from(node.value().attr("href")?);
   |                                                          - if the loop doesn't execute, this value would never get returned
57 |
58 |             return Some(link);
   |             ----------------- if the loop doesn't execute, this value would never get returned
   = help: return a value for the case when the loop has zero elements to iterate on, or consider changing the return type to account for that possibility
 

Programs with custom services, virtual environments, config files in different locations, programs creating datas in different location...

I know today a lot of stuff runs in docker, but how does a sysadmin remember what has done on its system? Is it all about documenting and keeping your docs updated? Is there any other way?

(Eg. For installing calibre-web I had to create a python venv, the venv is owned by root in /opt, but the service starting calibre web in /etc/systemd/system needs to be executed with the User=<user> specifier because calibre web wants to write in a user home directory, at the same time the database folder needs to be owned by www-data because I want to r/w it from nextcloud... So calibreweb is installed as a custom root(?) program, running in a virtual env, can access a folder owned by someone else, but still needs to be executed by another user to store its data there... )

Despite my current confusion in understanding if all of this is right in terms of security, syntax and ownership, No fucking way I will remember all this stuff in a week from now.. So... What do you use to do, if you do something? Do you use flowcharts? Simple text documents? Both?

Essentially, how do you keep track?

 

Hi! I'm trying to learn Rust, as a little project, I'm trying to build a web scraper that will scrape some content and rebuild it with a static site generator, or using it for making POST requests.

I'm still at a very early stage and I still don't know much, the simplest error handling strategy I know is using match with Result.

To my eyes, this syntax looks correct, but also looks kind of a lot of lines for a simple http request.

I know the reqwest docs suggest to handle errors with the ? operator, which I don't know yet, therefore I'm just using what I know now.

fn get_document(permalink: String) -> Html {
        let html_content_result = reqwest::blocking::get(&permalink);
        let html_content = match html_content_result {
            Ok(response) => response,
            Err(error) => panic!("There was an error making the request: {:?}", error),
        };

        let html_content_text_result = html_content.text();
        let html_content_text = match html_content_text_result {
            Ok(text) => text,
            Err(error) =>
                panic!(
                    "There was an error getting the html text from the content of response: :{:?}",
                    error
                ),
        };

        let document = Html::parse_document(&html_content_text);

        document
    }

As for my understanding, this is what I'm doing here: I'm making an http request, if i get a Response, I try to get the text out of the response body, otherwise I handle the error by panicking with a custom message. Getting the text out of the request body is another passage that requires error handling, therefore I use the match expression again to get the text out and handle the possible error (In what circumstances can extracting the text of a response body fail?).

Then I can finally parse the document and return it!

I wonder if it is a correct and understandable way of doing what I've in mind.

Do you think this would be a suitable project for someone who is at chapter 7 of the Rust book? I feel like i actually need to build somethiong before keep going with the theory!

[–] [email protected] 26 points 10 months ago

It's the path of many of us here, now you will hate linux if you come from windows, give it a couple of months and you'll ask yourself how the fuck you could be on windows till now.

[–] [email protected] 1 points 10 months ago (2 children)

I wonder why we don't have AI browser extensions that can recognise and obscure possible ads / unwanted content yet

[–] [email protected] 1 points 10 months ago

I will add another amazing alternative i've found, currently working great: https://www.distractionfreeapps.com/ This was exactly what i was looking for.

[–] [email protected] 5 points 10 months ago (2 children)

Hisense A9 with full root + microG

A minimalist eink anti addictive machine that brings smartphones back to an actually useful tool removing literally all the bullshits.

[–] [email protected] 28 points 10 months ago (3 children)

What about sexual and emotional education in schools?

[–] [email protected] 1 points 11 months ago

Yeah sure, you have to trust your users

[–] [email protected] 6 points 11 months ago

I like Debian with GNOME

[–] [email protected] 12 points 11 months ago (1 children)

Badum tssss

[–] [email protected] 4 points 11 months ago (1 children)

Video editing softwares definetely, kdenlive is nothing compared to stuff like sony vegas.

[–] [email protected] 1 points 11 months ago (2 children)

I guess probably, because Matrix is thought for private chatting, i guess someone else might have had this same idea, i think matrix is opensource so there must be some client that does this.

 

I can't find it in the settings but is there any way to sort comments by popularity instead of time? Just like it is in normal reddit?

 

Honestly all this world looks really overwhelming, there's too much stuff going on: each program uses its own languages, its own compilers, uses different tools, libraries, dependencies, package managers and frameworks. You need specific instructions and documentation to learn new stuff at every single thing you deal with.

Whenever i open a project on Github i just feel overwhelmed because there will always be something new and i'm afraid i won't ever get out of that way of operate that "somehow makes things work" and really understand my code and program interactions..

Honestly it's really complicated because you use a program you need and you just see it from the surface, you don't have the time to learn how things work in a slightly more linear way, it would take ages considering the fact you probably need other 10 programs like that. To me it looks just like modern programming is about grabbing different pieces of fragmented knowledge all around web forums, wikis (or chatbots, which for me are just the next way of giving up our ability to learn) and somehow making things work.

I just get overwhelmed even when i take a look to a github page sometimes, even the frontpage has so much stuff you won't ever learn.

Another thing is the online community is the most sparse thing, far from actual real communities there is, you can work with people who won't ever even talk to, and their contribute can be as sterile as just creating a pull request and then leaving forever. You are mostly on your own striclty speaking of human connections and ability to share ideas and feelings.

I'm very fought because i somehow feel like i really love how certain ideals and creativity can be expressed with programming: i love that you can use something practical to solve idealistic, creative and technical problems. I love stuff such as digital etic, cypherpunk movemenet and all the work that opensource devs do to make the industry just a bit better, sometimes even receiving donations for their work, which for me is the highest form of payment, i've never seen someone more happy to pay for something as in the opensource community. But at the same time i'm starting to loathe technology and the internet because, adding on top of everything i said above about the sterility of the community, the difficulty to concentrate on a single thing and the dispersion there can be, i'm also dealing with a 10 years porn addiction since 5 years ago, progresses happens but are really slow and using my computer or phone is a huge trigger even if i'm trying my best to make them as minimal and not addictive as possible. Trust me, in a world designed to get you addicted to your hardware and software, being grown up used to doom scroll every day, it takes a huge amount of time and effort to have your things all sorted up to guarantee yourself a bit more privacy and software that is actually useful and doesn't want to keep you hooked, and at the same time don't be too much of a social outcast. You actually have to re-learn computer, or better saying, to actually learn computer for the first time, because you realize you can't just rely on having everything ready, set up, and just working from scratch without paying in some way, and the price that most big techs set is even higher, and far more subtle than just paying with money.

The software industry right now is shit outside of the few developers that are actually building products FOR users, and not for money, and of course that does mean that if i follow my ideals, i won't nearly have these much economical opportunities as every "usual" developer gets. It's a huge headache having to deal with programs even when i do it for myself, i can't even think of doing that for someone else right now (with all the work and continuity that this requires) and i'm thinking if i should really put my efforts somewhere else.

 

Bibliogram is being discontinued, and Barinsta doesn't work anymore too..

Is there some good soul providing an instagram frontend or app? I really need it to see events, but i don't want to get caught in those useless post suggestions and ads, i just wanna see the content i chose to see.

 

These are the things i care the most: I want a smartphone i can repair on my own (battery and screen are the essential parts), with a bootloader easily unlockable, even better with verified boot / supporting a custom OS with re-lockable bootloader.

I don't care if it's supported by an official foundation or by custom ROMs foundations, i want something that will most likely get the longest term updates and security patches.

Does a device like this even exists?

I know that probably one of the few alternatives here is the fairphone, however it's really expensive and i've read many negative reviews of it (pieces staying out of stock for months or stuff like that), and i can't see the meaning of having a repairable smartphone if i have to spend the same money that i would spend buying 3 smartphones with the same specs that would last me the same time. That said, i know the market isn't favouring these kind of businesses and these devices NEED to be expensive in order to keep existing, but i would like to know some other possible alternatives that satisfy these requirements, if they even exist.

Honestly i've come to a point i would probably prefer spend my money on a guitar instead that on a smartphone and just give up, the industry is terrible 😅

 

I regurlary took nandroid backups on my pc with TWRP (adb backup --twrp) of my phone, one day i needed to restore one and i found out i wasn't able to, the restore would stop midway and i needed to completely reset my phone..

Probably the corruption could have happened because i originally took the backups on a PC with a Ryzen processor, that's what i managed to figure out.

Anyway now i wanna make sure to have safe and healthy nandroid backup, is there a way to check this without having to try to restore on an emulator every time?

 

From a first perspective it actually looks good! I think these kind of regulation were really needed. But i would like to hear your opinions!

 

The new fairphone 5 came out, it looks cool but the price is really, really high..

If it's a phone that can really last 10 years it could be good, but is that true? Is it worth it? I could get the one with /e/os from Murena because i want a degoogled phone with a bootloader locked, but is it usable on a daily basis?

view more: next ›