teleren/devto huggingface dataset:
5 useful tiny Php helper functions
Published: 2022-05-13 17:37:58

Here I am going to introduce five useful Php functions that I usually use in my projects.

1. Does an array of keys exists in an array?
You can check multiple keys existence inside an array.
```php
function array_keys_exists(array $keys, array $arr)
{
    return !array_diff_key(array_flip($keys), $arr);
}
```
```php
$sample = [1, 2, 3, 4, 5];
array_keys_exists([2, 5], $sample) // Returns True
```


2. Delete an item from an array using its value.
```php
function delete_array_item_by_value($array, $value)
{
    if (($key = array_search($value, $array)) !== false) {
        unset($array[$key]);
    }
    return $array;
}
```
```php
$sample = [1, 2, 3, 4, 5];
delete_array_item_by_value($sample, 4) // $sample = [1, 2, 3, 5];
```

3. Want to apply a closure on items of an array? You can use `array_func_map`
```php
function array_map_recursive($callback, $array)
{
    $func = function ($item) use (&$func, &$callback) {
        return is_array($item) ? array_map($func, $item) : call_user_func($callback, $item);
    };

    return array_map($func, $array);
}
```

4. Generate random int with a fixed length
```php
function get_random_int(int $length): int
{
    $res = '';
    for ($i = 0; $i < $length; $i++) {
        $res .= mt_rand(0, 9);
    }
    if ($res[0] == 0) {
        $res = mt_rand(0, 9) . substr($res, 1);
    }
    return (int)$res;
}
```
```php
get_random_int(4) // Returns 6234
```

5. Checks for all parameters are empty or not.
```php
function all_empty()
{
    foreach (func_get_args() as $arg)
        if (empty($arg))
            continue;
        else
            return false;
    return true;
}
```
```php
all_empty([], [], [3, 4]) // Returns False
all_empty([], [], []) // Returns True
```
Automate an articles section in your github.io page
Tags: ci, githubaction, githubpages, automation
Published: 2022-05-13 17:26:41


