teleren/devto huggingface dataset:
The strangest thing in Ruby
Tags: ruby, rails, webdev
Published: 2022-03-16 05:03:07

I recently ran in the the following error via Rubocop in Ruby 3.1: 

```Omit the hash value```

I was puzzled and Googling didn't really help me find anything - until I dug into Rubocop itself (the error is given [here](https://www.rubydoc.info/gems/rubocop/RuboCop/Cop/HashShorthandSyntax))

It turns out that this warning is saying that we are now allowed to omit hash values _if_ the variable name is the same as the hash key. 

See the following example: 
```(ruby)
# Assume Point has two parameters, X and Y

# Before Ruby 3.1
x = 3
y = 10
Point.new(x: x, y: y)

# After Ruby 3.1
x = 3
y = 10
Point.new(x:, y:)
```
Notice how we can now just use the key names and leave the variables empty!

It's called Ruby's hash omission syntax, and it's new, as of Ruby 3.1!
Como agrupar asserts no JUnit
Tags: braziliandevs, java, junit
Published: 2022-03-16 04:53:15

---
title: Como agrupar asserts no JUnit
description: Sem julgamentos, veja uma forma melhor de agrupar múltiplos asserts em um mesmo teste
tags: [braziliandevs, Java, junit]
---

Pode haver momentos em que precisamos usar múltiplos asserts em um mesmo teste. Independente se você considera certo ou errado, afinal não estamos aqui para julgar, eu gostaria de apresentar uma forma de lidar melhor com estes asserts agrupando-os através do método [`assertAll()`](https://junit.org/junit5/docs/current/api/org.junit.jupiter.api/org/junit/jupiter/api/Assertions.html#assertAll(org.junit.jupiter.api.function.Executable...)).

No código abaixo eu tenho 2 testes, cada um com 2 asserts que falham. No primeiro eu usei asserts individuais enquanto no segundo eu os agrupei.

```java
import static org.junit.jupiter.api.Assertions.assertAll;
import static org.junit.jupiter.api.Assertions.fail;

import org.junit.jupiter.api.Test;

class AppTest {
  @Test
  void usingIndividualAsserts() {
    fail("Test 1, assert 1");
    fail("Test 1, assert 2");
  }

  @Test
  void usingGroupedAsserts() {
    assertAll(
      () -> fail("Test 2, assert 1"),
      () -> fail("Test 2, assert 2")
    );
  }
}
```

Meu `build.gradle.kts` está assim (estou usando Gradle 8.4):

```kotlin
plugins {
  java
}

repositories {
  mavenCentral()
}

dependencies {
  testImplementation(platform("org.junit:junit-bom:5.10.0"))
  testImplementation("org.junit.jupiter:junit-jupiter")
}

tasks.test {
  useJUnitPlatform()

  testLogging {
    showExceptions = true
    showCauses = false
    showStackTraces = false
    exceptionFormat = org.gradle.api.tasks.testing.logging.TestExceptionFormat.FULL
  }
}
```

E esta é a estrutura do meu projeto de teste:

```
project
├── build.gradle
└── src
    └── test
        └── java
            └── AppTest.java
```

A princípio ambos os testes rodam da mesma forma, porém, veja a saída no console quando eu executo o comando `gradle test`:

```yml
AppTest > usingIndividualAsserts() FAILED
    org.opentest4j.AssertionFailedError: Test 1, assert 1

AppTest > usingGroupedAsserts() FAILED
    org.gradle.internal.exceptions.DefaultMultiCauseException: Multiple Failures (2 failures)
        org.opentest4j.AssertionFailedError: Test 2, assert 1
        org.opentest4j.AssertionFailedError: Test 2, assert 2
```

Veja como no primeiro teste apenas a primeira falha é reportada. Na verdade, ele nem chega a executar o segundo assert, pois o teste é interrompido imediatamente.

Já no segundo teste as 2 falhas são reportadas nos dando a visão completa do que deu errado logo de cara.

Por isso, se vai usar vários asserts num mesmo teste, não deixe de agrupá-los, beleza?
Why doesn't JavaScript have a nullish-coalescing-assignment (??=) operator?
Tags: javascript, discuss
Published: 2022-03-16 04:46:43

JavaScript has `??`, and is used by doing `x ?? y`.
The purpose of which is to replace null-like values with another, instead of `||`, which favors the right hand side if the left is falsy, regardless of whether it is nullish or not.
[To understand it better, read more about it on the Mozilla Developer Network, that can explain it better than me.](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Nullish_coalescing_operator)

Anyways.
Where am I going with this?
... Well, if you look at the operators in JavaScript, you'll see a pattern with them:
```javascript
a = a + b;    // Factorable to: a += b
a = a - b;    // Factorable to: a -= b
a = a ** b;   // You can even factor this to: a **= b

a = a ?? b;   // Can't be factored to: a ??= b
              // ...?
```

This isn't a big issue, but it would make the language more consistent.
Not only that, but it would be a nice way to clean up constructors. For example:
```javascript
class Shape {
    constructor(x, y, w, h) {
        this.x = x ?? this.x;
        this.y = y ?? this.y;
        this.w = w ?? this.w;
        this.h = h ?? this.h;
    }
    
    // ...
    
    h = 0;
    w = 0;
    x = 0;
    y = 0;
}

// Could theoretically become...

class Shape {
    counstructor(x, y, w, h) {
        this.x ??= x;
        this.y ??= y;
        this.w ??= w;
        this.h ??= h;
    }
    // ...
}
```
As I said, it isn't a huge difference, but redundancy-removals similar to this are the reason `+=` even exist in the first place.

So, I present to you the question posed in the title.
Why doesn't JavaScript have a nullish-coalescing assignment operator&nbsp;&nbsp;&nbsp;&nbsp;(`??=`)?




<b><center><h1><b>Thanks for reading!<br/>Cheers!</b></center></h1></b>
Rendering existing website in component
Tags: react, beginners, help
Published: 2022-03-16 04:36:13

Hi!
I'm currently in the search of technology for my web app and the best bet so far I have on React, but the problem is that I cannot find info, whether the idea I have is even possible.

What I'm trying to achieve is to have two side-by-side components (A and B) split 50/50 on the screen, where A component will have some sort of controls, while B will be able to render any website just by providing url to such website. Effectively it should behave like iframe.

My simple POC idea is to for example change background color of website rendered in B by using one of controls in A. Another simple task, would be to list all of DOM elements from B inside some list in A. Such element on the list once it'll be clicked in A will be highlighted in B.

From what I gathered so far iframe should be possible inside React component, but at the same time it is treated as sandbox and no interactions can be performed with other components.

I am aware that I'm asking about rather complex topic, but I don't want to spend time learning React just to learn after some time that I wasted time, because such feature is just not possible...

Thanks for any feedback.
Hi again. Where did the time go?
Tags: watercooler, it, career, introduction
Published: 2022-03-16 04:19:24

Long story short I posted here in like 2019 _once_ and I got thousands of views on that post.

Still tickles me pink to this day.

That post was all about being a web developer and how crazy it is, furthermore, to be a full stack dev of any sort. From how I understand it the industry has only continued to grow in that direction. Cue thoughts, rants and controversy about Web3, and what it likely means for developers who make things for browsers and mobile devices.

But since that post I have left that corner of the tech industry behind and I'm pretty okay with that.

At this point I'm actually a senior systems administrator in a department of about two dozen people. I have little or nothing to do with web development anymore beyond talking with internal software and and devops folks on how their new in-house deliverables will integrate with our standing systems.

Nowadays when I'm programming at work it's usually some .NET-heavy PowerShell and maybe some C# if I actually need a fully compiled application, and not just a PSSession full of .NET assembly calls and NuGet modules.

At home I'm messing around with Rust for fun and building a Discord bot with a friend. I'm slowly unlearning my hatred for finicky systems-level programming instilled by learning C++ as a first language.

Frankly I'm posting here again because Twitter's a cesspool and Fediverse often feels like I'm standing between groups of people with signs and bullhorns; probably arguing about something Big Tech said or did. I'm not about that vibe.

So uh, hi? Again?

---
Photo by <a href="https://unsplash.com/@sleblanc01?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText">Stephanie LeBlanc</a> on <a href="https://unsplash.com/s/photos/bear-wave?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText">Unsplash</a>
Instance Vs. Class
Tags: rails, ruby, beginners, tutorial
Published: 2022-03-16 03:59:56

On introduction, the idea of instances and classes can seem overwhelming. However, they are actually quite simple concepts to understand over time. Let’s take a step back, and look at them in another light.

**What is a Class?**
A class is in practice, a blueprint while an instance is a single occurrence of a class. Let’s think about it like this, when creating a table for a car class, I might say it has a make, model, color, and a year. These attributes would be defined in our table and permitted in our create method. These blueprints aren't the actual car, instead they lay out step by step what every car should consist of and give us other helpful information (Class Methods) to be used in creation.

**What is an Instance?**
An instance is the product of a class. For example, an instance of our Cars class could be a black 2019 Dodge Charger. Another instance could be a 1993 red Chevy. These are all single occurrences of the cars class, all following the specific blueprint we created. These instances are all unique in value, but they still share the same attributes. If we were to strip the instances down to their very basic mold, they have a make, model, color and year. This is how the blueprint is used. 
**How to create an instance:**
Using our previous Car class and assuming string types for all except year, we could use .create
`Car.create(make: "Dodge",model: "Charger",color: "Matte Black",year: 2015)`
_or we could assign an instance to a variable:_
assuming we have setter and getter methods in our class file
`attr_reader :make, :model, :color, :year`
we could go the following in our rails console
`my_new_car = Car.new
my_new_car.make= "Dodge"
my_new_car.model= "Charger"
my_new_car.color= "Blue"
my_new_car.year= 2015`

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4ks8hikan2csqg2osrgg.png)

