teleren/devto huggingface dataset:
Running packer hcl2_upgrade and getting pkr.hcl file with template hcl2_upgrade unexpected in operand
Tags: packer, hashicorp
Published: 2023-05-31 22:00:00

---
title: Running packer hcl2_upgrade and getting pkr.hcl file with template hcl2_upgrade unexpected in operand
published: true
description: 'Introduction   Since Packer v1.7.0, it is recommended to use HCL2 instead of JSON for Packer...'
tags:
  - Packer
  - HashiCorp
published_at: '2023-05-31 22:00 +0000'
id: 1661911
date: '2023-05-31T22:00:00.000Z'
---

## Introduction

Since Packer v1.7.0, it is recommended to use HCL2 instead of JSON for Packer templates.
The `.pkr.hcl` file generated by the `hcl2_upgrade` command, which converts a Packer template written in JSON to HCL2 format, will output `"template: hcl2_upgrade:3: unexpected \"\\\\\" in operand"` in the `.pkr.hcl` file generated by executing the `.pkr.hcl` command.

## Solution

https://github.com/hashicorp/packer/issues/10728#issuecomment-793199077

In this case, the `\"` (escaped quote) used for escaping was not parsing JSON properly.
You can work around this problem by changing `\"` (escaped quote) to backtick.

### Before

Running `packer hcl2_upgrade` on a JSON file defined as follows...

```json
{
  "builders": [{
    "type": "amazon-ebs", ...
    ...
    "ami_name": "ami_name-{{isotime \"2006-01-02-15-04-MST\"| clean_resource_name}}"
  }], }
}
```

The following `.pkr.hcl` file will be generated.

```hcl
# could not parse template for the following block: "template: hcl2_upgrade:3: unexpected \"\\\\\" in operand"

source "amazon-ebs" "autogenerated_1" {
  ami_name = "ami_name-{{isotime \"2006-01-02-15-04-MST\"| clean_resource_name}}"
```

### After

After changing the description and running `packer hcl2_upgrade`...

```json
{
  "builders": [{
    "type": "amazon-ebs",.
    ...
    "ami_name": "ami_name-{{isotime `2006-01-02-15-04-MST`| clean_resource_name}}"
  }], ...
}
```

`"template: hcl2_upgrade:3: unexpected \"\\\\\" in operand"` is not output in the `.pkr.hcl` file,
but a `.pkr.hcl` file using the intended format (`legacy_isotime`).

```hcl
source "amazon-ebs" "autogenerated_1" {
  ami_name = "ami_name-{{ clean_resource_name `${legacy_isotime("2006-01-02-15-04-MST")}` }}"

```

## References

https://github.com/hashicorp/packer/issues/10728

https://developer.hashicorp.com/packer/docs/v1.7.x/commands/hcl2_upgrade

https://developer.hashicorp.com/packer/tutorials/configuration-language/hcl2-upgrade

https://developer.hashicorp.com/packer/docs/templates/hcl_templates/functions/datetime/legacy_isotime

https://developer.hashicorp.com/packer/docs/templates/legacy_json_templates/engine

https://www.packer.io/
This AWS CLI command can run instance refresh for auto scaling groups
Tags: aws, kubernetes
Published: 2023-05-31 21:49:39

Recently, I was working on upgrading Kubernetes versions for all our EKS clusters. The upgrade process is simple, We upgrade the K8s version and instance AMIs from Terraform. Then, we upgrade chart/image version of the different tools we deploy e.g: CoreDNS, ExternalDNS, kubernetes-dashboard, kube-proxy etc. 
All these steps can be automated ofcourse since we use Terraform. Especially when you have to upgrade a large number of clusters automation becomes absolutely essential. One step that always bothered me is that, you need to run an instance refresh for the autoscaling groups that your K8s worker nodes belong to. Otherwise, your EKS cluster will still be using the older worker nodes (using the older K8s version). Previously, I always did this using the AWS console manually. So, this was always a unwanted manual step in this workflow.
Recently, I discovered this AWS CLI command that turns out to be exactly what i was looking for.

