teleren/devto huggingface dataset:
Bookmarklets, and why you should use them
Tags: browser
Published: 2024-01-02 17:48:51

---
title: Bookmarklets, and why you should use them
published: true
description: Unlock your browser's full potential with this hidden technique
tags: browser
# cover_image: https://direct_url_to_image.jpg
# Use a ratio of 100:42 for best results.
# published_at: 2024-01-02 16:31 +0000
---
MOST of us have been using web browsers for a long time, yet relatively few of us know this somewhat obscure feature: browsers understand URLs that begin with `javascript:` instead of `http:` or `https:` protocols, and can actually execute the JavaScript code in the URL when you request it. Sounds like a security nightmare? Potentially, yes. You should be careful about what URLs you click on.

However! Harnessed in the right way, these `javascript:` URLs can be incredibly useful–enter bookmarklets.

## What are they

Bookmarklets are just regular browser bookmarks _except_ that they have a `javascript:` URL:

Name: (whatever name you want)

URL: `javascript:/* code */`

For example, `javascript:alert('hi!')`.

OK, so an alert pop-up is not that useful. But bookmarklets can do anything that JavaScript running on the page can. Even better, they allow you to replace some browser extensions that have similar functionality. For power users, instead of the memory overhead of a loaded browser extension, you replace it with a zero-cost bookmarklet.

Let me show you two very simple and useful bookmarklets and explain how they work.

## Allow paste

URL: `javascript:document.addEventListener('paste', e => e.stopImmediatePropagation(), true)`

When you click on this, it will 'trap' all paste events from further handling by JavaScript code, _but_ allow the actual paste to go ahead. Why would you need this? Well, some annoying websites like to disable paste functionality by setting their own `paste` event handlers on certain text inputs. They think that eg if you can't paste a password, you will be forced to type it in, which for some reason will make it more secure.

Of course, that's nonsense. But that's the kind of reasoning these sites have (I guess). So we circumvent these geniuses by taking control of our own paste events.

