teleren/devto huggingface dataset:
Systemd: start supervisor after redis on reboot
Tags: systemd, ubuntu, redis, supervisor
Published: 2022-02-13 18:07:30

I am using _supervisor_ to run my web application on system boot, and one of the application is using _redis_, so that requires _redis_ start first.

_supervisor_ doesn't have a good way to support start dependency, but _systemd_ support this.

## Steps

0, Create your _redis_ start config file, e.g. `6379.conf`, and make sure the `daemonize` is set to `no`

1, Create redis systemd file `redis.service`:
```
[Unit]
Description=Redis
After=network.target

[Service]
User=redis
Group=redis
ExecStart=/usr/local/bin/redis-server /home/redis/6379.conf
ExecStop=kill -s HUP $MAINPID
Restart=on-failure

[Install]
WantedBy=multi-user.target
```

2, Copy this file to path:
```bash
cp redis.service /lib/systemd/system/
```

3, Start redis with systemd:
```
systemctl start redis
```

4, Set start redis on system boot:
```
systemctl enable redis
```
If you changed the service file content, you need to reload it:
```
systemctl daemon-reload
```

5, Go to folder `/etc/systemd/system/multi-user.target.wants`, and find `supervisor.service`, under the `[Unit]` section, add line:
```
Requires=redis.service
```

All done. Now on the system reboot, _redis_ will start before _supervisor_, so if you applications are booted by _supervisor_, now they can safely connect to _redis_.
Ray : for building distributed applications.
Tags: ray, api, huggingface
Published: 2022-02-13 18:00:05