First you can fetch the autoscaling groups in your account
```bash
aws autoscaling describe-auto-scaling-groups --auto-scaling-group-names | grep AutoScalingGroupName | sed 's/\"AutoScalingGroupName\": //' | sed -E 's/^\s+//' | sed -E 's/\"//' | sed -E 's/\"//' | sed -E 's/\,//' | grep worker
```
Now, we can run the instance refresh for each item in the list using the following command
```bash
for line in $(aws autoscaling describe-auto-scaling-groups --auto-scaling-group-names | grep AutoScalingGroupName | sed 's/\"AutoScalingGroupName\": //' | sed -E 's/^\s+//' | sed -E 's/\"//' | sed -E 's/\"//' | sed -E 's/\,//' | grep spot-group); do
  aws autoscaling start-instance-refresh \
    --auto-scaling-group-name $line \
    --preferences '{"MinHealthyPercentage": 99, "InstanceWarmup": 300, "SkipMatching": false}'
done
```

If you found this post helpful, CLICK BELOW 👇 <a href="https://www.buymeacoffee.com/ashiqurrahman" target="_blank"><img src="https://www.buymeacoffee.com/assets/img/custom_images/orange_img.png" alt="Buy Me A Beer" style="height: 80px !important;width: 240px !important;box-shadow: 0px 3px 2px 0px rgba(190, 190, 190, 0.5) !important;-webkit-box-shadow: 0px 3px 2px 0px rgba(190, 190, 190, 0.5) !important;" ></a>
React state explained
Tags: webdev, react, tutorial, productivity
Published: 2023-05-31 21:43:42

## React state explained

State is a runtime data that react relies upon in order to render your app. This data changes over time and typically affects the visual output of our app.

There is an example of how to use:

### Import the useState

```jsx
import { useState } from 'react'
```

### Declare the state inside of your component

```jsx
import { useState } from 'react'

const SomeComponent = () => { 
	const [name, setName] = useState('')
	
	return (
	<div>
		{name}
		<button onClick={() => setName('doug')}> Change name </button>
	</div>
	)
}

export { SomeComponent } 

```

So, as we can see, we have 2 properties returned by the useState hook:

***name**:* returns the state value

***setName**:* function to set the state value

When setName is called, react re-render the app updating the name state with the new value.

### Additional info (important)

There is another type of data that changes over time and makes part of our application but not of react state like *mouse position, scroll position and others*. The browser keeps track of this data but because doesn't live inside of react or trigger re-renders of our application, this is not React state.
Looking for beta testers to test a software deployment solution.
Published: 2023-05-31 21:24:35

Traditional deployments often involve writing hundreds of lines of complex IaC code, which can be time-consuming and prone to errors. We are changing that. OpsCanvas changes the game by offering Draw and Deploy deployments using generative IaC, which automates the production of configuration file code and abstracts the difficult and necessary tasks required in the deployment process. We would love your feedback. We are opening our beta testing program now and it will be starting mid-June. Please register at www.opscanvas.com
pyaction 4.20.0 Released
Tags: github, docker, python, showdev
Published: 2023-05-31 21:13:38

## TL;DR