**Which way do you like more? Open to feedback.**
check out my github to see which method I like most:
https://github.com/robinlashae1
Acessando/Espelhando tela do celular no PC
Tags: braziliandevs, tooling, github
Published: 2022-03-16 03:38:42

# Sobre
Para prevenir que você perca dados importantes ou perca meios de comunicações como o WPP do seu celular, recomendo que utilize o app **scrcpy** que permite você espelhar a tela do seu celular no pc via USB. O scrcpy permite acessar seu celular caso venha ocorrer algum problema, no meu caso estou precisando esperar uns vinte minutos pra tela acender após clicar no botão de power.

# Utilização
Passos para instalação:

* [Acesse o repositório do scrcpy]
(https://github.com/Genymobile/scrcpy)
* [Baixe o app de acordo com seu sistema operacional(Windows no meu caso)](https://github.com/Genymobile/scrcpy):
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3jbeqyi12co8wtku6tkt.png)
* Extraia o arquivo zipado.
* Agora ative o modo desenvolvedor e modo depuração no seu celular.
 * Cada celular tem uma maneira, mas vou tentar te ajudar.
 * Vá nas configurações -> Sistema -> Sobre -> Informações do Software -> Clique 7 vezes na aba Número da versão
 * Após isso deve aparecer uma mensagem "Agora você é um desenvolvedor!" ou algo do tipo
 * Volte um pouco e vá em opções de desenvolvedor e habilite a depuração USB
* Vincule o USB no seu celular e no seu PC
* Agora volte para a pasta do arquivo que você extraiu e abra o .exe do scrcpy
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/gvuu9c59mxgxhb1abydw.png)

