Tag Archives: function

Change extension of a file using PHP

Following is not the most efficient solution out there. But if you are fan of regex, it is easy to read and maintain.

PHP
/**
* Change extension of a given filepath. If filename does not have extension,
* the new extension is simply appended.
*
* @param string $newExt May or may not start with .
*/
function changeExtension(string $filepath, string $newExt): string
{
$ext = str_starts_with($newExt, '.') ? $newExt : '.' . $newExt;
return preg_replace('/\.[^.]+$/', '', $filepath) . $ext;
}

vue: navigator.mediaDevices is undefined

If you are using internal IPs e.g. 192.168.0.300 etc for development, you are likely to encounter this error when dealing with media devices.

Assuming that you are not using localhost for development for a reason, you can do either of the following

  1. In Firefox you can enable the following two options described in https://stackoverflow.com/a/66605018/1805129. Go to about:config
    set to true media.devices.insecure.enabled and media.getusermedia.insecure.enabled

90c8821922ca484ba9ad755c39c9adbe -- <code>about:config</code> options in firefox” title=”” class=”aligncenter” /></a></p>
<ol>
<li>You can use service like <code>ngrok</code> or <a href=https://serveo.net/ to temporarily get https address. I learnt about these two services in the README file of https://www.npmjs.com/package/vue-qrcode-reader.

Flatten a HashMap> to Vec in Rust

I have somethat that may look like the output of tree like command. I want it a plain list wihtout nesting for further processing. I want to convert the following on the left to the one on the right.

{
    "/opt": [
        "a",
        "b",
        "c",
    ],
    "/root": [
        "a",
        "b",
        "c",
    ],
}
[
    "/opt/a",
    "/opt/b",
    "/opt/c",
    "/root/a",
    "/root/b",
    "/root/c",
]

The following gist shows how to do it. You can play with code on the playground here https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=dfdbc1036a4bc502488598a742552fba.

Line 12 converts HashMap to a vector of vector where inner most vector is join of key with individual values. flatten converts vector of vector to a vector (akin to concat).

Gist

https://gist.github.com/rust-play/3a11b9e4d16e992e995c8aa0d26c6141

Prepending/Appending to PATH using Rust

/// Add to to PATH environment variable. If `append` is false, add to the 
/// front of list.
pub fn add_to_path(path: &str, append: bool) -> anyhow::Result<()> {
    use anyhow::Context;
    use std::env;
    use std::path::PathBuf;

    let paths = env::var_os("PATH").context("empty PATH")?;
    let mut paths = env::split_paths(&paths).collect::<Vec<_>>();
    if append {
        paths.push(PathBuf::from(path));
    } else {
        paths.insert(0, PathBuf::from(path));
    }

    let new_path = env::join_paths(paths)?;
    env::set_var("PATH", new_path);

    Ok(())
}