I have started looking at [Ray serve](https://docs.ray.io/en/latest/serve/tutorial.html
) and [hugging face](https://huggingface.co). Ray serve is helpful in deploying AI and ML models on the cloud and the in house servers. You can expose api to Ray serve very easily. You can build AI & ML apps with Ray serve. It has the following features :

- Providing simple primitives for building and running distributed applications.

- Enabling end users to parallelize single machine code, with little to zero code changes.

- Including a large ecosystem of applications, libraries, and tools on top of the core Ray to enable complex applications.
Ways/Ideas to monetize a mobile game!
Tags: gamedev, ios, android, tooling
Published: 2022-02-13 17:39:47

So You made a unique and enjoyable mobile experience but you want to earn some money from it and you are looking for ways then this is for you! or you want to learn about game monetization or app monetization this blog is recommended.
so lets divide the ways in 3 parts:
       -*Enjoyable monetization
       -*Competitive monetization
       -*Profitable monetization 
and the final part being the tools tpo integrate advertisement services. 
btw I meant anything(in game playable) by stuff,
like levels,skins,characters,items,in game currency etc
##Section 1:
       **Enjoyable monetization:**
_ADVERTISEMENT:_
Lets face it if you ever played an android game a sudden advertisement was annoying as hell but if you were asked about if you want to watch an ad ,It wasn't that bad right?
yep,you can monetize your games with an enjoyable ad system but that won't be that profitable compared to section 3.Though if you use Among us like ad system it will be profitable and maintain a good user experience as well
##Section 2:
       **Competitive monetization:**
_AWARD AD SYSTEM:_
*You get this smexy skin and this banger gun for a 5 second ad!* is not a way be hated right?
If a game is awarding you stuff for advertisement and it's fine if you don't watch it you can unlock it by playing more later but you can rn with an ad.It's pretty enjoyable.
End users would love this bc who doesn't want more items?
You can make it pretty more likely to watch the ad by not allowing the item to be unlocked later without watching ad and make it disappear after more time. 
##Section 3:
       **Profitable monetization:** 
_AGGRESSIVE ADVERTISMENT:_
This might be more profitable but dont ever try it.
This method annoys the end user, they are more likely to not play your game again.
For playing every scene they need to watch an ad or everytime they enter the game they have to watch an ad

##Tooling:
You can use bytebrew for extra monitoring.
For unity You can use:
[Unity Ads SDK](https://unityads.unity3d.com/help/monetization/getting-started?_gl=1*1k17uvq*_gcl_aw*R0NMLjE2NDQ3Mzk3ODIuQ2p3S0NBaUE5YUtRQmhCUkVpd0F5R1A1bFRfaVVwZE5hTmdrOGxlM2wyNFYyaGRFMVJIYXdqcV8tazFHWWc2cDFzZUNOanBGUkd5cGJSb0MtU0VRQXZEX0J3RQ..*_gcl_dc*R0NMLjE2NDMyOTgxMDAuQ2owS0NRaUFvc21QQmhDUEFSSXNBSE9lbi1PclhmWmVDUGlIRTdIRFYwOGZseWQ0WWdoM0dCQ3hNc3FQNmRMbl9Xc25IdENnVzJpM0FuTWFBbFcwRUFMd193Y0I.)
for unreal:
[Unreal Engine Docs](https://docs.unrealengine.com/4.27/en-US/SharingAndReleasing/Mobile/Ads/)
for Godot:
[Godot Forum](https://godotengine.org/qa/47788/how-to-monetize-android-app-with-ads)
for construct:
[Construct Docs](https://www.construct.net/en/make-games/faq/monetising)
JDK, JVM, JRE para que serve ?
Tags: beginners, java
Published: 2022-02-13 16:31:32

## JVM (JAVA VIRTUAL MACHINE)

Java(codigo fonte)  -> compilador(javac) -> bytecode -> JVM = executar

Quando passado o bytecode para a Java virtual machine, ela compreende seu código e interpreta e executa, então compreendemos que o código fonte é passado para o JAVAC e compilado e gerado um bytecode e quando passado para a JVM, ela interpreta e executa nas plataformas de software.

JAVAC: então para sanar duvidas o JAVAC é o compilador primário da linguagem JAVA




JRE(JAVA RUNTIME ENVIRONMENT)

o JRE é composto por 2 partes, a JVM e bibliotecas e é utilizado para executar as aplicações da plataforma Java

## o que compõe uma JVM ?

Loader / Verificador

Loader: é a parte interna da sua JVM que carrega o bytecode na memoria da maquina virtual.

Verificador: ele faz uma verificação se o código pode ser interpretado sem nenhum problema.


## Interpretador / Gerenciador / JIT

Interpretador: Ele vai pegar seu código em ByteCode e transformar em código nativo
do seu sistema operacional. na maquina que estiver ele converte o código em Bytecode
em uma instrução que seu sistema operacional compreenda


Gerenciador: Trata como os códigos e variáveis serão gerenciados dentro da JVM


Compilador JIT: a cada trecho de código é traduzido no instante em que está para ser 
executado


## JDK(JAVA DEVELOPMENT KIT)

O JDK é composto pelo compilador e bibliotecas(API's) necessárias para criação de programas em Java, e ferramentas uteis para o desenvolvimento e para testes dos programas escritos por esta linguagem de programação.
Dentro do JDK já temos incluso o JRE e todos seus componentes, a Java LANG e Java Tools e Debugger.
Dicas para escrever um artigo de blog
Tags: artigo, blog, redacao, conectivos
Published: 2022-02-13 16:52:38


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

Antes de começar a escrever, procure as palavras-chave usadas pelos usuários para pesquisar seus produtos ou os tópicos do artigo do seu blog nos mecanismos de pesquisa.

As palavras-chave escolhidas certamente serão incluídas no título do artigo e no primeiro parágrafo.

Um post de blog deve conter pelo menos 600 palavras.

Insira links internos para artigos existentes ou conteúdo do site.

Escreva conteúdo original.

O artigo do blog deve ser de fácil leitura, o assunto deve ser claro desde o primeiro parágrafo do artigo.

Use títulos, subtítulos, parágrafos e, se necessário, listas com marcadores.

O comprimento de um parágrafo não deve ser excessivo, 4 frases são suficientes.

Introduza o tema do artigo no primeiro parágrafo e depois explique-o em profundidade nos seguintes.

**Reordenar os tópicos
**
Existem várias maneiras de classificar os vários tópicos em um artigo, tudo depende do tipo de tópico abordado no post.

Por exemplo, você pode optar por ordená-los cronologicamente, ou explicando o tópico de forma genérica no início e tornando-se cada vez mais específico à medida que escreve.

Ou, então, você pode usar um método muito usado pelos redatores web, ou seja, contar os elementos cruciais e importantes no início e entrar em cada vez mais detalhes à medida que avança na redação.

**Como escrever parágrafos
**
Agora que a lista de tópicos foi elaborada e ordenada seguindo a lógica descrita acima, podemos começar a escrever os vários parágrafos de cada tópico no alinhamento.

Algumas regras:

- - Um parágrafo deve abordar apenas um tema/tópico;
- - Um parágrafo deve conter uma frase básica e, em seguida, uma elaboração posterior desta;
- - Use espaços em branco de forma consistente com o texto, não apenas por estética;
- - Cada parágrafo deve conter no máximo 4 frases.
- Use [conectivos para redação](https://adeusponto.com/conectivos-para-redacao/)

**Use títulos e subtítulos para ajudar o leitor
**
Os títulos são muito importantes para seus leitores, pois permitem que eles rolem rapidamente pelo texto e decidam se (ou quais partes) desejam ler sobre seu artigo. Portanto, os subtítulos devem ser claros e devem cobrir o conteúdo dos parágrafos seguintes.
Using splice() Method to Remove Items - Laravel
Tags: php, laravel, webdev, programming
Published: 2022-02-13 16:34:31

Found this great resource https://www.larashout.com/laravel-collection-using-splice-method-to-remove-items that shows us how to use splice() and use it in your next projects I will show briefly, but visit the source to go deeper.

The below example shows a very simple use of the splice() method
```php
use Illuminate\Support\Collection;

$collection = new Collection([
    0,1,2,3,4,5,6,7,8,9
]);

// Splice the $collection from 5th index, which is 4
$spliced = $collection->splice(5);

dd($spliced); //return a new collection of remaining items like below.
/*
Illuminate\Support\Collection^ {#1338
  #items: array:5 [
    0 => 5
    1 => 6
    2 => 7
    3 => 8
    4 => 9
  ]
}
*/

dd($collection); //it will hold only the first five values of the original collection
/*
Illuminate\Support\Collection^ {#1341
  #items: array:5 [
    0 => 0
    1 => 1
    2 => 2
    3 => 3
    4 => 4
  ]
}
*/
```
The $length parameter can be used to control how long the section that is removed from the collection can be. The following example shows, how you can remove three items from the collection
```php
use Illuminate\Support\Collection;

$collection = new Collection([
    0,1,2,3,4,5,6,7,8,9
]);

// Splice the collection starting from 2nd item
// and take at most 3 items
$spliced = $collection->splice(2,3);

dd($spliced);
/*
Illuminate\Support\Collection {#656 ▼
  #items: array:3 [▼
    0 => 2
    1 => 3
    2 => 4
  ]
}
*/

dd($collection); //will now have the remaining items
/*
Illuminate\Support\Collection {#670 ▼
  #items: array:7 [▼
    0 => 0
    1 => 1
    2 => 5
    3 => 6
    4 => 7
    5 => 8
    6 => 9
  ]
}
*/
```
The below example shows how you can use the $replacement parameter
```php
use Illuminate\Support\Collection;

$collection = new Collection([
    'London', 'Paris', 'Dublin', 'Berlin'
]);

$spliced = $collection->splice(1, 3, [
    'New York', 'Tokyo', 'Sydney'
]);

dd($spliced);
/*
Illuminate\Support\Collection {#656 ▼
  #items: array:3 [▼
    0 => "Paris"
    1 => "Dublin"
    2 => "Berlin"
  ]
}
*/

dd($collection);
/*
Illuminate\Support\Collection {#670 ▼
  #items: array:4 [▼
    0 => "London"
    1 => "New York"
    2 => "Tokyo"
    3 => "Sydney"
  ]
}
*/
```
I hope you enjoyed it as much as I did with this great code and information.
Paracetamol.js💊| #53: Explica este código JavaScript
Tags: javascript, webdev, spanish, beginners
Published: 2022-02-13 16:32:39

## **Explica este código JavaScript**

```js
const getList = ([x, ...y]) => [x, y]
const getUser = user => { name: user.name, age: user.age }

const list = [1, 2, 3, 4]
const user = { name: "Lydia", age: 21 }

console.log(getList(list))
console.log(getUser(user))
```

-     A: `[1, [2, 3, 4]]` y `SyntaxError`
-     B: `[1, [2, 3, 4]]` y `{ name: "Lydia", age: 21 }`
-     C: `[1, 2, 3, 4]` y `{ name: "Lydia", age: 21 }`
-     D: `SyntaxError` y `{ name: "Lydia", age: 21 }`

Respuesta en el primer comentario.

---
Cardenas VS code extension: Save and search algorithms
Published: 2022-02-13 16:27:30



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


Hey there 👋 I’m [Juanse](https://github.com/juansemastrangelo), a frontend developer passionate about open source.

I created an extension for visual studio code when you can search and save algorithms in any coding language. The project is Open Source and you can take a look the code [here](https://github.com/CardenasExtension/cardenas-client) and the service [here](https://github.com/CardenasExtension/cardenas-service).

## Usage

1. [Download the extension.](https://marketplace.visualstudio.com/items?itemName=juansemastrangelo.cardenas)

2. Save your code in a file clicking in “Upload code using Cardenas” at the right-bottom.

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

3. Select if it is Template or Algorithm

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

4. Set a description for your code to find easly in the search section.

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


## Contributing
Contributions are what make the open source community such an amazing place to learn, inspire, and create. Any contributions you make are greatly appreciated.

If you have a suggestion that would make this better, please fork the repo and create a pull request. You can also simply open an issue with the tag “enhancement”. Don’t forget to give the project a star! Thanks again!

Fork the Project
1. Create your Feature Branch (git checkout -b feature/AmazingFeature)
2. Commit your Changes (git commit -m 'Add some AmazingFeature')
3. Push to the Branch (git push origin feature/AmazingFeature)
4. Open a Pull Request

## Thanks
Awesome, you made it till the end! Thank you for reading, I hope you found something useful in here.
Using Redis 7's New Sharded Pub/Sub in Go
Tags: go, redis, performance, tutorial
Published: 2022-02-13 16:20:35

Redis 7.0 RC1 is released in 2022/1/31. And it comes with a new [Sharded Pub/Sub](https://redis.io/topics/pubsub#sharded-pubsub) feature:

> Sharded pubsub helps to scale the usage of pubsub in cluster mode. It restricts the propagation of message to be within the shard of a cluster. Hence, the amount of data passing through the cluster bus is limited in comparison to global pubsub where each message propagates to each node in the cluster. This allows users to horizontally scale the pubsub usage by adding more shards.

Now, users can use the new `SPUBLISH` command to publish messages without worrying about overwhelming the whole Redis cluster.

And use `SSUBSCRIBE` command to receive those messages.

Here is an example showing how to use this new feature with [rueidis](https://github.com/rueian/rueidis), a high-performance RESP3 go client library:

```golang
package main

import (
	"context"
	"fmt"
	"time"

	"github.com/rueian/rueidis"
)

func main() {
	client, _ := rueidis.NewClient(rueidis.ClientOption{
		InitAddress: []string{"127.0.0.1:7001", "127.0.0.1:7002", "127.0.0.1:7003"},
	})

	ctx := context.Background()

	go func() {
		for {
			client.Do(ctx, client.B().Spublish().Channel("ch").Message("hi").Build())
			time.Sleep(time.Second)
		}
	}()

	client.Receive(ctx, client.B().Ssubscribe().Channel("ch").Build(), func(msg rueidis.PubSubMessage) {
		fmt.Println(msg.Channel, msg.Message)
	})
}

```

The above snippet does the following:
1. Initialize the client with Redis cluster addresses.
2. Start a goroutine to do `SPUBLISH` every second.
3. Use `client.Receive` with a `SSUBSCRIBE` command and a callback function to keep processing received messages.

The `client.Receive` will block forever until the `ctx` is done or the client is unsubscribed from the channel.

That's it! If you have any questions or issues with [rueidis](https://github.com/rueian/rueidis), please contact me on Github.
Introduction to modern python
Tags: beginners, programming, python
Published: 2022-02-13 16:19:14


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/pwc3i8edmitntlskqbd4.jpg)
**Python** is an interpreted, high-level  programming language with dynamic semantics. Python programs have the extension.**py** and can be run from the command line by typing **python file_name.py.**



## Why learn Python?

- It is also quite easy to learn, understand, code and  a developer-friendly language.

- Python is free and open sourced. Not only can you download Python for free, but you can also download its source code, make changes to it and even distribute it.

-  Python supports object-oriented programming and concepts of classes, objects encapsulation, etc.

- Python can be extended to other languages. You can write some of your code in languages like C++ or C. This comes in handy, especially in projects.

- Easily portable as it can be shared and you can run a code on any platform.

- Python has  extensive libraries that contain codes for various purposes.So, we don’t have to write the complete code for that manually.

## Where can Python be used ?

- Artificial Intelligence and machine learning. 

- Web development. 

- Game development. 

- Data science.

- Audio and Visual Application.

-  Software Development.

- Automation.

## Setup your python working environment
 For starters or data science enthusiasts,install  [ anaconda]( https://www.anaconda.com/products/individual)<br>

**Anaconda | Individual Edition**<br>Anaconda's open-source Individual Edition is the easiest way to perform Python/R data science and machine learning on a single machine. (19 kB)
<br> ![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/vfgpv9osywr6ys50wegb.png)
 For software developers/engineers install python interpreter ( preferably Python 3.8) [here]  (https://www.python.org/downloads/release/python-380/ )<br>![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/mmpsjdosi09kda8xtu09.png)
 
 Also install a  text editor of your choice.I prefer Visual Studio Code which can be downloaded through this [link] (https://code.visualstudio.com/).<br>
At the end of the installation,confirm your installation by opening the terminal and type:
```python
python --version
```
Then it should print the python version you just installed.<br>Now we are all set and you can proceed to create your first program!<br>
Launch VS Code and create a new file where your codes will be saved and it must have the **.py** extension.<br>For instance,I will create a file called **helloworld.py** and type in :
```python
print("Hello World!")
```
Save your file. Open your command line, navigate to the directory where you saved your file, and run the code.<br>The output should be:
```python
Hello World!
```
Congratulations, you have written and executed your first Python program.
Integrate Jitsi Meet IFrame API in React
Tags: react
Published: 2022-11-05 15:00:46

---
title: Integrate Jitsi Meet IFrame API in React
published: true
date: 2022-02-13 16:15:00 UTC
tags: React
cover_image: https://dev-to-uploads.s3.amazonaws.com/uploads/articles/rdnl098hulf9mufn6m2p.jpeg
canonical_url: https://anlisha.com.np/blog/integrate-jitsi-meet-iframe-api-in-react/
---

Jitsi is a set of open-source projects that allows you to easily build and deploy secure videoconferencing solutions.  
We’ll be using IFrame API to embed Jitsi Meet functionality in React application.

**A peak at final UI!**

![](https://anlisha.com.np/blog/wp-content/uploads/2022/05/1_THvoy7VckF2vuj6Cvi0org.png)

**Let’s Start!**

**Step1 — Start Basic CRA**

```
npx create-react-app react-jitsi-meet
cd react-jitsi-meet
npm install @mui/material @emotion/react @emotion/styled
```

We also installed MUI 5 for creating UI components.

**Step 2 — Setup Jitsi component; Initialize Jitsi Meet API library scripts**

A container element with pre-defined height and width is must for Jitsi iframe to render into.

{% embed https://gist.github.com/anlisha-maharjan/7e62f67a370baf61ec9f1a9fadf8427f %}

If you have self-hosted Jitsi server in your domain, you can specify its URL endpoint instead of `meet.jit.si.`  
Note that`initialise` function is called only once when the component is first rendered, and Jitsi’s `dispose()` method is called when the component is destroyed.  
Also the object from instantiating `JitsiMeetExternalAPI` provides methods and event listeners to configure and control the Jitsi interface. For example: `interfaceConfigOverwrite` allows to overrides options such as `APP_NAME`, `DEFAULT_BACKGROUND`.

**Step 3— Import Jisti Component in App.js**

```
import React from “react”;
import Jitsi from “./components/jitsi”;
function App() {
  return <Jitsi uuid=”1be9b511-eb38–4a97–909b-d70ee03a9501" />;
}
export default App;
```

**This is it.**

**Source Code!**  
all the source code is available at — [https://github.com/anlisha-maharjan/react-jitsi-meet](https://github.com/anlisha-maharjan/react-jitsi-meet)

**More Info!**  
 [Have a look at Jitsi’s docs for all the options, commands, methods and events available.](https://jitsi.github.io/handbook/docs/dev-guide/dev-guide-iframe)

The post [Integrate Jitsi Meet IFrame API in React](https://anlisha.com.np/blog/integrate-jitsi-meet-iframe-api-in-react/) first appeared on [Anlisha Maharjan](https://anlisha.com.np/blog).
'K' Closest Numbers(code and explanation)
Tags: algorithms, python, leetcode, programming
Published: 2022-02-13 16:09:07

**Problem Statement** 
Given a number array and two integers ‘K’ and ‘X’, find ‘K’ closest numbers to ‘X’ in the array. 
Return the numbers in the sorted order. ‘X’ is not necessarily present in the array.
Example 1:
Input: [5, 6, 7, 8, 9], K = 3, X = 7
Output: [6, 7, 8]
Example 2:
Input: [2, 4, 5, 6, 9], K = 3, X = 6
Output: [4, 5, 6]
**SOLUTION**
For finding the closest numbers to X we can simple calculate the absolute difference between X and 
all the values from the array.Now we store these values in a pair using tuple (abs diff, value) with the abs difference
along with the value itself
So, for example, [5, 6, 7, 8, 9], K = 3, X = 7
the tuple values would be (2,5), (1,6), (0,7), (1,8), (2,9)
So the value the first value in the tuple, the closest the element is from X 
Now we want the top k(3) values from this tuple that are closest to X(7)
Now we can utilize the heap data structure to do so
We can use min heap which will store the tuples in smallest to greatest values
So the heap will look like

                (0,7)
               /     \
             (1,6)   (1,8)
            /    \
          (2,5)  (2,9)     
Now we can easily remove the top K elements from this heap which will give the closest numbers
Look at the below code for more clarity
**CODE**

```
from heapq import *
def findClosestElements(A,K,X):
    answer = []

    minHeap1 = []
    for num in A:
        heappush(minHeap1, (abs(num-X),num)) #Creates a min heap with tuple values as discussed

    minHeap2 = [] #Remove the top K elements from minHeap1 and store in minHeap2 as we have to maintain order
    n = K
    while n > 0:
        a = heappop(minHeap1)
        heappush(minHeap2, a[1]) #Append top K elements values from the minHeap1 and store the second value 
        n -= 1                   # from the tuple i.e (0,7) --> 7 as '7' is the actual element

    while minHeap2:
        b = heappop(minHeap2) #Remove all the elements from the minHeap2 one by one and store them in answer 
        answer.append(b)
    
    return answer 
```
_Time Complexity_
The first step of creating minHeap1 will take O(N)
Creating minHeap2 will take O(KlogK)
So overall time complexity is O(KLogK)
_Space Complexity_
O(N) for storing N elements in heap