Today I wanted to update my [github page](https://protiumx.github.io/) to show a list of my
last Medium [articles](https://medium.com/@protiumx). I ended up automating it.

## First approach

My first attempt was fetching the RSS feed using the URL `medium.com/feed/@username` and parse
the `xml` document. But I was hit with a charming `CORS` error.
Now what?

I remembered that I'm using a github action to update a similar section on my [github profile](https://github.com/protiumx).
So, what if I tell this action that the README file is called `index.html`?

## blog-post-workflow

The [github action](https://github.com/gautamkrishnar/blog-post-workflow) supports a `readme_path` parameter. After 
a quick dive in its source code I noticed that this file could be anything, not necessarily a markdown file. Problem solved!

Let's add the articles section into the html:
```html
<section class="content__articles">
  <p>&gt; last published articles:</p>

  <ul>
    <!-- BLOG-POST-LIST:START -->
    <!-- BLOG-POST-LIST:END -->
  </ul>
</section>
```

Since the action is intended for markdown files, the default template for the posts links is `[title](url)` but we need html code.
Luckily the github action also provides a `template` param. So let's change the template to generate list items:
```html
<li><a href="$url" target="_blank">$title</a></li>$newline
```

That's it!

Our workflow configuration should be:
```yml
name: Update Medium articles
on:
  schedule:
    - cron: '0 0 * * 0' # Runs once a week
  workflow_dispatch:

jobs:
  update-articles-section:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v3
      - uses: gautamkrishnar/blog-post-workflow@master
        env:
          GITHUB_TOKEN: $
        with:
          feed_list: "https://medium.com/feed/@protiumx"
          readme_path: "https://raw.githubusercontent.com/protiumx/blog/main/articles/004/index.html"
          template: '<li><a href="$url" target="_blank">$title</a></li>$newline'
```
Check the file [here](https://github.com/protiumx/protiumx.github.io/blob/main/.github/workflows/medium-articles.yml).
NOTE: I added the `workflow_dispatch` trigger so I can trigger the action from the github UI.

That's all. I few lines of code and we added an automated section for our github page (or any page).

Related articles:
- [Publish your blog articles everywhere with this github action](https://dev.to/protium/publish-your-blog-articles-everywhere-with-this-github-action-3g6k)


👽
Overloading vs Overriding in Typescript
Tags: inheritance, overload, override, typescript
Published: 2022-05-13 17:17:22

The main difference between overloading and overriding is this: The former is concerned with the signature of a function, whereas the later is concerned with the behaviour of a method.

## Override

Override is something you do to change the _behaviour_ of a method in a _subclass_. When you override a method, it is expected that you intend to change the default behaviour of the method, that was inherited from the parent class. However, the method signature should remain the same in order not to violate [LSP](https://en.wikipedia.org/wiki/Liskov_substitution_principle).

## Overload

Overload is something you do to functions; Not to change their behaviour*, but rather to diversify their [signature](https://en.wikipedia.org/wiki/Type_signature). A function overload keeps the same name as the function, but it's free to introduce a different signature. You've probably seen an example of this if you come from a JavaScript background and seen [functions](https://lodash.com/docs/#reduce) which have parameters that can be one of two or more types:

```js
/**
* @param {string|string[]} The object to use
*/
function stringOrArray(strOrArr) {
  ...
}
```

It's difficult to tell that this is a function overload because JavaScript does not have a strong enough type system to disambiguate the overloads. However, with the _Jsdoc_ comment, we can sort of make out that this function has an overload.
With typescript we can make this overload an actual part of our function signature, instead of living in a comment.

ex.

```ts
function stringOrArray(str: string)
function stringOrArray(arr: string[])
function stringOrArray(strOrArr: string | string[]) {
  ...
}
```

## Conclusion

The implementation of the _overloaded_ function stays the same, but the signature is allowed to be different. In the case of _overriding_, the implementation can be different, but the signature has to be the same, in order not to violate the Liskov Substitution Principle.
Data structure everywhere
Tags: javascript, datascience, programming
Published: 2022-05-13 16:57:29

Everywhere we look and everything we use has in some degree a data structure implemented. If we look close enough to observe the intricates of the world arround us , soon will start picking up parttens on how everything arround us fits in just right.

In the world of quatum mechanics and science , our world itself is a marvel . From how just they seem to be enough room for everyone and a constant time to chip in the right seasons and moments. Most renowed scientist and physicist have called this a dimenssion . 

And now using real world examples to mirror how data structure is impelemented in the digital world.

Post to be continued…
Evento DIO The Map – 23/05 às 20h
Tags: eventos, treinamento, carreira, dio
Published: 2022-05-19 03:51:40

---
title: Evento DIO The Map – 23/05 às 20h
published: true
date: 2022-05-13 16:50:15 UTC
tags: Eventos,Treinamento,Carreira,DIO
canonical_url: 
---

The Map.\_ é um evento gratuito da Dio Global, a primeira comunidade focada em aceleração de carreira internacional para profissionais de tecnologia.

Prepare-se para estar 100% atento ao conteúdo no dia 23/05 às 20h, em um lugar calmo e tranquilo.  
Se curte anotar para memorizar melhor o conteúdo, deixe papel e caneta no jeito também!

<iframe src="https://www.youtube.com/embed/Wj8Yh1AutiE" frameborder="0" allowfullscreen="allowfullscreen"></iframe>

É tech. É pra dev. É conhecimento que faz acontecer. Uma plataforma colaborativa, de gente ajudando gente, construindo, vibrando juntos.  
Do Brasil para o mundo.

Site de cadastro: [https://vrlps.co/sbju77y/cp](https://vrlps.co/sbju77y/cp)

O post [Evento DIO The Map – 23/05 às 20h](https://guiadeti.com.br/evento-dio-the-map-23-05-as-20h/) apareceu primeiro em [Guia de TI](https://guiadeti.com.br).
How to automatically generate Class Validator models from your Prisma schema
Published: 2022-05-13 16:41:24

Here's what you need to do:

1- Install the generator 

- Using npm 

```bash
 npm install prisma-class-validator-generator
```

- Using yarn:

```bash
 yarn add prisma-class-validator-generator
```

2-  Add the generator to your Prisma schema

```prisma
generator class_validator {
  provider = "prisma-class-validator-generator"
}
```

3- Run `npx prisma generate` for your schema(or the example below)

```prisma
model User {
  id    Int     @id @default(autoincrement())
  email String  @unique
  name  String?
  posts Post[]
}

model Post {
  id        Int      @id @default(autoincrement())
  createdAt DateTime @default(now())
  updatedAt DateTime @updatedAt
  title     String
  content   String?
  published Boolean  @default(false)
  viewCount Int      @default(0)
  author    User?    @relation(fields: [authorId], references: [id])
  authorId  Int?
}
```

Now you will have all possible Class Validator models generated with their validations for you!

![Class Validator models](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/rchrkm37th438brotm8d.png)
How to set up Xcode
Tags: ios, tutorial
Published: 2022-05-13 16:34:36

Getting Xcode set up on your computer can be a pain with its large file size, confusing errors, and  specific procedures. In this tutorial, I will guide you along the easiest and fastest way to download/install Xcode and provide workarounds on some errors that you might potentially get. 

1️⃣ Download the version that you want from Apple’s [website](https://developer.apple.com/xcode/resources/) 

> 💡 Make sure you download with Safari and not Chrome

2️⃣ Move sure to cd first into the directory where the file is located, i.e. Documents or Applications. Then, use this command in your terminal to expand the file.

```
xip -x Xcode_13.xip
```

3️⃣ Next, you might get this message that looks like an error but it’s actually not. It’s actually just working on expanding and you want to give it 20-30 min. 

```
xip: signing certificate was "Software Update" (validation not attempted)
```

4️⃣ Finally, after the item has been expanded, you’ll get a message like this. 

```
xip: expanded items from "/Users/ivychen/Documents/Xcode_13.xip"
```

Simply move it to your Applications folder, then it should be good to go!

**Alternative Workarounds**

If the method above doesn’t work (probably because you don’t have at least 30-40 GB on your computer), then you can try it with an external hard drive. Download the file with Safari on to your computer, copy it to your hard drive + expand it there. Then, move the expanded item back to your Applications folder and it should work!

Also, if you don't want to use the terminal, then you can just double-click to expand but it will take much longer.
WakaTime VsCode Extension ... Amazing
Published: 2022-05-13 16:16:49


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


Came across **wakatime vs code extension** used for tracking your coding time. The extension gives you various data analysis based on various filters such date ranges and projects and other metrics.

This extension is just amazing, as it enables a dev be consious on how much time is spent various projects or languages, giving u a better grasp on how you are developing as a developer.

> I have been struck again and again by how important measurement is to improving the human condition.
_ Bill Gates_
JavaScript Array Methods : Concat()
Tags: javascript, array, webdev, beginners
Published: 2022-05-13 16:06:25

**The concat() method concatenates (joins) two or more arrays.It returns a new array, containing the joined arrays. It does not change the existing arrays.**

Example : 

```
const array1 = ['a', 'b', 'c'];
const array2 = ['d', 'e', 'f'];
const array3 = array1.concat(array2);

console.log(array3);
//Output: Array ["a", "b", "c", "d", "e", "f"]
```

![Concat](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ai60f9t4vlzo5gnx2knk.png)
A small Python Quiz
Tags: python, watercooler, discuss, quiz
Published: 2022-05-13 15:59:40

Can you guess what value the variable `a` has to take, so that this program prints `A is not equal A!`?


```python
if a != a:
    print("A is not equal A!")
```


{% embed https://twitter.com/bascodes/status/1525142574914080768 %}
Reliable hosting solution
Published: 2022-05-13 15:57:51

DedicatedHosting4u can help you reach new heights with your online business. If you're serious about your business, a dedicated hosting server is a terrific option. By offering servers, we might be able to assist with email marketing. Reliable dedicated hosting , [Reliable hosting solution](https://www.dedicatedhosting4u.com/) , [Dedicated hosting](https://www.dedicatedhosting4u.com/) , [dedicated server california](https://www.dedicatedhosting4u.com/)
How to Run a data scraping workload on AWS EKS and visualize using Grafana
Published: 2022-05-13 15:55:41

This post is my solution walkthrough for the bonus Acloud guru challenge from the Cloud resume book by Forrest Brazeal. The book can be found [Here](https://cloudresumechallenge.dev/book/). This challenge is a good learning path for deploying workloads on Kubernetes cluster and spinning up a Kubernetes cluster. This post will describe how I completed the challenge and my approach towards the challenge solution. My challenge solution provides a good learning experience for these technologies:

- Kubernetes and deploying to Kubernetes
- App Development (I used Python but in theory it can be anything)
- Data analysis and visualization using Prometheus and Grafana  

More details can be found here:  
https://amlanscloud.com/kubechallenge/
Pensioner's Portal
Tags: javascript, webdev, html, css
Published: 2022-05-13 15:41:27

I created my own version of the Indian Central Government- Pensioner's Portal Home page. I would really like to know your comments on it.[](https://abhinandhc.github.io/Pensioner-s-Portal/)
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/e6lwz2nxwvyve6ln3kgf.png)
What's the Difference Between a Parameter and an Argument?
Tags: beginners, programming, ruby, rails
Published: 2022-05-13 15:27:42


I have an embarrassing confession.

Until just recently, I was using *parameters* and *arguments* interchangeably when talking and pairing with other software developers on my team.

Parameters and arguments are not the same things, but they are similar.

Let's dig into the differences so you don't have to make the same embarrassing mistake as me.

---

## Parameters vs Arguments

A **parameter** is a variable defined in a function definition. It is the variable that the function expects you to pass when it is called. These parameters define the variables that we can use throughout the rest of the function as well.

An **argument** is the value that we pass to the function when we call it. Arguments determine the value of the parameter variables in our function.

They might still sound similar, so here's an example with code.

```ruby
def adder(x, y)
  x + y
end
```

The `adder` function takes 2 parameters `x` and `y`.

We can then call our `adder` function and pass it 2 arguments.

```ruby
>>> adder(2, 3)
5
```

Since we passed the arguments `2` and `3` the body of the function will run, substituting its parameters with the arguments we supplied.

---

## How Keyword Arguments Work

Many programming languages, including Ruby, allow us to name parameters with specific keywords.

This is useful for a number of reasons.

When we call a function and pass arguments, our function depends on the order of our arguments.

For example, if our function instead performed an operation like subtraction or division, the order of our arguments matters significantly.

For example, if we called the below function with the arguments `divider(0,1)` the result would be zero, but if we swap the order our function would raise an exception. (Can't divide by zero, unfortunately...)

```ruby
def divider(x, y)
  x / y.to_f
end
```

With keyword arguments, we can specify which parameter is which more clearly and when we call the function and pass arguments, the order no longer matters for our keyword arguments.

If we changed our method to something like this:

```ruby
def divider(numerator:, denominator:)
  numerator / denominator.to_f
end
```

Then to call this method we have to include our keywords:

```ruby
>>> divider(numerator: 0, denominator: 1)
0
```

We could also reverse the order without raising an exception since our parameters are named.

```ruby
>>> divider(denominator: 1, numerator: 0)
0
```

---

## Takeaways

I bet most of your team doesn't know the difference between parameters and arguments.

There's a subtle difference, but it's easy to understand once you see a few examples.

Parameters tell us what the function will take, while arguments are the values we pass to a function when we call it.

Parameters are like variable names, arguments tell us what their values are.

The order of your parameters and arguments matter. But you can use keyword arguments to make order unnecessary and to more clearly name your arguments when you call your function.
Fully Responsive UP Business Landing PageTemplate
Tags: javascript, webdev, opensource, nextjs
Published: 2022-05-13 15:25:43

Hey guys Check out I have just added A New Fully Responsive UP Business Landing Page Template to [DEV.UI](https://dev-ui.vercel.app/)
Check out this [UP Business Landing Page Template](https://dev-ui.vercel.app/templates/landingpage)
Twitter bots
Tags: tracery, javascript, twitterbots, twitter
Published: 2022-05-13 15:21:08

I recently attended to a Twitter bot workshop hosted by [Canek Zapata](https://twitter.com/canekzapata) called "Jardín de Bots".

I had experience with bots before, following tutorials by [Daniel Shiffman](https://shiffman.net/a2z/twitter-bots/) and another one with just images using Tumblr's queue and [IFTTT](http://ifttt.com/).

[OvvO bot](https://twitter.com/OvvO_bot) it's also a Yen/No bot, you just have to mention it.
[Ffffoundish_bot](https://twitter.com/Ffffoundish_bot) #ripFfffound

But this time it was a lot easier. We didn't have to apply for a Key on Twitter Devs or the use of the API and credentials.

We used [Tracery ](https://www.tracery.io/)and [Cheap bots done quick](https://cheapbotsdonequick.com/)

Tracery is a js library that let you combine group of strings in a controlled random way. You just have to fill with text the js object that is already arranged for you, so you just have to worry on the combination of those strings.

Then, when your bot's code is done, you go to cheapBotsDoneQuick to run it and post it. You can also set an automated posting and the use of images (hosted somewhere else). 

It's definitely a cool way to make bots, it gives you a lot of choices, and it's excellent for people that are not very comfortable yet with code.

Oh! my new bot combines lyrics of Rosalía and C. Tangana in a sentence. Follow it here :) 
[https://twitter.com/rosaliatangana](https://twitter.com/rosaliatangana)
Variable sequence - 2
Tags: solidity, gasoptimization, bestpractice
Published: 2022-05-13 15:18:37

---series: Gas Optimization techniques---

We previously saw in [Variable sequence organization](https://dev.to/rushanksavant/variable-sequence-organization-8k1), that fitting multiple variables in single slot saves gas on execution.

But there is an exception to this case. 
Lets just try to recall our previous observations, consider following contracts:

```solidity
contract varSequence2_1{
    uint var1;
    uint var2;
    uint var3;

    function updateVar(uint num) external {
        var1 = num;
        var2 = num;
        var3 = num;
    }

}

contract varSequence2_2{
    uint8 var1;
    uint8 var2;
    uint8 var3;

    function updateVar(uint8 num) external {
        var1 = num;
        var2 = num;
        var3 = num;
    }

}
```
Which contract will cost us more gas on `updateVar` function execution? If you guessed `varSequence2_1` then you are right. This is similar to what we saw in [Variable sequence organization](https://dev.to/rushanksavant/variable-sequence-organization-8k1).

Now, consider the following contracts:

```solidity
contract varSequence2_1{
    uint var1;
    uint var2;
    uint var3;

    function updateVar(uint num) external {
        var1 = num;
    }

}

contract varSequence2_2{
    uint8 var1;
    uint8 var2;
    uint8 var3;

    function updateVar(uint8 num) external {
        var1 = num;
    }

}
```
Which contract do you think will cost us more gas on `updateVar` function execution now? It will be **varSequence2_2**. But why so? 

## Conclusion
This is observed because the opcodes increase when you have to find a particular element and mask it out of a storage slot. And hence there is an increase in gas.
Hoisting and Temporal Dead Zone (TDZ)
Tags: javascript, webdev, beginners, programming
Published: 2022-05-13 15:11:38

## **What is Hoisting???**

In JavaScript Hoisting refers to the process whereby the interpreter appears to move the declaration of functions, variables or classes to the top of their scope, prior to execution of the code.

Let's try to learn this terminology with example
```javascript
debugger;
console.log(a);
abc();

var a = "Hello";

function abc () {
  console.log("Print Hello");
}
```

**Result**:
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/bu7xe3t7m3eyopjk9u5l.PNG) 

as per above image "dubugger;" is set on first line to see how thinks works.we are still on first line, but variable and function have gotten memmory allocation.
because, before executing first line interpretor goes through code and do memmory allocation for all functions and variables.

This is one of stage of creating execution context. Generally, There are two stages:

- Assigns memory to every variable, class or functions
- Starts executing code line by line. 

This first stage is called hoisting. Now using this concept we will understand another important topic which is Temporal Dead Zone. so,

## **What is Temporal Dead Zone???**

as per MDN defination, 
A temporal dead zone (TDZ) is the area of a block where a variable is inaccessible until the moment the computer completely initializes it with a value.

as per defination we get variable type should be block scoped like "let" or "const" ( not var because it is functioned scope,we will see at the end.)
so let's understand by example:

```javascript
{
	console.log(data);
	let data = "hello";
}
```
**Result:**

```
"Uncaught ReferenceError: Cannot access 'data' before initialization"

```
it gives reference error for data, because as we seen in hoisting, it trys to create execution scope and assigns memory for every variable, class or function.but, let is not global scoped, so it is not accessible.
![see output for TDZ let](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/syj50aro34wb88w3jmgv.png)
 

Now, change sequence of code:
```javascript
{
	let data = "hello";
        console.log(data);
}
```
so, error is gone and it prints "hello".

for const, it works same way but const varible needs to initialize with some value as per its rule.

Now let's see for var, var is special keyword compare to earlier two. because it is global scoped, we can access it before declaration as it is added to global scope compare to let which is added to block scope.

![var and let](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2f63yfpjasd5zylvm1dl.png)