teleren/devto huggingface dataset:
The JavaScript Array.at() method
Tags: javascript, array
Published: 2022-05-12 13:00:38

Often we want to return a single item from an array. There are a few methods of doing this including the `at(index)` method which returns the item at a given index. It takes both positive and negative values where negatives values count back from the last item in the array.

Let's take a look and compare this method with the methods we might be more familiar with.

## Getting the index of the first item in an array

Using square bracket notation is also still perfectly fine and to get the first item in an array you can do:

### Using the array length method

You an use the square brackets passing in the index of 0 to get the first item in the array.

```js
array[0]
```

### Using the at method

You can also use the `at()` method passing in the index of 0 to get the first item in the array.

```js
array.at(0)
```

## Getting the index of the last item in an array

### Using the array length method

The real difference is when you want to get the last number in the array. It is very common to use the length property of an array and subtract 1, to get the last item in the array. We use a -1 because arrays start at 0 and not 1.

```js
array[array.length - 1]
```

### Using the slice method

Or you could use the slice method where you can slice from one index to another to get the value you want. However this method will return an array with the which might not necessarily be what you are want.

```js
array.slice(-1)
```

### Using the at method

Although there is nothing wrong with using the method above we can use a shorter syntax using the at() method and passing in the value of -1 without having to use the `array.length`.

```js
array.at(-1)
```

Again both methods are fine so use the one you prefer.

## Example

To see a real example in use, let's create an array of food and then find the index of the first and last item in the array.

```js
const food = ['pizza', 'burgers', 'sushi', 'steak', 'salad']

console.log(food[0]) // pizza

console.log(food.at(0)) // pizza

console.log(food[food.length - 1]) // salad

console.log(food.slice(-1)) // [salad]

console.log(food.at(-1)) // salad
```