#Finalização 
Pronto, você consegue utilizar seu celular pelo PC. Se preferir pode tentar vincular a conexão do PC e celular via Wi-Fi, posso trazer essa feature para esse artigo mais tarde. Bom uso!
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/mspapq6wdastgq9e6c42.png)
Test gRPC services with gRPCurl
Tags: grpc, protobuf, productivity
Published: 2022-03-16 03:33:19

# Test gRPC services with gRPCurl

The gRPC functions can only be called by gRPC clients. My team just started migrating to gRPC stack, and I found gRPCCurl is a very helpful CLI tool to test and debug. 

## Installation

```shell
brew install grpcurl
```



## Usage

Start your gRPC service and check the service metadata. My service is running on port of 10030.

Use "-plaintext" if your service does not use TLS.

```shell
grpcurl -plaintext localhost:10030 describe
grpc.health.v1.Health is a service:
service Health {
  rpc Check ( .grpc.health.v1.HealthCheckRequest ) returns ( .grpc.health.v1.HealthCheckResponse );
  rpc Watch ( .grpc.health.v1.HealthCheckRequest ) returns ( stream .grpc.health.v1.HealthCheckResponse );
}
grpc.reflection.v1alpha.ServerReflection is a service:
service ServerReflection {
  rpc ServerReflectionInfo ( stream .grpc.reflection.v1alpha.ServerReflectionRequest ) returns ( stream .grpc.reflection.v1alpha.ServerReflectionResponse );
}
sample_module.sample_package.SayHi is a service:
service SayHi {
  rpc SayHello ( .sample_module.sample_package.HelloRequest ) returns ( .sample_module.sample_package.HelloReply );
}
```

Call sample_module.sample_package.SayHi service.