I just released [pyaction](https://github.com/cicirello/pyaction) 4.20.0, a [Docker container with Python, git, and the GitHub CLI](https://dev.to/cicirello/pyaction-a-docker-container-with-python-git-and-the-github-cli-930).


## Changelog 4.20.0 - 2023-05-31

### Changed
* Bumped GitHub CLI to 2.30.0.


## Current Version List

This latest release of pyaction includes:
* Python 3.11.3
* [GitHub CLI 2.30.0](https://github.com/cli/cli/releases/tag/v2.30.0)
* git 2.30.2
* curl 7.74.0
* gpg 2.2.27



## More Information

For more information, see my earlier post about pyaction here on DEV, as well as pyaction's GitHub repository.

{% link https://dev.to/cicirello/pyaction-a-docker-container-with-python-git-and-the-github-cli-930 %}

{% github cicirello/pyaction %}



## Where You Can Find Me

Follow me [here on DEV](https://dev.to/cicirello) and on [GitHub](https://github.com/cicirello):

{% user cicirello %}

Or visit my website:

{% embed https://www.cicirello.org/ %}
Question about starting transition from another tech stack to Elixir in 2023
Tags: elixir
Published: 2023-05-31 20:55:28

Hi all!

I am a JavaScript developer with 7+ years of experience in several countries and a vast toolkit. I am looking for an "additional" skill to help me transition into an alternative tech stack that is less overcrowded and has a good future outlook. I have very little experience with Elixir, but a huge interest in the Elixir ecosystem.

Please let me know if you have any thoughts or suggestions regarding this idea.

Thank you!
Compile pg_math for YugabyteDB (wrapper on GNU Scientific Library distribution functions)
Tags: yugabytedb, distributed, postgres, extension
Published: 2023-05-31 20:45:00

Many extensions are easy to compile on PostgreSQL and install on YugabyteDB. The most important is to compile it in the right version of PostgreSQL and identify all files and dependencies.
In the first post of this series, I did it in a Dockerfile.
Here I'll run similar commands on a Docker container started from the YugabyteDB 2.18 image, that is built with Alma8, to install [pg_math](https://github.com/chanukyasds/pg_math), a wrapper for GSL (GNU Scientific Library) statistical distribution functions.

## Start YugabyteDB

As this extension comes as a dynamic library that doesn't need to be pre-loaded, I can already start YugabyteDB and will install the extension just before the CREATE EXTENSION.

I start this test container and connect to it:
```sh
docker pull   yugabytedb/yugabyte:2.18.0.1-b4 
docker exec -it $(
docker run -d yugabytedb/yugabyte:2.18.0.1-b4 /home/yugabyte/bin/yugabyted start --advertise_address=0.0.0.0 --background=false
) bash
```

## Install postgresql11-devel

YugabyteDB is compatible with PostgreSQL 11.2 and then I'll build my extension with PostgreSQL 11:

```sh
dnf update -y
dnf groupinstall -y 'Development Tools'
dnf install -y https://download.postgresql.org/pub/repos/yum/reporpms/EL-8-x86_64/pgdg-redhat-repo-latest.noarch.rpm
dnf install epel-release -y redhat-rpm-config
dnf --enablerepo=powertools install perl-IPC-Run -y
dnf -qy module disable postgresql
dnf install -y postgresql11-devel
export PATH="/usr/pgsql-11/bin:${PATH}" # add pg_config to the path
```
This is needed to build the extension. The idea is to build it in an ephemeral container and just get the necessary files to deploy to YugabyteDB nodes

## Build pg_math extension

I follow the instructions from pg_math [README.md](https://github.com/chanukyasds/pg_math#installation)
```
dnf -y install gsl gsl-devel
git clone https://github.com/chanukyasds/pg_math.git
cd pg_math
make
make install
```

## Install in YugabyteDB

I can explore the necessary files with `pg_config` and `ldd`:
![pg_config](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1i8z6m7mvku9hhpa06od.png)

I get all files from the extension (lib and share/extension) as well as the dependencies (GSL - GNU Scientific Library):
```sh
cd /usr/pgsql-11
cp /usr/lib64/*gsl* lib
tar -cvf /tmp/extensions.tar lib share/extension
cd $YB_HOME/postgres
tar --skip-old-files -xvf /tmp/extensions.tar
```

## Test the extension

Now ready to CREATE EXTENSION and test it:
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/dqfs9hs9jb7ostn2ierl.png)

When the repo for the extension contains regression tests, it is a good practice to run them.
OSDC-Assigment9-GithubActions(CI)
Tags: osdc, yaml, git, github
Published: 2023-05-31 20:38:04

In lesson 9 we learned about "Continuous Integration(CI) for GitHub projects" We learned GitHub Actions and provided examples of how to use them. The presentation included a demonstration of a simple workflow and implementation, examples of how to trigger jobs, and an overview of environment variables and repositories from @szabgab.
This links can help learn the subject:

- [repositories with sample GitHub Action](https://code-maven.com/github-actions)
- [collection of github actions](https://github.com/actions)

The assignment was to find a project with tests but without continuous integration and set up a GitHub Action to run the tests. 
I find intresting project [universities-api-wrapper](https://github.com/jremes-foss/universities-api-wrapper) from [pydigger](https://pydigger.com/)
This steps of my work in here assigment:
1) Fork the project to be able edit it.

2) Add GitHub Actions Workflow to ci.yml. in folders i create .github/workflow.

3) Create ci.yml - this my code:

```
name: CI

on:
  push:
    branches:
      - main
  pull_request:
    branches:
      - main

jobs:
  build:
    runs-on: ubuntu-latest

    steps:
      - name: Checkout code
        uses: actions/checkout@v2

      - name: Set up Python
        uses: actions/setup-python@v2
        with:
          python-version: 3.9  

      - name: Install dependencies
        run: pip install -r requirements.txt

      - name: Run tests
        run: pytest
```

4) Validate my code yaml in [yaml-validator](https://codebeautify.org/yaml-validator)

5) send [PR](https://github.com/jremes-foss/universities-api-wrapper/pull/5) that i explain to author why i create the file ci.yml.

6) To activate the workflow, you need to select it from the Actions menu and run it manually.

**Update: my PR is merged:Hi @zoharasulin. Thank you! I was intending to create this at some point, so it was very helpful you to create this pull request. Much appreciated.**

that's it!!
Thank you for listening,
Zohar.
Easy Ways to Compare Two Arrays in JavaScript
Tags: javascript
Published: 2023-05-31 20:23:52

Comparing two arrays is one of the widely used and most important challenges you might face in programming. There are many ways to do this, but we are going to learn the easiest and fastest ways.

## 1. Using loops
Of course, the first way would be looping. We can quickly compare array elements one by one. No matter whether it is a "while" loop or a `for` loop. First, we need to check the length of the two arrays. If both have the same size, we can keep the comparison up.

```js
function compareTwoArrays(arr1, arr2) {
  if (arr1.length !== arr2.length)
    return false;

  for (let i = 0; i < arr1.length; i++) {
    if (arr1[i] !== arr2[i])
      return false;
  }
  
  return true;
}

compareTwoArrays([null, 1, 2], [undefined, 1, 2])
```
Now, let's test our function. We are going to pass two arrays that are different:

```js
let array1 = [null, 1, 2];
let array2 = [undefined, 1, 2];

compareTwoArrays(array1, array2)  // false
```
As we expect, it returns false, because `null` is not equal to `undefined`

Then, let's pass two arrays that are exactly the same:

```js
let array3 = [null, 1, "a"];
let array4 = [null, 1, "a"];

compareTwoArrays(array3, array4) // returns true
```
This time, it returns true.

## 2. Using every() method
What does the `every()` method do? The `every()` method executes a function for every array element. So we can use it instead of loops. The every() method returns a boolean, and we will return the result as the result of the function. If all the elements of two arrays are equal at the same index, it returns true, otherwise returns false.

```js
function compareTwoArrays(arr1, arr2) {
  if (arr1.length !== arr2.length)
    return false;
    
  return arr1.every((element, index) => {
    return element === arr2[index]
  });
}

let array1 = [null, 1, "a"];
let array2 = [null, 1, "a"];
compareTwoArrays(array1 , array2); // true
```

And the result will be the same as before.
Upstream speaker spotlight: Julia Ferraioli, co-founder of Open Source Voices
Tags: opensource, maintainers, upstream, community
Published: 2023-05-31 20:17:17

_Upstream is a week away—June 7!—and wow, our schedule is shaping up brilliantly. Over the next week we’ll share more details about the amazing speaker lineup. [RSVP now](https://upstream.live/)!_

This is the second year in a row that Julia Ferraioli is speaking at Upstream, and we are so happy that she agreed to join us again. 

A little about Julia: she is an open source engineer, scientist, and analyst with over a decade of experience in launching, managing, and optimizing open source projects at scale at companies such as Google, Twitter, and Cisco. 

Most recently, she is the co-founder of Open Source Stories, contributor to LeadDev, and sought-after conference speaker. Her background includes research in machine learning, robotics, HCI, and accessibility. Julia finds energy in developing creative demos, creating beautiful documents, and rainbow sprinkles. She’s also a fierce supporter of LaTeX, the Oxford comma, and small pull requests. (We love the Oxford comma over here on the Tidelift events team, too.)

Julia will be the closing keynote speaker at Upstream this year; her talk, titled [How we treat others is a supply chain issue](https://upstream.live/speaker-2023/julia-ferraioli), fits in beautifully with the theme of this year’s event: The accidental supply chain. She will discuss how the sustainability and supply chain conversations often leave out a critical factor in the equation: the people and social systems without which there would be no open source.

Julia has written about the people and social systems of open source in the past, specifically in this blog post: [Open source and social systems](https://www.juliaferraioli.com/blog/2022/open-source-social-systems/); and spoke about this last year at Upstream in her talk: [A social model of open source: all the dynamics that are fit to print](https://explore.tidelift.com/upstream/main-upstream-2022/session-julia-ferraioli). We are excited to hear her more directly relate this topic to the open source supply chain, because sometimes people forget about the actual, real people who are creating and maintaining the code.

We can’t think of a better person to help close a day full of the discussion on the accidental supply chain at Upstream on June 7, 2023. [RSVP so you don’t miss it](https://upstream.live/)!
Smart Contracts en Scroll Alpha [ZK ESP Semana1]
Published: 2023-05-31 20:10:12

---
title: Smart Contracts en Scroll Alpha [ZK ESP Semana1]
published: true
description: 
tags: 
# cover_image: https://direct_url_to_image.jpg
# Use a ratio of 100:42 for best results.
# published_at: 2023-05-31 02:17 +0000
---

{% youtube dSlhXtvgbI8 %}


## Antes de comenzar

Asegurate de tener fondos en Scroll Alpha. Para obtenerlos te recomiendo [esta guía](https://twitter.com/Layer2es/status/1662140004964134914) a cargo de @Layer2es.

## Lanza un contrato En Scroll Alpha

Lanza el siguiente smart contract en [Remix](https://remix.ethereum.org/).

```solidity
// SPDX-License-Identifier: MIT
pragma solidity 0.8.19;

import "@openzeppelin/contracts/token/ERC20/ERC20.sol";

contract SimpleToken is ERC20 {
    constructor(
        string memory name,
        string memory symbol,
        uint256 initialSupply
    ) ERC20(name, symbol) {
        _mint(msg.sender, initialSupply * 1 ether);
    }
}
```

En el constructor coloca el nombre, el símbolo y el supply inicial en ether (como unidad de medida, o sea sin comas).

![ERC20 Constructor Remix](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1vdw8fmdsr56i3gxm98v.png)

## Usa el Token

Agrega el address del contrato en tu metamask y podrás empezar a usar el token.

![Agregar ERC20 a Metamask](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/m57t83oivmp6rasqxjdk.png)

Puedes probar agregar liquidez a [uniswap en scroll](https://uniswap-v3.scroll.io/) como un primer experimento.

## Para la siguiente semana

La siguiente semana lanzaremos un ZK Sudoku NFT en Goerli testnet. Será una introducción a circuitos ZK usando la librería [Zokrates](https://zokrates.github.io/gettingstarted.html) en combinación con contratos en Solidity.

Para la siguiente semana asegúrate de una wallet lista con fondos en Goerli Testnet. Adicionalmente necesitarás Node.js y un editor de texto, te recomiendo Visual Studio Code. A continuación te dejo los enlaces para la instalación:

* Linux
  * Node.js: te recomiendo descargarlo en Linux via [NVM](https://github.com/nvm-sh/nvm#installing-and-updating)
  * VS Code: https://code.visualstudio.com/docs/setup/linux
* Windows y OSX
  * Node.js: https://nodejs.org/en/download
  * VS Code: https://code.visualstudio.com/Download
Find the Length of the Last Word in a String - javascript
Tags: javascript, webdev, beginners, programming
Published: 2023-05-31 20:06:52

Let's solve a coding challenge. We will discuss how to find the length of the last word in a string using javascript as our programming language. 

First the problem statement: 
**Given a string, return the length of the last word in the string.**

To understand how to solve the problem, let's start with an example. Let's say this is our string:

 `const str = 'hello i am a string'` 

We need to isolate the last word in the string, find its length, and return it. Let's start by isolating the last word. We can separate all of the words in this string and store them in an array. In javascript we use split for this. 

`const words = str.split(' ');`

We pass a space into the function as the delimiter. This will separate the words into the array by the spaces. Once we have our array, we need to target the last element of the array and get it's length.

`const lastWordLength = words[words.length - 1].length;`

We can then return this value and our function is complete. There are two edge cases we inspect. What if there are extra spaces in our string? 

`str = '   hello i am   a string    '`;

To account for this edge case, we need to trim the extra space from the string before we split it. The code would change to this.

`const words = str.trim().split(' ');`

The other edge case is if the string is an empty string. In this case, we would just return 0;

Now we have accounted for our edge cases and the problem is effectively solved. This is what the completed function could look like. 

```
function lengthOfLastWord(s) {
    if (s.length === 0) {
        return 0;
    } else {
        const words = s.trim().split(' ');
        const lengthOfLastWord = words[words.length - 1].length;
        return lengthOfLastWord;
    }
};
```

That's it! Have a wonderful day!
Safe AAnything Goes Hackathon Submission
Published: 2023-05-31 20:05:12

---
title: Safe AAnything Goes Hackathon Submission
published: true
description: 
tags: 
//cover_image: https://direct_url_to_image.jpg
---



# Problem Statement:

Creating a subscription model based dapp is still a huge challenge in the web3 world. Some of the major challanges are:

1. Recurring Payments
 * Reccuring payments are a pain in the web3 world. Payments have to be constantly approved by EOAs.

2. Gas fees
 * Gas is spent on creating, subscribing and even for cancelling a subscription on the Blockchain

3. Need of Externally Owned Accounts
 * Need of EOAs to fund different wallets and approve tokens. It is a hectic task.


# Proposed Solution:

* A web/mobile based dapp to manage all your web3 subscriptions in one place. A place where subscribing is as easy as a click of a button. We bring Account Abstraction using Relayer servers to reduce the gas fees and improve the overrall UX. The user will authenticate through Safe Wallet (https://app.safe.global/welcome)
* Using AA, we remove the process of approving transactions agin and again.
* Account abstraction could make this system much more efficient and cost-effective. By abstracting the user's account, it separates the user's private key from their on-chain address.
* Using relayers as servers which interact with the chain for the users. The user then can create a plan where they will provide all the details of the plan and the relayer will create a plan for the merchant/user
* They can get the list of subscription to keep a track of all stuff they are subscribed to and they can view all the plans 

## Main Features:
* Keeps your personal wallet safe and secure
* easy one click subscription
* invite people to a seamless subscription method

![User Flow](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3m9bs8b9wotmwrq3bdud.png)