teleren/devto huggingface dataset:
Day 10 - Arrays
Tags: 100daysofcode, solidity, web3, blockchain
Published: 2022-06-07 13:32:00

{% embed https://github.com/Envoy-VC/30-Days-of-Solidity noreadme %}

This is Day `10` of `30` in Solidity Series
Today I Learned About Arrays in Solidity.

Arrays are data structures that store the fixed collection of elements of the same data types in which each and every element has a specific location called index. Instead of creating numerous individual variables of the same type, we just declare one array of the required size and store the elements in the array and can be accessed using the index. In Solidity, an array can be of fixed size or dynamic size. Arrays have a continuous memory location, where the lowest index corresponds to the first element while the highest represents the last element.

## Creating an Array

To declare an array in Solidity, the data type of the elements and the number of elements should be specified. The size of the array must be a positive integer and data type should be a valid Solidity type

**Syntax** -

```solidity
<data type>[<size optional>] <name> = <initialization>
```

---

## Fixed-size Arrays

The size of the array should be predefined. The total number of elements should not exceed the size of the array. If the size of the array is not specified then the array of enough size is created which is enough to hold the initialization.

Example -

```solidity
// SPDX-License-Identifier: MIT

pragma solidity ^0.8.7;

contract MyContract {
    // Declaring Array
    uint256[6] fixedArray;

    // Defining function to assign value to fixed Array

    function assignValueToFixedArray() public returns (uint256[6] memory) {
        fixedArray = [10, 20, 30, 40, 50, 60];
        return (fixedArray);
    }
}
```

Output -

```solidity
"0": "uint256[6]: 10,20,30,40,50,60"
```

---

## Dynamic Arrays

The size of the array is not predefined when it is declared. As the elements are added the size of array changes and at the runtime, the size of the array will be determined.

Example -

```solidity
// SPDX-License-Identifier: MIT

pragma solidity ^0.8.7;

contract MyContract {
    // Declaring Array
    uint256[] dynamicArray;

    // Defining function to assign value to dynamic Array
    function assignValueToDynamicArray() public returns (uint256[] memory) {
        dynamicArray = [1, 5, 3, 7, 9, 1, 2, 6];
        return (dynamicArray);
    }
}
```

Output -

```solidity
"0": "uint256[]: 1,5,3,7,9,1,2,6"
```

---
Array Nesting
Tags: leetcode, dsa, theabbie
Published: 2022-06-07 13:30:42

You are given an integer array `nums` of length `n` where `nums` is a permutation of the numbers in the range `[0, n - 1]`.

You should build a set `s[k] = {nums[k], nums[nums[k]], nums[nums[nums[k]]], ... }` subjected to the following rule:

*   The first element in `s[k]` starts with the selection of the element `nums[k]` of `index = k`.
*   The next element in `s[k]` should be `nums[nums[k]]`, and then `nums[nums[nums[k]]]`, and so on.
*   We stop adding right before a duplicate element occurs in `s[k]`.

Return _the longest length of a set_ `s[k]`.

**Example 1:**

**Input:** nums = \[5,4,0,3,1,6,2\]
**Output:** 4
**Explanation:** 
nums\[0\] = 5, nums\[1\] = 4, nums\[2\] = 0, nums\[3\] = 3, nums\[4\] = 1, nums\[5\] = 6, nums\[6\] = 2.
One of the longest sets s\[k\]:
s\[0\] = {nums\[0\], nums\[5\], nums\[6\], nums\[2\]} = {5, 6, 2, 0}

**Example 2:**

**Input:** nums = \[0,1,2\]
**Output:** 1

**Constraints:**

*   `1 <= nums.length <= 105`
*   `0 <= nums[i] < nums.length`
*   All the values of `nums` are **unique**.

**SOLUTION:**

    class Solution:
        def DFS(self, nums, i, visited):
            visited.add(i)
            if nums[i] not in visited:
                return self.DFS(nums, nums[i], visited)
            else:
                return (i, visited)
        
        def arrayNesting(self, nums: List[int]) -> int:
            n = len(nums)
            mlen = 0
            visited = set()
            for i in range(n):
                if i not in visited:
                    start, l = self.DFS(nums, i, set())
                    end, l = self.DFS(nums, start, set())
                    visited.update(l)
                    mlen = max(mlen, len(l))
            return mlen
Get first date and last date of months with date-fns
Tags: javascript
Published: 2022-06-07 13:22:32

Do not wasted time with native Date, use `date-fns` and go home!

```js
import { format, lastDayOfMonth } from 'date-fns'

const today = new Date()
const firstDateOfMonth = format(today, 'yyyy-MM-01')
const lastDateOfMonth = format(lastDayOfMonth(today), 'yyyy-MM-dd')
```

Now go home!
How to Convert REM to PX?
Tags: rem, px, font, css
Published: 2022-06-07 13:18:23

There are many Font Size units to configure sizes of the fonts in CSS such as:

1. **em** Relative to the font-size of the element (2em means 2 times the size of the current font)	
2. **ex** Relative to the x-height of the current font (rarely used)	
3. **ch** Relative to the width of the "0" (zero)	
4. **rem** Relative to font-size of the root element	
5. **vw** Relative to 1% of the width of the viewport*	
6. **vh** Relative to 1% of the height of the viewport*	
7. **vmin** Relative to 1% of viewport's* smaller dimension	
8. **vmax** Relative to 1% of viewport's* larger dimension	
9. **%** Relative to the parent element

So It's better to use a tool which can helps to easily converts REM to Pixels:

[REM to PX Converter] (https://codebeautify.org/rem-to-px-converter)
![REM to PX](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3t7omi6s5tjcea1dl388.png
)
I found this tools to make UI designer's life easy.

Here are more CSS Unit Converter Tools Online can be found: [https://codebeautify.org/css-unit-converter-tools](https://codebeautify.org/css-unit-converter-tools)
![CSS Unit Converter](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/e0nspjxkrtr6t0y47wny.png)
Number Complement
Tags: leetcode, dsa, theabbie
Published: 2022-06-07 13:00:51

The **complement** of an integer is the integer you get when you flip all the `0`'s to `1`'s and all the `1`'s to `0`'s in its binary representation.

*   For example, The integer `5` is `"101"` in binary and its **complement** is `"010"` which is the integer `2`.

Given an integer `num`, return _its complement_.

**Example 1:**

**Input:** num = 5
**Output:** 2
**Explanation:** The binary representation of 5 is 101 (no leading zero bits), and its complement is 010. So you need to output 2.

**Example 2:**

**Input:** num = 1
**Output:** 0
**Explanation:** The binary representation of 1 is 1 (no leading zero bits), and its complement is 0. So you need to output 0.

**Constraints:**

*   `1 <= num < 231`

**Note:** This question is the same as 1009: [https://leetcode.com/problems/complement-of-base-10-integer/](https://leetcode.com/problems/complement-of-base-10-integer/)

**SOLUTION:**

    class Solution:
        def findComplement(self, num: int) -> int:
            return int("".join([str(1 - int(c)) for c in "{:b}".format(num)]), 2)
In javascript make mapping json objects with specified keys
Published: 2022-06-07 12:56:45

#####You have an array of objects what you want to do is map through them and return specific key value pairs in a new array.

> ######The Functions Code SS

![The Functions Code SS](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/q8hp79sz73lfa2o2w4ue.png)


######1. For example you have specific keys array
![For example you have specific keys array](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/z6vwt1xxlpcyyieh6tc9.png)

######2. The JSON Object you want to manipulate
![Json Objects](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/u14nvdfthw7jxndqlcrt.png)

######3. Result the mapped JSON Objects

![The Result](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/mr3jp00sovp5iwtoawvl.png)

```
const visibleColumnFields =  ['LicencePlate', 'car', 'CarAttributes', 'ReservationStatus', 'ReservationType', 'CustomerGroupName'];

// The original json objects
      let rows =  [{
        "LicencePlate": "ZPL 524",
        "car": "Opel Corsa",
        "CarAttributes": "Z",
        "ReservationStatus": "İptal Edildi",
        "ReservationType": "Yıllık İç Müşteri",
        "CustomerGroupName": "Dev Test Technology",
        "CompanyName": "İş Geliştirme Müdürlüğü",
        "Zimmet": "Petor Petor ",
        "LocationName": "Test Company Location",
        "EndDateTime": "28.04.2022 00:00",
        "RentDays": "1 Gün",
        "TotalPrice": "350.00",
        "CurrencyType": "Lira",
        "CurrencySymbol": "₺",
        "TotalPriceByCurrency": "350.00",
        "CurrencyRate": "1"
      }];

// Mapping over the objects
      let retwriteRow =   rows.map( function (e) {
        return Object.keys(e).filter((key) => visibleColumnFields.includes(key)).reduce( (cur, key) => {
          return Object.assign(cur, {[key] : e[key]})
        },{})
      });
```
Jewels and Stones
Tags: leetcode, dsa, theabbie
Published: 2022-06-07 12:30:43

You're given strings `jewels` representing the types of stones that are jewels, and `stones` representing the stones you have. Each character in `stones` is a type of stone you have. You want to know how many of the stones you have are also jewels.

Letters are case sensitive, so `"a"` is considered a different type of stone from `"A"`.

**Example 1:**

**Input:** jewels = "aA", stones = "aAAbbbb"
**Output:** 3

**Example 2:**

**Input:** jewels = "z", stones = "ZZ"
**Output:** 0

**Constraints:**

*   `1 <= jewels.length, stones.length <= 50`
*   `jewels` and `stones` consist of only English letters.
*   All the characters of `jewels` are **unique**.

**SOLUTION:**

    class Solution:
        def numJewelsInStones(self, jewels: str, stones: str) -> int:
            jewels = set(jewels)
            return len([c for c in stones if c in jewels])
Dall-E-2 & Imagen; A premonition for Designers and Illustrators
Tags: dalle2, imagen, design, ai
Published: 2022-06-07 12:27:50

There's no doubt that the future will be dominated by technology, principally by the advancements in Artificial Intelligence. The automated applications of AI have long been perceived as a threat by "Luddite", whereas a technophile enjoys such advancements and adapts to the new changes.

The recent news by OpenAi has stunned the aspiring artists, Illustrators, and the industry in general by announcing a very advanced text-to-image model called **[Dall-E-2](https://openai.com/dall-e-2/)**. Google, following up with Dall-E, also announced a similar application, which is called [Imagen](https://imagen.research.google). Both of these models are capable of producing realistic and uncanny images just by inputting a single command or sentence.

As advanced and realistic as the model is, it is still not possible to fine-tune the generated images accordingly to your requirements. The model is still in its early phases and there's a lot of work and research to be done. Given the advantage, designers or illustrators can use this model to generate an image, use it as an inspiration and then prepare the final product. 

It is also vital here to understand and upskill yourself as the time passes because the future is evidently for those who work alongside the technological advancements.

The attached pictures are some of the sample images generated by Google's Imagen model.

![Google's Imagen Samples](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/08uvfk38m15nb69gwfdu.jpg)


![Imagen Sample 2](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/49jkzz9yl2rh3elcgnag.jpg)
How to calculate the distance between two points, using math
Tags: javascript, maps, haversine
Published: 2022-06-07 12:16:51

Roughly a year ago, I wrote a post about [how to sort a list of physical locations by how close they are to you](https://blog.jws.app/2021/how-to-sort-a-list-of-locations-by-how-close-they-are-to-you/).  At the time, I was working on [an app that needed to know how close you were to each of Wisconsin's State Parks](https://blog.jws.app/tag/state-parks-app/).  On July 26, I am giving [an online presentation at That Conference on the topic of "Locating your user in meatspace"](https://that.us/activities/4CYljqsNWFJrs70dvEp6) and ahead of that, I wanted to drill down on the topic of how to calculate the distance between two point while only using math to do so.

So, how do you do that?  You use the Haversine formula.  Now, I am not a great mathematician according to [Simon Kettle](https://community.esri.com/t5/coordinate-reference-systems-blog/distance-on-a-sphere-the-haversine-formula/ba-p/902128):

> The haversine formula is a very accurate way of computing distances between two points on the surface of a sphere using the latitude and longitude of the two points. The haversine formula is a re-formulation of the spherical law of cosines, but the formulation in terms of haversines is more useful for small angles and distances.

According to [Kettle](https://community.esri.com/t5/coordinate-reference-systems-blog/distance-on-a-sphere-the-haversine-formula/ba-p/902128), the word "Haversine" comes from the function: haversine(θ) = sin²(θ/2).  [The formula can be used in javascript code like so](https://codepen.io/steinbring/pen/jOZpjKQ):

{% codepen https://codepen.io/steinbring/pen/jOZpjKQ %}

The output is in kilometers but since 1 kilometer is equal to 0.621371 miles, it should be reasonably easy to [convert the output to miles](https://codepen.io/steinbring/pen/XWZBvrm).

{% codepen https://codepen.io/steinbring/pen/XWZBvrm %}

So, what do you think?  How are you going to use the haversine formula in your projects?  Feel free to let me know in the comments, below.
Lessons learnt from the 8 week sql challenge: string_agg
Tags: sql, bigquery, 8weeksqlchallenge, sqltips
Published: 2022-06-07 12:16:25

👩🏼‍💻 using [Google BigQuery SQL syntax](https://cloud.google.com/bigquery/docs/reference/standard-sql/query-syntax)
📁 check the [Github repository](https://github.com/meerens/8-week-sqlchallenge) for context

A neat function I discovered during the challenge is [`STRING_AGG`](https://cloud.google.com/bigquery/docs/reference/standard-sql/functions-and-operators#string_agg) which strings together (concatenates) non null string values in a single field. 

This was by no means a requirement but instead of the output below, I wanted to return a table that shows the 3 customer id's and for each customer id strings together the different product names in a single cell.

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

So what's the syntax for creating the output below?

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

Turns out it's a lot simpler than I thought.

Instead of this ...

```sql
SELECT
customer_id,
product_name
FROM q5_items_sold_ranked
WHERE count_rank = 1
ORDER BY customer_id ASC;
```
... do this.

```sql
SELECT
customer_id,
STRING_AGG(product_name, ', ') AS most_popular_items
FROM q5_items_sold_ranked
WHERE count_rank = 1
GROUP BY customer_id
ORDER BY customer_id ASC;
```

Hope you find this useful, let me know in the comments if any questions.
using google-api-javascript-client (gapi) with no authentication [code example]
Tags: gapi, googleapi, googlecalendarapi
Published: 2022-06-07 12:13:50

Here is an example of using [Google APIs Client Library for browser JavaScript, aka gapi](https://github.com/google/google-api-javascript-client) with **no authentification**. The Google Api we are calling here is [Calendar API](https://developers.google.com/calendar/api).

There are some caveats:

* We will be calling a public calendar.
* It's a read-only request.
* You do need an api key from [google cloud console](https://console.cloud.google.com/).

First load api.js: `<script src="https://apis.google.com/js/api.js"></script>`. Then add the following script:

```javascript
  // fill in your api key
  const apiKey = "******";
  // select a calendar by id
  const calendarId = "******";

  function start() {
    // Initializes the client with the API key and the Calendar API.
    gapi.client.init({
      'apiKey': apiKey,
      // load the correct library (calendar in this case)
      'discoveryDocs': ['https://www.googleapis.com/discovery/v1/apis/calendar/v3/rest'],
      'scopes': 'https://www.googleapis.com/auth/calendar.readonly'
    }).then(function() {
      return gapi.client.calendar.events.list({
        'calendarId': calendarId,
        'maxResults' : 5,
      });
    }).then(function(response) {
      console.log('response',response.result.items);
    }, function(reason) {
      console.log('Error: ', reason);
    });
  };
  // Loads the JavaScript client library and invokes `start` afterwards.
  gapi.load('client', start);
```

This example is based on a sample in the google-api-javascript-client: <https://github.com/google/google-api-javascript-client/blob/master/docs/samples.md#loading-an-api-and-making-a-request>.
Turn your tweets into beautiful and editable posts with Tweeta.io
Published: 2022-06-07 12:09:09


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

**Steps to create image from the tweet**
1.Choose your favorite tweet and copy the link
2.Open the Tweeta.io.
3.Paste the link pf the tweet in paste Twitter post link section.
4.Customize look using Colors, Text size, Radius, Theme and many more sections.
5.Download the image using Download button.
6.Share the image into your favorite social media.

You can also download the images in the popular social media post and story sizes also.
 
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/q8qc7goj8sn9m79nr65m.png)
Static website with React app in subdirectory
Tags: react
Published: 2022-06-07 12:04:09

I have a static website on www.mydomain.com with two pages:
home: www.mydomain.com
about: www.mydomain.com/about

How can I add a React app to www.mydomain.com/app?
It should use routing, so I e.g. can go to www.mydomain.com/app/profile

I host it on Cloudflare Pages.
Count Items Matching a Rule
Tags: leetcode, dsa, theabbie
Published: 2022-06-07 12:00:47

You are given an array `items`, where each `items[i] = [typei, colori, namei]` describes the type, color, and name of the `ith` item. You are also given a rule represented by two strings, `ruleKey` and `ruleValue`.

The `ith` item is said to match the rule if **one** of the following is true:

*   `ruleKey == "type"` and `ruleValue == typei`.
*   `ruleKey == "color"` and `ruleValue == colori`.
*   `ruleKey == "name"` and `ruleValue == namei`.

Return _the number of items that match the given rule_.

**Example 1:**

**Input:** items = \[\["phone","blue","pixel"\],\["computer","silver","lenovo"\],\["phone","gold","iphone"\]\], ruleKey = "color", ruleValue = "silver"
**Output:** 1
**Explanation:** There is only one item matching the given rule, which is \["computer","silver","lenovo"\].

**Example 2:**

**Input:** items = \[\["phone","blue","pixel"\],\["computer","silver","phone"\],\["phone","gold","iphone"\]\], ruleKey = "type", ruleValue = "phone"
**Output:** 2
**Explanation:** There are only two items matching the given rule, which are \["phone","blue","pixel"\] and \["phone","gold","iphone"\]. Note that the item \["computer","silver","phone"\] does not match.

**Constraints:**

*   `1 <= items.length <= 104`
*   `1 <= typei.length, colori.length, namei.length, ruleValue.length <= 10`
*   `ruleKey` is equal to either `"type"`, `"color"`, or `"name"`.
*   All strings consist only of lowercase letters.

**SOLUTION:**

    class Solution:
        def countMatches(self, items: List[List[str]], ruleKey: str, ruleValue: str) -> int:
            index = {
                "type": 0,
                "color": 1,
                "name": 2
            }
            ctr = 0
            for item in items:
                if ruleValue == item[index[ruleKey]]:
                    ctr += 1
            return ctr
Building a Security-First Culture As A Developer or Team
Tags: discuss, devops, security
Published: 2022-06-07 11:48:19

Developing a security-first culture is crucial in today's digital age where cyber attacks and data breaches have become increasingly prevalent. As a developer or team, it may seem daunting to develop a security-first culture, but it's not that complex when put into practice. In this article, we'll list some activities that can help build a security-first culture.

## Managing Secret Credentials

Using a .env file to hide secrets during development is a common practice, but it doesn't scale and doesn't improve codebase security. Using an enhanced tool like Onboardbase, a secure online vault for developers and teams to store and share app secrets, is a better and more improved option. Managing secret credentials the right way can help developers and teams reduce the rate of vulnerability in their codebase or project and create a good security culture.

## Bug Hunt Session

Organizing a bug hunt session in a company can help the team discover issues fast and fix them before pushing to the general public. There are tools available to test codebase for bugs, leaked secret keys, and more. Gitguardian, for example, can scan codebase for leaked secret keys and reduce the stress of checking every single line of code in the codebase. Having regular bug hunt sessions and utilizing available tools can help foster a security-first culture.

## Automate Security Initiatives

Security automation is a machine-based execution of security actions that can detect, investigate, and remediate cyber threats with or without human intervention. Security automation can identify incoming threats, triage and prioritize alerts as they emerge, and perform automated incident response. Automating security initiatives can help create a more secure and efficient work environment.

## Security Awareness Training

Taking security courses and implementing security awareness training can help enlighten development teams and give them more insights on how to prioritize security when building products for themselves or the company. It is essential to put in place time and budget for taking security courses to ensure that developers are equipped with the necessary knowledge to develop a security-first culture.

In conclusion, building a security-first culture is vital to protect against cyber threats and data breaches. By following the activities listed above, developers and teams can develop a security-first culture and make it an integral part of their work environment.