```shell
grpcurl -d '{"msg": "jimmy"}' -plaintext localhost:10030 sample_module.sample_package.SayHi/SayHello
{
  "msg": "SayHijimmy",
  "code": "1"
}
```
Carbon Add Minutes In Laravel Example
Tags: laravel, laravel8, php, carbon
Published: 2022-03-16 03:10:14

In this tutorial, we will see an example of carbon add minutes in laravel, here I will give you a simple example of laravel carbon add minutes, carbon provides many function like addMinute(), addMinutes() to add minute in laravel 8. Using the carbon addMinute() or addMinutes() function you can change the minutes in the date in laravel 8.

If we need to add minute or more then one minutes in date and time then you can use carbon in laravel. carbon provides addMinute() and addMinutes() method to add minutes on carbon date object.

So, let's see an example of laravel 8 carbon add minutes to date or add minutes using carbon in laravel 8.

---

> **_[Read More : Carbon Add Minutes In Laravel Example](https://techsolutionstuff.com/post/carbon-add-minutes-in-laravel-example)_**
GeoNode Basic Installation using Docker
Tags: python, django, linux, opensource
Published: 2022-03-16 02:30:53

GeoNode is an open-source spatial data infrastructure (SDI) that is open source and used to store and manage geospatial data including sharing it over the web.

**Docker** came to revolutionize the DevOps practices and here is one example of such. Let us deploy GeoNode in Ubuntu 20.04 using docker.

{% youtube O4xZ5_unX5g %}
One-click attack nima?
Tags: hacking, dotnet, uzbek, beginners
Published: 2022-03-16 02:11:45

[XSRF/CSRF](https://crashtest-security.com/cross-site-request-forgery-csrf/) (one-click attack) hujumlar deb bir zararli saytdan turib boshqa saytga hujum qilinishga aytiladi.

Quyidagi holatga nazar tashlang:

- siz **https://halol-bank.uz** saytiga *login* qilganingizda u sayt sizga `id_token` ya'ni *kalit* beradi. 
- *Login*dan keyin sizni **https://halol-bank.uz** har bir so'rovingizga *brauzer* yuqoridagi kalitni qo'shib yuboradi. Bu har bir tugma bosga parolni qayta-qayta teravermaslik uchun kerak.
- siz endi **https://parazit.uz** nomli zararli saytga kirdingiz va u yerda `Sovg'ani yutib ol 🥳🎉` degan tugmani ko'rib uni bosasiz
- bu tugma ortida quyidagicha kod yashiringan
```html
<h1>Sovg'ani yutib ol 🥳🎉</h1>
<form action="https://halol-bank.uz/api/account" method="post">
    <input type="hidden" name="Transaction" value="PulYechish" />
    <input type="hidden" name="Qiymat" value="1000000" />
    <input type="submit" value="Tugmani bosing!" />
</form>
```
- yuqoridagi kodga e'tibor bering. Zararlangan vebsayt `halol-bank` ga so'rov jo'natmoqchi. 
- esingizda bo'lsa siz *login* qilganingizdan keyin kalit berilgandi. Ushbu yuqoridagi tugma bosilganda so'rov `halol-bank`ga boradi, shuning uchun kalit qo'shib jo'natiladi
- qarabsizki kalitni ko'rgan bank bu *parazit* saytni siz deb o'ylaydi va **1000000** miqdordagi pulni hisobingizdan yechib oladi


> Yuqorida tushinish **One-click attack**ni tushintirish uchun sodda/uydirma misollardan foydalanildi.

Bunda hujumlarni oldini olish uchun **ASPNET Core**da `AntiForgeryToken`lardan foydalaniladi. Ular haqida batafsil keyingi postda.
Azure - Use regional endpoint for ARM REST API calls
Tags: azure, powershell
Published: 2023-09-13 15:41:06

---
title: Azure - Use regional endpoint for ARM REST API calls
published: true
date: 2022-03-16 00:00:00 UTC
tags: Azure,Powershell
canonical_url: 
---

Recently I opened different support cases to Microsoft for an unusual behavior on Azure.

When I created a new resource in West Europe, it was available on the Azure portal, but from my Automation Account in North Europe I could not see it.

In other words, when I did a **Get-AzStorageAccount -ResourceGroup $resourceGroupName** from my workstation I could see my new storage, but from my Automation account I could not.

In order to diagnose the problem there is a very simple way, you just have to do in powershell the following commands:

```
$token = Get-AzAccessToken
$authHeader = @{
    'Content-Type'='application/json'
    'Authorization'='Bearer ' + $token.Token
}

$locations = @("westeurope", "northeurope")

foreach ($location in $locations) {
    Write-Host "Location : $location" -ForegroundColor Cyan
    $restUrl = "https://$location.management.azure.com/subscriptions/$subscriptionId/resourceGroups/$resourceGroupName/resources?api-version=2022-01-01"; 
    (Invoke-WebRequest -Uri $restUrl -Method GET -Headers $authHeader).Headers
}

```

And you will see through which region your calls go through via the **x-ms-routing-request-id** header which contains the **WESTEUROPE** value corresponding to the region

Very useful when there is a synchronization problem on Azure side, and the support can force a sync if you don’t want to wait for it to happen
Mongolian OCR in C# and .NET
Published: 2022-03-16 01:55:08

---
canonical_url: https://ironsoftware.com/csharp/ocr/languages/mongolian/
---

_Other versions of this document_

- [Монгол хэлээр](https://ironsoftware.com/csharp/ocr/languages/mongolian-mn)
- [125 More OCR Languages](https://ironsoftware.com/csharp/ocr/languages/)

IronOCR is a C# software component allowing .NET coders to read text from images and PDF documents in 126 language, including Mongolian.

It is an advanced fork of Tesseract, built exclusively for the .NET developers and regularly outperforms other Tesseract engines for both speed and accuracy.

## Contents of IronOcr.Languages.Mongolian

This package contains 52 OCR languages for .NET:

- Mongolian
- MongolianBest
- MongolianFast

## Download

Mongolian Language Pack [**монгол**]

- Download as [Zip](https://ironsoftware.com/csharp/ocr/packages/language-packs/Mongolian.ocrdata)
- Install with [NuGet](https://www.nuget.org/packages/IronOcr.Languages.Mongolian/)

## Installation

The first thing we have to do is install our **Mongolian** OCR package to your .NET project.

`PM> Install-Package IronOCR.Languages.Mongolian`

## Code Example

This C# code example reads Mongolian text from an Image or PDF document.

**C#:**
```cs
//PM> Install-Package IronOcr.Languages.Mongolian
using IronOcr;
var Ocr = new IronTesseract();
Ocr.Language = OcrLanguage.Mongolian;
using (var Input = new OcrInput(@"images\Mongolian.png"))
{
    var Result = Ocr.Read(Input);
    Var AllText =  Result.Text
}
```

**VB:**
```
'PM> Install-Package IronOcr.Languages.Mongolian
Imports IronOcr
Private Ocr = New IronTesseract()
Ocr.Language = OcrLanguage.Mongolian
Using Input = New OcrInput("images\Mongolian.png")
	Dim Result = Ocr.Read(Input)
	Dim AllText As Var = Result.Text
End Using
```
MICR OCR in C# and .NET
Published: 2022-03-16 01:45:34

---
canonical_url: https://ironsoftware.com/csharp/ocr/languages/micr/
---

[126 More Languages](https://ironsoftware.com/csharp/ocr/languages/)

IronOCR is a C# software component allowing .NET coders to read text from images and PDF documents in 126 language, including MICR.

It is an advanced fork of Tesseract, built exclusively for the .NET developers and regularly outperforms other Tesseract engines for both speed and accuracy.

## Contents of IronOcr.Languages.MICR

This package contains 11 OCR languages for .NET

- MICR

## Download 

MICR Language Pack [Magnetic Ink Character Recognition]

- Download as [Zip](https://ironsoftware.com/csharp/ocr/packages/language-packs/MICR.ocrdata)
- Install as [NuGet](https://www.nuget.org/packages/IronOcr.Languages.MICR/)

## Installation

The first thing we have to do is install our **MICR** OCR package to your .NET project.

`PM> Install-Package IronOCR.Languages.MICR`

**C#:**
```cs
//PM> Install-Package IronOcr.Languages.MICR
using IronOcr;
var Ocr = new IronTesseract();
Ocr.Language = OcrLanguage.MICR;
using (var Input = new OcrInput(@"images\MICR.png"))
{
    var Result = Ocr.Read(Input);
    Var AllText =  Result.Text
}
```

**VB:**
```
'PM> Install-Package IronOcr.Languages.MICR
Imports IronOcr
Private Ocr = New IronTesseract()
Ocr.Language = OcrLanguage.MICR
Using Input = New OcrInput("images\MICR.png")
	Dim Result = Ocr.Read(Input)
	Dim AllText As Var = Result.Text
End Using
```