teleren/devto huggingface dataset:
SSH Tunnel
Tags: vimeditor, linux, devops, tjkt1tugas
Published: 2022-09-06 00:53:28

**Tunneling ke workstation dengan cara**

```
ssh student@xx.xx.xx.xx -p 1XX09 -Dbebas
```

contoh: 

```
ssh student@10.2.2.11 -p 13809 -D8888
```

**Setting socks proxy di firefox dengan:**

- Jalankan aplikasi Browser firefox
- Buka settings
- Cari Network Setting atau Pengaturan jaringan
- Pilih Manual proxy configuration
- Pada sock host masukan ip localhost = 127.0.0.1, Port masukan port yang digunakan saat tunneling contoh= 8888.
- Centang pada Proxy DNS when using SOCKS v5

**Lanjut mengikuti intruksi guide di lab**
Run a node app into AWS lambda
Tags: aws, node, docker
Published: 2022-09-06 00:41:56

I create this post because I didn't find any information on this when I needed it, or the information was dispersed around the web, so I hope this post helps someone. This is going to be straight and I'm assuming that you already have a private repository in AWS.

Steps

1. Create your code and ensure that a handler exists.
2. Setup & upload your Dockerfile with the right parameters.
3. Configuring AWS.
4. Close the rest of your browser tabs.


If you are reading this before you write any code make sure to check the repository of AWS and confirm the node version (Some of the node versions are not verified, you can find the supported versions here).

Once you have your Node JS code you need to make sure that inside your main file exists a handler function this is a requisite for lambda functions no matter the programming language.

```
const https = require('https')
let url = "https://docs.aws.amazon.com/lambda/latest/dg/welcome.html" 

export.handler = async (event) => {
     
  const promise = new Promise((resolve, reject) => {
    https.get(url, (res) => {
        resolve(res.statusCode)
      }).on('error', (e) => {
        reject(Error(e))
      })
    })

  return promise
 
}
```

After you have all your logic we are going to create a container with docker. Your Dockerfile should be similar to this:

```
FROM public.ecr.aws/bitnami/node:14.20.0

COPY ./source .

RUN npm install --omit=dev


CMD [ "app.handler" ] 
```
In this case, we're using node:14.20 as an image (notice the repository), we install all the packages ignoring devs dependencies (we don't need linters or other tools into the container) and in the CMD we call the function handler.

For testing purpose you can also use node -e 'require("./index").handler()' in CMD.

Then build the container.

```
docker build -t <name>:<tag> .
```

Push the files to your AWS private repository using the CLI of AWS (be aware that the following are just dummy data, you need to replace them with your values).

```
aws ecr get-login-password --region us-east-1 | docker login --username AWS --password-stdin 123456789012.dkr.ecr.us-east-1.amazonaws.com   
```
 

```
docker tag  <name>:<tag> 123456789012.dkr.ecr.us-east-1.amazonaws.com/<name>:<tag>
docker push 123456789012.dkr.ecr.us-east-1.amazonaws.com/<name>:<tag>
```
Lambda is going to run this every time that is being invoked. Now you need to create a repository inside AWS.

After you push your files go into lambda and select create a lambda container function, once there just pick the container from your repository, and set the correct permissions. Once finish the process try to invoke the test, you can place an API Gateway layer so your function can be called from an endpoint.

Some other helpful resources:

AWS Node Lambda container [documentation](https://docs.aws.amazon.com/lambda/latest/dg/nodejs-handler.html).
Sample of the code inside my personal [repo](https://github.com/dashpy/node-container-lambda)
This one is a [video tutorial](https://www.youtube.com/watch?v=23fE57EFRK4) for python
h-DBSCAN: A simple fast DBSCAN algorithm for big data，looks like a fake.
Published: 2022-09-06 00:40:33

A picture in this paper: 
[Shaoyuan Weng, Jin Gou, Zongwen Fan; Proceedings of The 13th Asian Conference on Machine Learning, PMLR 157:81-96](https://proceedings.mlr.press/v157/weng21a/weng21a.pdf)
seemed to copy from [the post](https://www.it610.com/article/4811193.htm) 
and, no any reference to Figure 5, no improve, also, seems like a boast.:-D

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ks9gd4b84iivyu3cu2fl.jpg)
Padrão Singleton com PHP
Tags: php, webdev, programming
Published: 2022-09-06 00:10:58

O padrão singleton tem como finalidade centralizar a criação de um objeto, mantendo o vivo durante todo o ciclo de execução.

> SINGLETON, O ANTI-PATTERN
> Para muitos, o padrão Singleton é considerado um anti-
> pattern por conta do seu uso em forma estática (chamando a
> classe sem precisar instanciá-la) e, principalmente, pelo
> acesso global à instância da classe. Os problemas de utilizar
> classes estáticas são vários: não podemos trabalhar com
> interfaces, nosso código fica com um acoplamento mais alto,
> entre outros.
(quote do livro: Design pattern com PHP 7 - página 43.) 

Dito isso, o singleton ainda é muito utilizado no mercado quando precisamos de uma instância unica. 

Com esse controle, impedimos a criação descontralada de instancias de classes. Este padrão é muito utilizado quando estamos lidando com classes/frameworks de logs. 

```
<?php 

namespace Singleton; 

class LogsSingleton 
{

    /** @var self $singleton instância da classe de logs. */
    protected static LogsSingleton $instancia;

    /** os métodos construtor, clone e wake up precisam ser privados, para que a classe só seja criado via método getInstancia */
    private function __construct()
    {
        
    }
    private function __clone()
    {
        
    }
    private function __wakeup()
    {
        
    }

    public static function getInstancia() : self 
    { 
        // self => se refere a própria classe 
        // Se a instancia estiver vazia, nenhuma classe foi criada ainda 
        if (empty(self::$instancia))
        {
            self::$instancia = new self();
        }
        return self::$instancia;
    }

    /** function para gravar dados em um arquivo de texto, simulando log */
    public function gravarLog(array $dados):void 
    {
        $nomeArquivo = 'logs.txt';

        $logsAnteriores = [];

        if (filesize($nomeArquivo) > 0)
        {
            $conteudoArquivo = file_get_contents($nomeArquivo);
            // com esse array vazio, impedimos erros casos o arquivo inicial esteja vazio
            $logsAnteriores = json_decode($conteudoArquivo, true);
        }
        $logsAnteriores[] = $dados;
        // escreve no arquivo 
        $arquivo = fopen($nomeArquivo, 'w');
        fwrite($arquivo, json_encode($logsAnteriores));
        fclose($arquivo);
    }
}

$instanciaLogs = LogsSingleton::getInstancia();
print_r($instanciaLogs);
```


Criamos a propriedade $instancia de forma estática, já que ela será responsável por garantir o acesso único a instância da classe. Os métodos mágicas __construct, __wakeup e __clone estão privados para impedir que sejam chamados e criem instâncias da classe. 

Se tentarmos criar uma instância desta classe, sem utilizar o método getInstancia(), teremos um fatal error. 

Testando:

```

$instancia = LogsSingleton::getInstancia();
$instanciaNova = LogsSingleton::getInstancia(); 

if ($instancia === $instanciaNova) 
{ 
 echo "são iguais";
}
```
Can your change be safely reverted?
Tags: backwardcompatibilit, revert
Published: 2022-09-23 21:57:34

---
title: Can your change be safely reverted?
published: true
date: 2022-09-06 00:00:00 UTC
tags: backwardcompatibilit,revert
canonical_url: https://jhall.io/archive/2022/09/06/can-your-change-be-safely-reverted/
---

An often-overlooked use case for code or infrastructure changes, is the ability to revert.

Sometimes we do think about this, when it comes to things like destructive database changes. We may be careful not to delete the users table, without a backup.

But I often see this concern being forgotten about more menial changes, and sometimes it can bite!

Here’s a random example:

Your HTTP server sets a session cookie for every visitor, which contains the user name as a simple string. This has been working fine for months… until you decide that it would be good to store additional information in the cookie. Like maybe the user’s favorite flavor of ice cream.

You can no longer use a simple string. You need some way for your cookie to contain multiple pieces of information. Maybe you choose for a comma-separated list. This is perfect, because your code can easily split on commas, and use the first value as the user name, and the second value as the favorite ice cream flavor. And if the second value doesn’t exist, no problem… you can set it the next time you send a cookie their way.

You’ve now got a nifty ice cream flavor storing cookie, and it’s 100% backward compatible! All old cookies still work, with no problem, and new cookies will be gracefully upgraded.

But what happens if you ever have to revert the ice cream flavor feature?

What if you discover that tracking ice cream flavors just puts too much load on your database. And it wasn’t really very useful anyway… so now you’re going to revert the code.

Except now, all your users sessions are invalid. Whoops!

And the reason is that `alice,vanilla` isn’t a valid user name. 🤔

What’s the solution? Although I can think of a handfull of potential solutions to this type of problem, sadly, there isn’t a single one-size-fits all solution.

The point here isn’t how to solve the problem. The point is to be aware of the potential for the problem in the first place, so that you can plan for such eventualities.

How would you solve this type of problem? Send me an email, and let me know. 🙂

* * *
_If you enjoyed this message, [subscribe](https://jhall.io/daily) to <u>The Daily Commit</u> to get future messages to your inbox._
Chrome插件开发 - Publishing a Chrome browser extension
Published: 2023-08-13 02:12:12

---
title: Chrome插件开发 - Publishing a Chrome browser extension
published: true
date: 2022-09-06 00:00:00 UTC
tags: 
canonical_url: https://manon.icu/blog/translate/build-chrome-extensions/publishing-a-chrome-browser-extension
---

[Chrome Store](https://chrome.google.com/webstore/devconsole)

向 chrome store 发布插件需要账户，并且一次性支付 5 刀

![ltzRTH](https://cdn.jsdelivr.net/gh/manonicu/pics@master/uPic/ltzRTH.jpg)

注册并支付后，点击做侧边栏选项卡，点击新建项目

![1nDx44](https://cdn.jsdelivr.net/gh/manonicu/pics@master/uPic/1nDx44.jpg)

提交`zip`文件后，需要填写一些必须的字段：

- 描述：关于此扩展做什么的
- 类别：扩展类型
- 语言：插件的主要语言
- 图标：商店图标（128\*128）
- 屏幕截图：提供至少一张 1280*800 或 640*400 的屏幕截图

在`隐私`选项上：

- 简短介绍
- 权限：使用了哪些权限
- 数据：需要使用哪些数据

如无法提交，点击以下链接查看可能的原因。

![YEafWz](https://cdn.jsdelivr.net/gh/manonicu/pics@master/uPic/YEafWz.jpg)

## Source Code

[【Source Code】](https://github.com/rebelchris/turbo-reader)
Introducing the Auth0 Flutter SDK
Tags: flutter, android, ios, programming
Published: 2022-09-05 20:10:18


> Original post written by [Juan Cruz Martinez](https://auth0.com/blog/authors/juan-cruz-martinez/) for Auth0 blog.

### Learn about the essential features of the Auth0 Flutter SDK and how it helps developers build and secure Flutter iOS and Android applications.

### <br>

Today we are announcing the release of the [Auth0 Flutter SDK](https://pub.dev/packages/auth0_flutter), a new SDK that makes it easy to secure Flutter applications with Auth0. Whether you need to secure access to an iOS or Android application, the Auth0 Flutter SDK got you covered!

The new Flutter SDK builds on a strong foundation by wrapping our existing and robust [Auth0.Android](https://github.com/auth0/Auth0.Android) and [Auth0.swift](https://github.com/auth0/Auth0.swift) libraries while focusing on the developer experience first.

Our SDK team optimized the Auth0 Flutter SDK for quick integration into your applications and for flexibility to accommodate simple and advanced use cases.

Since the introduction of [Flutter 3](https://medium.com/flutter/introducing-flutter-3-5eb69151622f), the framework allows for building cross-platform applications, extending from mobile applications to desktop applications and platforms. Our SDK allows for extension in such platforms by leveraging federated plugins, which means you can easily add support for other platforms without forking the SDK.

## Auth0 Flutter SDK Features

The new SDK offers features for multiple use-cases and complexity, going from magically getting the job done to providing a rich set of APIs enabling you to build your authentication flow per your specific requirements.

Let's explore the essential features of the Auth0 Flutter SDK that enable developers to do more:

- ⚡️ Quick implementation of login, logout, and automatic storage and renewal of tokens functionality into Flutter apps using WebAuth and the [Auth0 Universal Login](https://auth0.com/docs/authenticate/login/auth0-universal-login) page.
- ⚙️ For more advanced use-cases, developers have access to the [Authentication API](https://pub.dev/documentation/auth0_flutter/latest/auth0_flutter/AuthenticationApi-class.html), which at the time of release supports:
	- Logging in with a username or email and password
	- Signing up new users
	- Getting user information from `/userinfo`
	- Renew tokens
	- Reset passwords
- 🔐 Auth0 provides a default instance of [Credentials Manager](https://pub.dev/documentation/auth0_flutter/latest/auth0_flutter/DefaultCredentialsManager-class.html) that automatically stores the user's credentials. If you need your own solution for handling credentials, you can create your own [custom credentials manager](https://pub.dev/documentation/auth0_flutter/latest/auth0_flutter/CredentialsManager-class.html).
- ➕ And more [advanced features](https://pub.dev/packages/auth0_flutter#advanced-features) like accepting user invites, login into organizations, and bot detection.

[Read more...](https://auth0.com/blog/introducing-the-auth0-flutter-sdk/?utm_source=devto&utm_medium=sc&utm_campaign=devto)
How to configure path aliases w/Vite + Vue/React
Tags: javascript, vue, vite, react
Published: 2022-09-05 23:59:30

While building [Humanizer](https://kohasummons.github.io/humanizer), I hit a snag while trying to import a component using the '@' path alias to src.

![What you get if path aliases aren't configured in your project](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/fbgou0sdcr635xkmxcfo.jpeg)

That's when I realised that Vite does not provide path aliases(@/~) out of the box. If we want to use that, we would need to set it up ourselves.

Hi, I am koha and In this short article, I will show you how to configure your Vite Project, vue or react, to work without fuss with path aliases.

## Why Path aliases

Path aliases clean up your import statements. And beyond that, it contributes greatly to having a maintainable codebase. Get rid of those `../.../.../` sort of imports today and use path aliases. Just do it. ☘️

## Configuring Path Aliases

In your `vite.config.js` file, at the top of the file, import the path module.

```js
import * as path from 'path';
```

Then add the `resolve` option to the object passed to `defineConfig`:

```js
export default defineConfig({
  // ... rest of the code
  resolve: {
    alias: [{ find: "@", replacement: path.resolve(__dirname, "src") }],
  },
});
```

That would inform vite of the alias and now '@' should now resolve correctly to `/src/`.

Your `vite.config.js` file should look like this now. Yours might be slightly different if you have other things set up

```js
import { defineConfig } from "vite";
import vue from "@vitejs/plugin-vue";
import * as path from "path";

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [vue()],
  resolve: {
    alias: [{ find: "@", replacement: path.resolve(__dirname, "src") }],
  },
});
```

## Using path alias

Now you can reference components, imports or whatever really using a `@`.

```js
import TheHero from "@/components/TheHero.vue";
```

Everything should work fine if you followed the guide correctly.

## Conclusion 

Awesome! 🚀 You Just configured your project to use path aliases and supercharge your workflow.

I hope this article has been useful. If you want snappy, super fast content like this, you can follow me here and in one click you would be notified of my next post.

Do leave a comment if you've got any questions and contributions.

Koha.
Aptos Typescript SDK
Published: 2022-09-05 23:35:29

Aptos предоставляет официальный SDK на языке Typescript. Typescript SDK получает наибольшее внимание со стороны команды Aptos Labs и сообщества, что означает тщательное тестирование и активные обновления. Он доступен на npmjs с исходным кодом в [репозитории aptos-core GitHub](https://github.com/aptos-labs/aptos-core/tree/main/ecosystem/typescript/sdk).

## Примечание по совместимости
Вы должны убедиться, что используете правильный SDK для среды, в которой ведется разработка:

Devnet: Используйте последний пакет на [npmjs](https://www.npmjs.com/package/aptos).
Local testnet: Используйте SDK из соответствующего коммита. Подробнее об этом рабочем процессе тестирования вы можете прочитать [здесь](https://dev.to/egormajj/rukovodstvo-po-protsiessu-razrabotki-lokalnoi-tiestovoi-sieti-40i6).

Если у вас нет особых причин, вы должны использовать первую установку для разработки, devnet + пакет на npmjs. Подробнее о различных вариантах установки вы можете прочитать [здесь](https://aptos.dev/nodes/aptos-deployments/).
Introducing pi-chat.ml, looking for contributors.
Tags: opensource, contributorswanted, react, python
Published: 2022-09-05 23:18:53

Hello, I started this project as part of a Hackathon ([BuilderHacks S2](https://builderhacks2.devpost.com)) and would like sharing it with you.

[πChat](http://pi-chat.ml)

# The project
The basic idea is developing chatrooms that allow friends to study together by submitting questions with a ML model in the backend verifying the answers. The latter is important because oftenly, answers are checked like this:

![Computers are usually dumb when checking answers](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/mzp5zqkot6ks47llxeba.png)

NLP and other technologies like CAS are used to __smartly__ grade submissions like so:

![They should check what the user meant, not what they typed exactly](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/bq12bo3otite6xcrxb0p.png)

## Grading questions

Hence, several techniques are used to verify answers:
- **Text strict**: As you might expect, verifies that expected answer and submission match _exactly_.
- **Text medium**: Transforms to lowercase and strips away punctuation (and parentheses, apostrophes, etc) to verify that expected answer and submission match _loosely_.
- **Text similarity**: Uses NLP (Though spacy) to verify that the similarity score for answer and submission is above 0.8

- **Scalar**: Uses quantulum3 to identify scalars with unit and number and verify the answer matches submission (e.g., 10 cm = 10.0 centimeters)
- **Math**: Uses CAS to make sure mathematical expressions match. (e.g., "(x*x)/2" == "0.5*x^2")

![Visual description of the above](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/n1bidl0rxlsuthpewafr.png)

## Other features
Additionally other features include KaTeX support, a drawing canvas and chatroom generation. 

# In the future
I developed the project in under two days as part of the hackathon but I intend to take it even further in the future, solving many bugs (and there are many) as well as integrating new features. I am open to feedback as well as working together with other people to make it happen. 

# Technologies used
- Frontend: React
- Frontend (real time communication): hop.io
- Backend: Python

------

Please let me know if you have any feedback and if you'd be interested in participating. 

Devpost submission with more info: https://devpost.com/software/chat-edgwsa?ref_content=my-projects-tab&ref_feature=my_projects
Explaining Selection Sort Algorithm in Simple English
Tags: dsa, sorting
Published: 2022-09-05 23:10:52

In this Blog, we will discuss the Selection Sort Algorithm and its working procedure. Selection sort is an in-place comparison-based sorting algorithm that sorts the array by repeatedly finding and swapping the minimum element with the leftmost element of the array.

> In-place means that the algorithm does not use extra space for manipulating the input but may require a small though non-constant extra space for its operation. Usually, this space is O(log n), though sometimes anything in O(n) (Smaller than linear) is allowed.

In this algorithm, the array is divided into two parts. One part will initially be empty but will contain the sorted array and is placed on the left-hand side, while the other part carries the original unsorted array and is placed on the right-hand side. In every iteration, the minimum element is picked from the unsorted list and gets placed at the beginning of the sorted array, thus reducing the size of the unsorted array by one while at the same time increasing the size of the sorted array by 1.

Now that we have understood what selection sort is, let’s understand its working procedure with a simple example of an array with a length of 5.

## How Selection Sort Algorithm Works
The working principle of this algorithm is very simple. As told, we just have to find the minimum element from the unsorted array and place it at the beginning of the sorted array.

To begin with we have to assume that the first element of the unsorted subarray is the minimum element of the array. Then by iterating and comparing every element of this unsorted array with the first element which we have assumed to be the minimum element of the array we have to find the minimum element of the array.

If we find any element less than our current min element, that element becomes the new min of the array and the journey continues till the last element. Upon reaching the end of the array, simply replace the leftmost element of the unsorted array with the current min element. We have to do this every time until the array is sorted completely.

Let’s take an example of an array of length 5 to understand it better

![Unsorted Array](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/jwcxvcb662bo4p1jm3z5.png)

Since the array we are using is of length 5, we will be making 4 passes. One pass per element, and as for the last element, it will be automatically sorted. Thus we can say that for an array of size n, n-1 passes are required to sort that array using the selection sort.

[Continue Reading…](https://tekolio.com/explaining-selection-sort-algorithm-in-simple-english/)