Paste it in your console and see for yourself or play around with the indexes to get different results Or checkout the [codepen](https://codepen.io/debs-obrien/pen/vYdXxdy) I created.

Again all methods work perfectly fine so choose the one you prefer. The `at()` method seems quite nice and easy to remember too and it has full browser support too. (Unless you need Internet Explorer or Opera for Android).

## Learn More

To read more about it check out the MDn docs for [Array.prototype.at()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/at)

- Check out my post on the [array filter method](/blog/js-array-filter-method)
- Check out my post on the [array map method](/blog/js-array-map-method)
Token injection in Angular
Tags: javascript, angular, webdev, beginners
Published: 2022-05-12 12:44:14

A friend of mine recently had a job interview with a top UK firm , looking for Angular developer .I could remember him calling to tell me, he didn't do so well in the interview .So I ask him to tell me the questions that was asked.This particular question got my  attention.

**What is Token injection in Angular **

The Injection Token allows creating token that allows the injection of values that don't have a runtime representation. 

Now the above is too complex for me to understand so let break it down 

Imagine you working on a project with has multiple base-url

1. https://dog.api/
2. http://cat.api/

This baseUrl above contains series of endpoint nested under them like 

1. readOneBread
2. readAllBread

The best way to load this individual api without conflict is by using the angular token injection.

To create a token injection use the following 

- create a file called `app.config.ts `

```
import {InjectionToken} from "@angular/core"

export const CAT_URL = new InjectionToken<string>(_desc:'cat api')
export const DOG_URL = new InjectionToken<string>(_desc:'dog api')

```
- Register the token in the provider of your module

```
provider:[{
provide:CAT_URL,
useValue:'http://cat.api/'

},
{
provide:DOG_URL,
useValue:'http://dog.api/'

},


]
```
- Finally to access this in our services 

```
Constructor(private client:HttpClient,@inject(CAT_URL)private cat_url:string ){
}


getAllBread(){

this.client.get(this.cat_url+'readAllBread')

}
```
Thanks for reading.
Trying TruffleRuby
Tags: ruby, truffleruby
Published: 2022-05-12 12:37:18

---
title: Trying TruffleRuby
published: true
description: ruby
tags: ruby,truffleruby
//cover_image: https://direct_url_to_image.jpg
---

I ran wbrk2.rb:

```Ruby
# encoding: UTF-8
require 'thailang4r/word_breaker'
word_breaker = ThaiLang::WordBreaker.new
line = 'แต่ผมเคยมีปัญหาตอนจ่ายตังหลายปีแล้วแต่ผมเคยมีปัญหาตอนจ่ายตังหลายปีแล้วแต่ผมเคยมีปัญหาตอนจ่ายตังหลายปีแล้วแต่ผมเคยมีปัญหาตอนจ่ายตังหลายปีแล้วแต่ผมเคยมีปัญหาตอนจ่ายตังหลายปีแล้วแต่ผมเคยมีปัญหาตอนจ่ายตังหลายปีแล้วแต่ผมเคยมีปัญหาตอนจ่ายตังหลายปีแล้วแต่ผมเคยมีปัญหาตอนจ่ายตังหลายปีแล้วแต่ผมเคยมีปัญหาตอนจ่ายตังหลายปีแล้ว'

t1 = Time.now
for i in 1..10000
  puts word_breaker.break_into_words(line).join("|")
end
t2 = Time.now
puts t2-t1
```

in cRuby, jRUby, TruffleRuby by this script:

```Shell
#!/bin/bash
IMPLS=("cruby1" "jruby1" "truffle1")
for i in $(seq 1 10); do
    for j in ${IMPLS[*]}; do
	echo $i,$j,$(docker run --rm -it -v $(pwd):/work -w /work $j ruby wbrk2.rb | tail -n1)
    done
done
```

Dockerfile.cruby:

```Dockerfile
FROM ruby:3.1
RUN gem install thailang4r
```

Dockerfile.jruby:

```Dockerfile
FROM jruby
RUN gem install thailang4r
```

Dockerfile.truffle:

```Dockerfile
FROM ghcr.io/graalvm/truffleruby:22
RUN gem install thailang4r
```


|      | cRuby       | jRuby      | TruffleRuby |
|------|-------------|------------|-------------|
| 1    | 16.42368491 | 54.169815  | 11.385601   |
| 2    | 16.58381034 | 51.668375  | 11.99536    |
| 3    | 16.47655229 | 53.584401  | 12.088978   |
| 4    | 17.52281777 | 54.222869  | 10.893925   |
| 5    | 16.92775603 | 54.912019  | 12.24505    |
| 6    | 16.89063941 | 52.43011   | 11.413859   |
| 7    | 17.12419062 | 57.041267  | 11.395317   |
| 8    | 17.51911099 | 51.571193  | 11.551416   |
| 9    | 16.97416603 | 51.805853  | 11.578309   |
| 10   | 16.79307381 | 51.006189  | 12.517783   |
| mean | 16.92358022 | 53.2412091 | 11.7065598  |
| Speed| 1X          | 0.32X      | 1.45X       |


wbrk2 on TruffleRuby ran at 1.45X speed of cRuby. wbrk2 on jRuby ran at 0.32X speed of cRuby.
CubexSoft MBOX Converter For Mac OS
Tags: programming, discuss, database, performance
Published: 2022-05-12 11:50:18

I deliberate using the best software **CubexSoft [MBOX Converter For Mac](https://www.cubexsoft.com/mbox/)**. If you are unconvinced on “how to export MBOX files into Outlook PST file format.” It uses a very simple and easy graphical interface to deliver smooth conversion of MBOX emails into any other formats as well like PST, EML, MSG, RTF and HTML.  Both versions are also supported by this application including all Windows Operating System editions or Mac OS. The user who has purchased [MBOX to PST](https://www.cubexsoft.com/mbox/pst.html) Converter is enabled to a free demo that allows them to move up to 25 emails from MBOX to PST for free of cost.

Visit More Info: https://www.youtube.com/watch?v=NV2OuXbIg_M&t=21s
Random Meme Generator with Appwrite DEV.to Hackathon
Tags: appwritehack, javascript, programming, react
Published: 2022-05-12 11:50:04


### Overview of My Submission
I have built an app which registers a user using appwrite users and logs in. Then there is a button "Fetch new memes". On clicking this, each time a new meme comes on the screen.
I have built this using ReactJS and user service of appwrite.
Here is the link. Please go through the README.
[](https://github.com/adityaaryam/DEV.to-Hackathon)
I have used the MIT LICENSE


### Submission Category: 

**Web2 Wizards**

The user generated content that I am using are the memes. It uses the api `https://meme-api.herokuapp.com/gimme`.

### Link to Code

`https://github.com/adityaaryam/DEV.to-Hackathon` 


### Additional Resources / Info

This is the login page
![Login Page](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/nyjkrmwx8hcsha5pbpf5.png)

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


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

Fetch new meme:
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/yl3y9c32nun15w44iz3t.png)
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1k8y4ivq2tnx9nbwasfj.png)


Appwrite console:

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

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/m4gsxtomfegl6o7usuib.png)
Digital Marketing Services by Reputed Agency for Companies
Tags: digitalmarketingservices, seoservices
Published: 2022-05-12 11:47:39