This allows you to get rid of: [Don't F*** With Paste](https://chromewebstore.google.com/detail/dont-f-with-paste/nkgllhigpcljnhoakjkgaieabnkmgdkb)

## Scroll top/bottom

URL: `javascript:window.scrollTo(0, window.scrollY == 0 ? document.body.scrollHeight : 0)`

When clicked, this will:

- If at the top of the page, scroll to the bottom
- Else, scroll to the top

Simple, yet effective.

This allows you to get rid of: [Scroll To Top](https://chromewebstore.google.com/detail/scroll-to-top/hegiignepmecppikdlbohnnbfjdoaghj)

## And more

These are just two simple use cases. As you can imagine, anything you can do with JavaScript on a web page, you can do with bookmarklets. Even making HTTP requests with the Fetch API! You're limited only by your imagination.

I have a [collection of bookmarklets](https://yawaramin.github.io/bookmarklets/) if you are interested in more. Have fun 🙂
Token dev tools inspector 🔑👀
Tags: webdev, javascript, extensions, jwt
Published: 2024-01-02 17:13:02

🙋🏻‍♂️ Alguna vez te has encontrado copiando el JWT de una petición en Chrome? Ya sea para usarlo en Postman, inspeccionarlo en JWT, o cualquier otra tarea, y... es algo que haces con frecuencia? 🤔

Yo sí, y la verdad, el proceso puede volverse un molesto después de tantas veces:

1. Abre las DevTools de Chrome 🛠️
2. Accede al panel de Network 🔍
3. Busca la petición que te interesa 🕵️
4. Abre la sección de Headers 📜
5. Selecciona todo el JWT (y cruza los dedos para no copiarlo mal) 🤞
6. Finalmente, cópialo 📋

Ahora, imagina tener que hacer esto varias veces al día, todos los días! 💀

Por suerte, he creado una extensión para Chrome que hace esto mucho más fácil: 🌟 **Token Dev Tools Inspector** 🌟

Con solo unos clics, agiliza la extracción de tokens en Chrome DevTools:

1. Abre Chrome DevTools 🛠️
2. Localiza el panel Token Inspector (similar a los paneles Consola, Red o Aplicación) 🔍
3. ¡Encuentra tus tokens sin esfuerzo! 🚀


![Preview of Token dev tools inspector](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/y4ztfc37abluym68bgpe.png)

Cómo ves, va directo al grano, UI simple pero funcional, además con acceso directo a jwt.io si quieres inspeccionar el contenido del token.

Te preocupa la privacidad de que un tercero esté leyendo tus tokens? Lo entiendo, por ello el proyecto es Open Source para que verifiques que los datos no salen al exterior!
[https://github.com/Guuri11/token-inspector](https://github.com/Guuri11/token-inspector)

Si quieres darle un intento, aquí tienes el enlace para instalar la extensión con toda su información:
[https://chrome.google.com/webstore/detail/token-devtools-inspector](https://chrome.google.com/webstore/detail/token-devtools-inspector/enlnbonndfjonmelmplbmgnobjffbhoj)

Espero que os guste, y como ya dije, el proyecto es Open Source, así que no dudéis en dar vuestro feedback si queréis!

Feliz año! 🎊
First Entry
Tags: dev, blog
Published: 2024-01-02 17:26:18

I've been meaning to start a dev blog for ages - something to document what I'm learning, how I'm finding it, what my thoughts are... you know the drill. I've been applying for jobs for around 2 months now, and a lot of the roles I'm finding myself drawn to are front-end, webby/UI/UX type positions. I guess that makes sense, I love working with Javascript and the post-codeclan deeper dives into these kind of technologies have been thrilling. But there's a couple of words (well, one word and one weird recursive acronym) that keep coming up that I remain almost entirely unexperienced in: PHP and Wordpress. Asking around showed me that these have both been around for quite a while, and PHP at least seems to be pretty hated. But hey, it's about time I started plugging some of those holes on my CV.

I've flirted a little with Wordpress on an old film review blog I started an University that went nowhere, and it remains, from what I remember, a pretty easy to use and flexible web CMS. I didn't dive too deep into it the mechanics of it's customisation back then, and I'm enjoying seeing just how flexible you can be with it. 

PHP however, seems far more interesting. I don't quite see why it's quite so hated yet, but I'm sure that will come. I'm enjoying how little setup it takes, and how it feels as though your typing DIRECTLY in your browser, completely server-side.  It definitely feels the most unique of all the languages I've been exposed to, and I can see how it could perhaps be lacking versatility compared to other languages. But it's quick and simple, which I'm digging so far. Certainly having PHP in HTML and vice-versa beats using Jinja to inject Python into HTML in my opinion.
MoviePy: Basic Usage
Published: 2024-01-02 17:24:42

{% embed https://www.youtube.com/watch?v=zoIq99_HJg0&t=124s&ab_channel=POLOXUE %}
In an era dominated by short-form videos, numerous user-friendly editing software options exist. 

However, for specialized video formats like eBook presentations or comic readings, streamlining the video creation process through automation stands as a crucial enhancement for efficiency.

In this tutorial, we'll delve into MoviePy, a Python library designed to automate video production processes. We'll explore its capabilities and demonstrate how it simplifies video editing tasks through simple Python code.

## Installation
To utilize MoviePy, the initial requirement is installation. Python's package manager - pip, can install it.

```bash
pip install moviepy
```

This automatically installs essential dependencies like ffmpeg. For text clips, imagemagick is necessary, which can be installed via HomeBrew:

```bash
brew install imagemagick
```

Additionally, for previewing work in progress, pygame is required:

```bash
pip install pygame
```

# Getting Started with MoviePy
To access all necessary functions and classes in MoviePy, import them:

```python
from moviepy.editor import *
video = VideoFileClip("input_video.mp4")
```

We initialize a video variable that represents the underlying video clip we are operating on.

# Resizing and Rotating Videos
Let's begin by resizing a video:

```python
video.resize(width=404, height=240).write_videofile("resized_video.mp4")
```

Similarly, we can rotate videos:

```python
video.rotate(180).write_videofile("rotated_video.mp4")
```

# Cutting and Extracting Segments

Trimming segments from a video is effortless with MoviePy:

```python
video.subclip(5, 15).write_videofile("subclip_5_15_video.mp4")
```

# Exporting a GIF
Creating a GIF from a video segment is easy:

```python
video.subclip(5, 15).resize(width=404).rotate(180).to_gif("output_video.gif")
```

# Conclusion
In this tutorial, we covered various features of MoviePy, showcasing its simplicity and efficiency in video editing tasks. For more advanced techniques with MoviePy, consider subscribing to our channel for future tutorials.

Explore these examples, experiment, and enjoy the creative possibilities MoviePy offers in simplifying video editing!
Odoo : move a field using xpath
Published: 2024-01-02 17:20:55

If you are working in Odoo, often you will have the situation to move fields from one place to other. 

here is the quick snippet to do it 

```
<xpath expr="//field[@name='targetfield']" position="before">
                    <field name="the_field_to_be_moved"
						   position="move"/>
               </xpath>
```
Token Devtools Inspector 👀🔑
Tags: webdev, javascript, jwt, extensions
Published: 2024-01-02 17:14:50

🙋🏻‍♂️ Have you ever found yourself copying the JWT of a request in Chrome? Whether it's to use it in Postman, inspect it in JWT, or any other task, and? Is it something you do frequently? 🤔

I do, and truth be told, the process can become a pain after so many times:

1. open Chrome's DevTools 🛠️
2. Go to the Network panel 🔍
3. Search for the request you are interested in 🕵️
4. Open the Headers section 📜
5. Select the entire JWT (and keep your fingers crossed that you don't copy it wrong) 🤞
6. Finally, copy it 📋

Now, imagine having to do this several times a day, every day! 💀

Luckily, I've created a Chrome extension that makes this a lot easier: 🌟 **Token Dev Tools Inspector** 🌟

With just a few clicks, streamline token extraction in Chrome DevTools:

1. Open Chrome DevTools 🛠️
2. Locate the Token Inspector panel (similar to the Console, Network or Application panels) 🔍
3. Find your tokens effortlessly! 🚀


![Preview of Token dev tools inspector](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/y4ztfc37abluym68bgpe.png)

As you can see, it goes straight to the point, simple but functional UI, also with direct access to jwt.io if you want to inspect the token content.

Are you worried about the privacy of a third party reading your tokens? I understand, that's why the project is Open Source so you can verify that the data doesn't go outside!
[https://github.com/Guuri11/token-inspector](https://github.com/Guuri11/token-inspector)

If you want to give it a try, here is the link to install the extension with all its information:
[https://chrome.google.com/webstore/detail/token-devtools-inspector](https://chrome.google.com/webstore/detail/token-devtools-inspector/enlnbonndfjonmelmplbmgnobjffbhoj)

I hope you like it, and as I said, the project is Open Source, so don't hesitate to give your feedback if you want!

Happy new year! 🎊
Mocking with Rust
Tags: rust, beginners
Published: 2024-01-02 17:02:18

I've got something cooking that i've written in Rust and I recently discovered a neat trick to test it.

Coming from python, mocks are a thing i often reach for. I find it really neat that I can throw an api from a package in a test harness so easily, same as how I'd do with a HTTP api in an integration test.

Something external I often mock is time. That's not some deep nihilist philosophy, i mean literally if there's a delay i'll mock out stuff that waits, sleep, etc so that my tests can prove the delayed behaviour instantly.

In the Rust thing I'm working on I faced this exact issue, specifically a timeout on a socket.
I have a check on an `Instant`, is .`elapsed()` greater than a `Duration`, and if it is I drop the socket from the hashmap it's stored in and it gets closed.

But I don't want my tests to wait the actual time, I want to be able to manipulate that time.

In python I would move the external world of the time api around the timeout internal to my function, but in Rust I can use an impl inside my tests to flip that and just move my timeout internal to my struct around the external world. check this out:


```rust
struct WaitingPlace {
    last_switch: Instant,
    switch_every: Duration,
    is_on: bool,
}
impl WaitingPlace {
    fn new(switch_every: Duration) -> Self {
        Self {
            last_switch: Instant::now(),
            switch_every,
            is_on: false,
        }
    }
    fn do_stuff(&mut self) {
        self.flip_check();
        println!("is_on: {}", self.is_on);
    }
    fn flip_check(&mut self) {
        if self.last_switch.elapsed() > self.switch_every {
            self.last_switch = Instant::now();
            self.is_on = !self.is_on;
        }
    }
}
#[cfg(test)]
mod tests {
    fn test_time() {
        use super::WaitingPlace;
        impl WaitingPlace {  // <- here's the magic where I reach into the struct and change the time
            fn move_time(&mut self, last_switch: Instant) {
                self.last_switch = last_switch;
            }
        }

        let mut wp = WaitingPlace::new(Duration::new(1, 0));
        assert_eq!(wp.is_on, false);
        wp.do_stuff();
        assert_eq!(wp.is_on, false);
        wp.move_time(Instant::now() - Duration::new(1, 0));
        wp.do_stuff();
        assert_eq!(wp.is_on, true);
    }
}
```

it's effectively a window onto the internals of my WaitingPlace struct that only exists in my tests. pretty neat i reckon. Maybe this is super obvious to you seasoned rust devs, or maybe i've created an abomination that no one wants to see. Either way i thought it was neat.

If you know a better way of doing this let me know.
create dark mode context react mui
Published: 2024-01-02 16:53:58

**To add dark mode to react with context in mui.
Steps to do:**

1. The first step is to install mui in your project:

npm install @mui/material @emotion/react @emotion/styled

Now, let's create a simple dark mode context and toggle between light and dark themes using MUI. Here's an example:

**Create a DarkModeContext.js file for the context:**

```
// DarkModeContext.js
import React, { createContext, useContext, useState } from 'react';

const DarkModeContext = createContext();

export const DarkModeProvider = ({ children }) => {
  const [darkMode, setDarkMode] = useState(false);

  const toggleDarkMode = () => {
    setDarkMode((prevMode) => !prevMode);
  };

  return (
    <DarkModeContext.Provider value={{ darkMode, toggleDarkMode }}>
      {children}
    </DarkModeContext.Provider>
  );
};

export const useDarkMode = () => {
  return useContext(DarkModeContext);
};
```
**Wrap your main App component with the DarkModeProvider:**

```
// App.js
import React from 'react';
import { DarkModeProvider } from './DarkModeContext';
import MyApp from './MyApp';

const App = () => {
  return (
    <DarkModeProvider>
      <MyApp />
    </DarkModeProvider>
  );
};

export default App;
```

**Use the useDarkMode hook in your components to access the dark mode state and toggle function:**

```
// MyApp.js
import React from 'react';
import { useDarkMode } from './DarkModeContext';
import { ThemeProvider, createTheme } from '@mui/material/styles';
import { Button, CssBaseline, Paper, Typography } from '@mui/material';

const MyApp = () => {
  const { darkMode, toggleDarkMode } = useDarkMode();

  const theme = createTheme({
    palette: {
      mode: darkMode ? 'dark' : 'light',
    },
  });

  return (
    <ThemeProvider theme={theme}>
      <CssBaseline />
      <Paper style={{ padding: 16, textAlign: 'center' }}>
        <Typography variant="h4" gutterBottom>
          Welcome to My App
        </Typography>
        <Button onClick={toggleDarkMode} variant="contained" color="primary">
          Toggle Dark Mode
        </Button>
      </Paper>
    </ThemeProvider>
  );
};

export default MyApp;
```

Now, your app is set up with a dark mode context using Material-UI. The DarkModeProvider provides the dark mode state and a function to toggle it, and you can use the useDarkMode hook in your components to access this functionality. The ThemeProvider from MUI allows you to switch between light and dark themes dynamically. The CssBaseline component helps to normalize styles and make the dark mode transition smoother.
hello (dev.to) world
Tags: saas, startup, webdev
Published: 2024-01-02 16:42:28

# Why am I here?

My name is Tom and I have a problem that I want to talk to you about.

Many years ago I built [localhost.run](https://localhost.run) to help me write webhooks and accidentally got a bunch of users on it. Since then I've been launching and building and changing and re-launching over and over in an attempt to make it into my day job. Each time something has gotten in the way.

Today I'm trying something different.

# What am I talking about?

[localhost.run](https://localhost.run) puts your localhost webapp on the internet.

If you've got a web app knocking about that you don't mind putting on the internet for a minute, fire it up now on port 8080.
If not then find a directory that doesn't have anything secret in it and start either a python (`python -m http.server 8080`) or node (`npx http-server -p 8080`) webserver, then run this command:

```
ssh -R 80:localhost:8080 nokey@localhost.run
```

You'll get an internet accessible URL back that anyone on the internet can connect to to see your webapp.

Simple right?

But building stuff is easy, it's all the stuff that isn't building that is difficult.

# How will I (try to) solve my problem?

I'm fortunate that life has allowed this to be my side project, but that's not guaranteed sustainable, I need it to become a business that I can fully focus on for that. All the building i've done has only taken it this small distance by luck.

So instead of again rebuilding it to be faster or fixing stuff in the frontend or moving stuff around in the backend to be more scalable, I'm going to talk about it with all of you.

There's still work to do, so a lot of this will be technical details about how i've built and will build not just localhost.run but also stuff around it.

But I also want to talk about my journey towards figuring out how to build a business around it, so there will be a lot of that too. Be warned tho, I know how to build software, but have no idea how to build a business, so don't treat both as equally as authoritative ;)

My hope is that if I externalise this stuff it will give me a signal that i'm moving forward instead of just moving around.

I've got a bunch of stuff planned, some of that in the technical space is astro.build and rust, two things i've recently gotten into, and i've also got an article brewing about how to move gigiabits per second thru a python socket proxy if you're into that kind of thing, so subscribe if you want to hear about these ;)

If you happen by this article please do respond back if you've got any suggestions for me or anything you'd like to know about localhost.run.

edit: first tech article of many done: [mocking with rust](https://dev.to/localhost-run/mocking-with-rust-32a2)
Choose boring technology
Tags: engineeringprocess
Published: 2017-09-08 18:57:21

---
title: Choose boring technology
published: true
description: engineering
tags: engineering process
---
 
In one of [Charity Majors' talks](https://dev.to/ben/charity-majors-is-my-spirit-animal), I've seen yesterday, she mentioned, Dan McKinley's post [Choose Boring Technology](http://mcfunley.com/choose-boring-technology). I've found it  and it is a real gem! Memorizing this post should be the final assignment for any programming course!

Why I think it is that important? It reminds us, engineers, what are out goals. I assure you we are not engineering for the sake of engineering. I've seen couple of times when instead of solving problems engineers were working on something just because it was new and cool. 

The most striking example of "chasing shiny objects" I've seen was a proposal to remodel development process, that came from a totally fresh employee (and recent collage graduate). The guy did not have any idea why the current process was introduced, he had only a rough understanding how developers work, the only thing that mattered was that they were not using some trendy build system he happened to know. He was crushed by questions from senior engineers and they proved that his solution would take the development process 10 years back. Not only, he had not done his homework and had learnt how the current solution works, but more importantly he had not assessed the impact his changes would have had on the other's work.

Don't be this guy, read Dan's post and learn it by heart!
Find in batches and pluck
Tags: rails, performance, ruby, development
Published: 2024-01-02 16:34:00

---
title: Find in batches and pluck
published: true
description: How to use find in batches with pluck in Ruby on Rails.
tags: #rails, #performance, #ruby, #development
# cover_image: https://direct_url_to_image.jpg
# Use a ratio of 100:42 for best results.
published_at: 2024-01-02 16:34 +0000
---


How to use find in batches in Ruby on Rails along with pluck.

```ruby
class NewYearJob
  def perform
    Employee.active.in_batches do |employees|
      rotate_jobs = employees.pluck(:id).map do |employee_id|
        RotateYearJob.new(employee_id)
      end

      ActiveJob.perform_all_later(rotate_jobs)
    end
  end
end
```
Difficulty Finding Content on Commercial Property Assessed Clean Energy (C-PACE) on Dev.to
Published: 2024-01-02 16:11:45

Hello Dev.to Support Team,

I hope this message finds you well. I am reaching out to bring attention to a concern I've encountered while navigating your platform.

I have been actively searching for information and discussions related to "**[Commercial Property Assessed Clean Energy](https://cmscf.com/cms-cf/)**" (C-PACE) on Dev.to. Unfortunately, my attempts to find relevant content or discussions on this specific topic have been unsuccessful. It seems that either the search functionality may not be yielding accurate results or there may be a lack of content addressing C-PACE within the platform.

As commercial property owners and businesses increasingly explore sustainable energy solutions, C-PACE financing plays a crucial role. Users on your platform may be interested in sharing insights, experiences, and knowledge related to C-PACE, making it a valuable topic for discussion.

I kindly request the support team to investigate this matter and consider ways to improve the search functionality or encourage the creation of content related to Commercial Property Assessed Clean Energy. This could contribute to fostering a more diverse and informative community on Dev.to, catering to the interests and needs of users involved in sustainable and energy-efficient commercial property initiatives.

Thank you for your attention to this matter, and I appreciate your efforts in maintaining an engaging and inclusive platform on Dev.to.

Best regards,
Paul Lander