We offer a full suite of [digital marketing services](https://www.pixel-studios.com/digital-marketing/digital-marketing-agency-in-chennai). Our creative team is able to create everything from web design and development to SEM campaigns. Contact Us!

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5x2ggoo9lbiyp9oqipan.png)
You Don’t Need React to Create a Reusable Button!
Tags: react, programming, javascript, webdev
Published: 2022-05-12 11:45:02

![](https://miro.medium.com/max/1400/0*3uerYL2xll2h33PS)

Use Web Components instead!

{% medium https://medium.com/@mariusbongarts11/you-dont-need-react-to-create-a-reusable-button-2108cfeac38c %}
Radix Sort
Tags: javascript, programming, algorithms
Published: 2022-05-12 11:43:48

What do we understand about Radix Sort ?
 - Stable Sorting Algorithm
 - Mutates original Array
 - Is NOT a comparison sort
 - sorts by exploiting the way numerics are interpreted
 - mostly implemented if Array contains only positive numbers
    - there can only exist 10 different positive integers (0 - 9)
 - each loop results in `Array<Array<Int>>`
    - similar concept to **Bucket Sort**
 - uses 2 nested for-loops
    - First, create 2 helper functions
        - getMaxNumOfDigits()
        - getDigitByPos()
    - Next, in main function
        - Outer loop ends at MaxNumOfDigits
            - init new bucket of 10 on each loop (Array of size 10)
        - Inner loop loops thru total number of elements in the Array
            - bucket position would have an Array inside pushed with values of that digit by position
        - flatten the Array of Array and reassign back to original Array
 - Time and Space Complexities are a complete opposite of Counting Sort
 - Time complexity 
    - Best      is O(nk)
    - Average   is O(nk)
    - Worst     is O(nk)
 - Space complexity
    - O(n+k)

```js
function getMaxNumOfDigits(arr) {
    const max = Math.max(...arr);
    if (max === 0) return 1;
    // suggest to just memorise this if can't think of the math on the spot
    // else just use stringify and get length of string
    return Math.floor(Math.log10(max)) + 1;
}
function getDigitByPos(num, pos) {
    if (num === 0) return 0;
    // e.g.
    // num = 1234, pos = 2
    // floor(1234 / 10^2) % 10
    // floor(1234 / 100) % 10
    // = 12 % 10
    // = 2
    return Math.floor(num / Math.pow(10, pos)) % 10;
}

function RadixSort(arr) {
    const arrLength = arr.length;
    const maxNumOfDigits = getMaxNumOfDigits(arr);

    for(let i = 0; i < maxNumOfDigits; i++) {
        const digitsBucket = new Array(10);
        
        for (let j = 0; j < arrLength; j++) {
            const digit = getDigitByPos(arr[j], i);
            if (!digitsBucket[digit]) {
                digitsBucket[digit] = [];
            }
            digitsBucket[digit].push(arr[j]);
        }

        arr = digitsBucket.flat();
    }

    return arr;
}
```
Problem: turning an image into a canvas ignores the filters
Tags: html, javascript, css, help
Published: 2022-05-12 11:32:42

Hi, in [this code](https://drive.google.com/file/d/1p2v9-Oz3QjMsWbc-mtFV-DC0MJWH49oH/view?usp=sharing) I put a button with a function that turn a div containing an image into a canvas, and I setted filters to this image but they are ignored, the canvas shows the original image without them. Can you help me?
Blockchain Game Development To Create P2E Games 2022!
Tags: blockchain, gamedev, nft, unity3d
Published: 2022-05-12 11:29:32

For all those who are planning to create a blockchain powered gaming platform, you have landed in the right place! Check out the Dappsfirm and get solutions to all your questions about blockchain game development.
 
Dappsfirm is a leading **[blockchain game development company](https://www.dappsfirm.com/blockchain-game-development)** that helps to create play-to-earn gaming platforms on various blockchain networks. We are global leaders in delivering blockchain powered gaming solutions and blockchain game dapp development services with a strong portfolio of clients who are market leaders in this gaming era. We have a dedicated and skilled team of high-quality experts who constantly work with diverse industrial players in different gaming genres.

We deal with all types of blockchain game development queries as well as blockchain game development consulting requirements. Some of the primary factors that make Dappsfirm a better choice for you are-

- Result Driven Gaming Approach to The Goals
- Team of Expert 3D/2D gaming Developers & blockchain professionals
- Top Tier Techstack & Gaming Tool Expertise
- Offers Unity 3D/Unreal, Flutter, Hybrid and other types of Blockchain game dapp development
- Uses Agile Methodologies to save your time and money with compromising on functionality
 
**Blockchain Game Development Services**
 
 
Get Enterprise-Ready Blockchain Game Development Services For The Most Popular Gaming Models:

- [Metaverse Game Development](https://www.dappsfirm.com/metaverse-game-development)
- Metaverse NFT Game Development
- [NFT Game Development](https://www.dappsfirm.com/nft-game-development)
- NFT Game Clone Development
- DeFi Game Development
- Play To Earn Game Development
- Role Play Game Development
- Blockchain Game Clone Development
- Blockchain Sports Betting Game Development
- And More

**Blockchain Game Clone Script Development**
 
Blockchain Game Clone script is a pre-built game clone script that is usually inspired by popular blockchain games like Crypto kitties, Betfury, Axie infinity, Zedrun and more. It covers all the design, features, and models of the existing gaming platforms. Currently, the blockchain game clone script concept is getting more prominent in the gaming space. Because one can create and launch a superfine and innovative blockchain gaming platform instantly at an affordable cost which becomes the primary reason to choose blockchain game clone script.

**Market-Leading Blockchain Game Clone Script**

- Cryptokitties Clone
- Betfury Clone
- Upland Clone
- Blankos Block Party Clone
- Mobox Clone
- Lightnite Clone
- Cryptopop Clone
- PolkaPets Clone
- Thetan Arena Clone
- Blockchain Cuties Clone
- CryptoBots Clone
- League of Kingdoms Clone
- And More

If you are looking for the top blockchain game development company, or ready-made blockchain game clone script then your search ends here!
 
**Talk to our experts**
 
Call/Whatsapp - +919597355524
Telegram - https://t.me/Dappsfirm
Skype - live:.cid.31364a310d2d094f
Email - sales@dappsfirm.com
876. Middle of the Linked List
Published: 2022-05-12 11:05:29

Given the head of a singly linked list, return the middle node of the linked list.

If there are two middle nodes, return the second middle node.

 

**Example 1:**


Input: head = [1,2,3,4,5]
Output: [3,4,5]
Explanation: The middle node of the list is node 3.
**Example 2:**


Input: head = [1,2,3,4,5,6]
Output: [4,5,6]
Explanation: Since the list has two middle nodes with values 3 and 4, we return the second one.
 

**Constraints:**

The number of nodes in the list is in the range [1, 100].
1 <= Node.val <= 100

Solution : 

```javascript
var middleNode = function(head) {
  // create array A to push elements in 
    let A = [head];
  // Remember that Linked List is Like SANDWISH the head contain the next node and the next node contain the next node till the end 
  // The end is where no next | node.next = null
  
  
  // loop though the list till the end 
    while (A[A.length - 1].next != null)
      // push every element 
        A.push(A[A.length - 1].next);
  // Return the middle one 
    return A[Math.trunc(A.length / 2)];
};
```
Advanced ORM in Django
Tags: python, django, video
Published: 2022-05-12 10:32:14


## Slides

You can find the slides here:

[https://bas.surf/pyconde22-slides](https://bas.surf/pyconde22-slides)

## Recording

Also there is a recording of my talk on PyConDE's YouTube channel:

{% embed https://youtu.be/F1vaEBDxAig %}
Hoisting and Temporal Dead Zone (TDZ) in JavaScript?
Tags: javascript, webdev, beginners, programming
Published: 2022-05-12 09:30:16

Hoisting and Temporal dead zone can be difficult to understand in the first try. I will try to make you understand in one of the simplest ways possible please be with me till the end.


First to understand hoisting we will have to understand how does a JS program runs.

A JS program runs in 2 phases:

1. Memory allocation phase
2. Code execution phase

**<u>Memory Allocation Phase</u>**

In a JS program all the variables are allocated only memory not their values and all the functions are allocated with their body.

**<u>Code Execution Phase</u>**

After memory allocation code execution is done. Code execution is done line by line


**<u>Hoisting</u>**

Meaning of hoisting in English dictionary: raise or haul up.

Hoisting in JS is also done in same way. When a variable or function is called before it is defined, this is known as hoisting.

Hoisting in case of let and const variables is different from hoisting with var variables

When a var variable is hoisted it gives `undefined` but when a let or const variable is hoisted it gives `ReferenceError` 

code Example:
In case of var

  `console.log(bestFood); // returns undefined because bestFood’s TDZ does not exist here
  var bestFood = "Vegetable Fried Rice"; // bestFood’s TDZ does not exist here
  console.log(bestFood);`


In case of let and const

`console.log(bestFood); // returns ReferenceError because bestFood’s TDZ 
let bestFood = "Vegetable Fried Rice";`


This happens because when memory allocation of var variable is done it allocates a placeholder "undefined" but in case of let and const no such thing happens


**<u>Temporal Dead Zone or TDZ</u>** occurs when a variable is not initialized and you attempt to access a variable before its complete initialization, then it gives a `ReferenceError`

TDZ ends when you initialize that variable


Functions can also be hoisted.

code example:

`catName("Tiger");
function catName(name) {
  console.log("My cat's name is " + name);
}`

output: My cat's name is Tiger

As you already know that when functions are hoisted then whole body of function is copied in memory allocation phase. So, In case function hoisting it does not give any error.
Arty Farty - AI Song Contest 2020
Published: 2022-05-12 13:00:59

---
title: Arty Farty - AI Song Contest 2020
published: true
date: 2022-05-12 09:28:00 UTC
tags: 
canonical_url: https://dataroots.io/research/contributions/arty-farty-3
---

Since 2020, dataroots participate in the AI Song Contest. Since the contest is coming soon and the team is working hard, we thought to tease with our [previous participations!](https://open.spotify.com/embed/album/5LiTKxFWyy20sgplyB0c9i?utm_source=generator)

6 dataroots colleagues group together with only one mission: generating fully automated songs by clicking a button! The final algorithm generates songs by traversing the shortest distance in MIDI harmonies sampled by Variational Autoencoders.

Songwriting was so easy each team member generated their own tunes. The final submission (Violent Delights Have Violent Endings) was democratically voted by the whole company.

**2020** - by **Beatroots AI**

<iframe width="200" height="113" src="https://www.youtube.com/embed/pQCsZhVwdi8?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
Cara Upload File Atau Image Ke Firebase Pada React Native
Tags: javascript, firebase, reactnative
Published: 2022-05-12 09:05:00

## **Getting Started**
install [firebase](https://www.npmjs.com/package/firebase) pada projek kamu
```
npm i firebase
```
atau

```
yarn add firebase
```
**Tambahkan Firebase configuration pada projeck kamu**
saya menyimpan Firebase configuration pada `root/src/config/Firebase.js` isi file Firebase configuration seperti ini :

```
import { initializeApp } from "firebase/app";

const firebaseConfig = {
  apiKey: "xxxxx",
  authDomain: "xxxxx",
  databaseURL: "xxxxxxx",
  projectId: "xxxxxxx",
  storageBucket: "xxxxxxx",
  messagingSenderId: "xxxxxxx",
  appId: "xxxxxxx",
  measurementId: "xxxxxxx"
};

// Initialize Firebase
const app = initializeApp(firebaseConfig);

export default app;
```
**view button** 

```
<TouchableOpacity style={styles.btnUpload}>
    <Text style={styles.btnLabel}>Upload Photo</Text>
</TouchableOpacity>
```
**install image picker**
saya menggunakan library [react-native-image-picker](https://www.npmjs.com/package/react-native-image-picker)

```
npm i react-native-image-picker
```
atau 

```
yarn add react-native-image-picker
```
import [react-native-image-picker](https://www.npmjs.com/package/react-native-image-picker) pada file screen kamu, misalkan `root/src/screens/UploadPhoto.js`

```
import {launchImageLibrary} from 'react-native-image-picker';
```
**install react-native-uuid**

```
npm i react-native-uuid
```
atau

```
yarn add react-native-uuid
```
import pada file screen kamu 

```
import uuid from 'react-native-uuid';
```
**import firebase**
jangan lupa import firebase juga

```
import React from "react";
import {
  StyleSheet,
  Text,
  TouchableOpacity
} from "react-native";

import uuid from "react-native-uuid";
import { launchImageLibrary } from "react-native-image-picker";
import {
  getStorage,
  ref,
  uploadBytes,
} from "firebase/storage";

import firebase from "../config/Firebase";
```
**Buat function upload photo**

```
const uploadPhoto= async () =>{
    await launchImageLibrary({}, async (response) => {
        if (response.didCancel || response.error) {
            Alert.alert("oops, batal memilih foto.");
        } else {
            let uri = response.assets[0].uri;
            let fileName = response.assets[0].fileName;
            
            let storage = await getStorage(firebase);

            const rersult = await fetch(uri);
            const blob = await rersult.blob();

            uploadBytes(ref(storage, fileName), blob, {
            contentType: "image/jpeg",
            firebaseStorageDownloadTokens: uuid.v4(),
            }).then(() => {
            console.log("Upload With blob");
            });
        }
    });
}
```
tambahkan onPress pada button

```
<TouchableOpacity style={styles.btnUpload} onPress={()=> uploadPhoto()}>
    <Text style={styles.btnLabel}>Upload Photo</Text>
</TouchableOpacity>
```

Selesai 🚀😎