teleren/devto huggingface dataset:
Trying to @POST at a server url - getting Trust anchor for certification path not found
Tags: help, android, ssl, retrofit
Published: 2022-06-09 13:17:37

I am trying to make a post request with a body, with Retrofit and OkHttpClient in kotlin. The url is https and when I try to make the request I am getting the Trust anchor for certification path not found exception

Also in manifest I am using android:usesCleartextTraffic="false"

This is the way I am creating the sslSocketFactory and I am using a custom .crt file. I also have a .key file which i am not sure if i should use it. When i try the request with insomnia api client, I need both files to make a successful request.

`object RetrofitHelper {
    fun getOkHttpClient(context: Context): OkHttpClient {

        val loggingInterceptor = HttpLoggingInterceptor()
        val client = OkHttpClient.Builder()
        client.followRedirects(false)
        client.followSslRedirects(false)
        client.connectTimeout(10, TimeUnit.SECONDS)
        client.callTimeout(20, TimeUnit.SECONDS)
        client.addInterceptor(loggingInterceptor)


        val cf = CertificateFactory.getInstance("X.509")
        val certificate = context.resources.openRawResource(R.raw.crtfile)
        val key = context.resources.openRawResource(R.raw.keyfile)

        try {
            val ca = cf.generateCertificate(certificate)
            val keyStoreType = KeyStore.getDefaultType()
            val keyFactory = KeyFactory.getInstance("RSA")

            val keyBytes = ByteArray(key.available())

            val keyStore = KeyStore.getInstance(keyStoreType)
            keyStore.load(null, null)
            keyStore.setCertificateEntry("ca", ca)
            val arrayOfCertificates = Array<Certificate>(1) { ca }

            keyStore.setKeyEntry("key", keyBytes, arrayOfCertificates)


            val tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm()
            val tmf = TrustManagerFactory.getInstance(tmfAlgorithm)

            tmf.init(keyStore)
            val sslContext = SSLContext.getInstance("TLS")
            sslContext.init(null, tmf.trustManagers, null)

            client.sslSocketFactory(
                sslContext.socketFactory,
                tmf.trustManagers[0] as X509TrustManager
            )

        } catch (e: Exception) {
            Log.d(TAG, "getOkHttpClient: " + e.localizedMessage)
        } finally {
            if (certificate != null) {
                certificate.close()
            }
        }
        return client.build()
    }}`
Day 12 - Enums
Tags: 100daysofcode, solidity, web3, blockchain
Published: 2022-06-09 13:09:00

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

This is Day `12` of `30` in Solidity Series
Today I Learned About Enums in Solidity.

Enums are the way of creating user-defined data types, it is usually used to provide names for integral constants which makes the contract better for maintenance and reading. 

Enums restrict the variable with one of a few predefined values, these values of the enumerated list are called enums. Options are represented with integer values starting from zero, a default value can also be given for the enum. By using enums it is possible to reduce the bugs in the code.

**Syntax**

```solidity
enum <enumerator_name> { 
    element 1, 
    element 2,
    ....,
    element n
} 
```

Example:

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

pragma solidity ^0.8.7;

contract EnumType {
    // Creating an enumerator
    enum Days {
        Monday,
        Tuesday,
        Wednesday,
        Thursday,
        Friday,
        Saturday,
        Sunday
    }
    // Declaring variables of type enumerator
    Days day;

    // Setting a default value
    Days constant defaultDay = Days.Monday;

    // Get default Day
    function getDefaultDay() public pure returns (Days) {
        return defaultDay;
    }

    // Set day to a object from the enumerator Days
    function setDay() public {
        day = Days.Tuesday;
    }

    // get value of day
    function getDay() public view returns (Days) {
        return day;
    }
}
```

Output:

When we run the getDefaultDay function, we get the default value of the enumerator.

```solidity
0:uint8: 0
```

When we run the getDay function we get `0:uint8: 0` as we have set it to a default value of Monday.

When we run the setDay function and then run the getDay function we get `0:uint8: 1` as setDay function has set the value of `day` to Tuesday.

---
If let shorthand project wide refactoring using Xcode regex search & replace.
Tags: swift, refactorit, wwdc, ios
Published: 2022-06-09 13:08:11

Swift 5.7 introduced this beauty (**if let shorthand**)
[https://github.com/apple/swift-evolution/blob/main/proposals/0345-if-let-shorthand.md](https://github.com/apple/swift-evolution/blob/main/proposals/0345-if-let-shorthand.md)

You can leverage the power of regex in Xcode search and replace bar to refactor your projects codebase.

**Search:**```if let (\w+) = (\1) \{```
**Replace:**```if let $1 \{```

![Xcode Regex Search & Replace](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/20hoq2uiyuutjavky5h0.png)
Closures In JavaScript
Tags: javascript, beginners, programming, tutorial
Published: 2022-06-09 13:05:38

Like i said in my previous post about stale closures in React and JavaScript (Check my page for more info!), i'm here to talk about closures in detail in this post.

So, what are closures?

In order to understand closures, first we have to talk about something called **Lexical Scoping**.

Check the following example:

```javascript
const outerFunc = () => {
  const name = "Khan";
  
  const innerFunc = () => {
    console.log(name);
  }

  return innerFunc;
}
```

"A lexical scope in JavaScript means that a variable defined outside a function can be accessible inside another function defined after the variable declaration."

In the example i gave, the function **innerFunc** has access to the **name** variable because it's lexical scope is inside the **outerFunc** function and after the declaration of the **name** variable.

Now, with the information we have, let's check out what a closure is from the example below.

```javascript
const outerFunc = () => {
  const name = "Khan";
  
  const innerFunc = () => {
    console.log(name);
  }

  return innerFunc;
}

const nameLogger = outerFunc();

nameLogger(); // Will log "Khan" to the console
```

But how does the innerFunc remember the name variable, even after the outerFunc has been invoked and the name variable isn't in the scope anymore?

This is called a **closure** in JavaScript. The function innerFunc closed over the outer variable **name**, and is able to remember it even after the **outerFunc** function has been invoked because of this.

Closures has many use cases. Like the example below:

```javascript
const adder = (x) => {
  return (y) => x + y;
}

const addTwo = adder(2);
const four = addTwo(2);

console.log(four); // Will log 4
```

In the example above, we used closures to make an adder function, in which the returned arrow function inside the adder function will still remember variable x, because it closes over it.

The function generator in the example above is also called **Currying**, which means we use functions to create other functions which might help reduce the amount of code we write. If not for currying and closures, we would have to do something like this:

```javascript
const addTwo = (x) => x + 2;
const addFour = (x) => x + 4;
const addTen = (x) => x + 10;
```

Thanks to closures, we're able to reduce the amount of code we write and we can make our code much cleaner.

## CONCLUSION

Closures are a very essential part of JavaScript, and it can be used in many ways. For example, React hooks rely heavily in closures. If you want to see how, you can check out my article **Avoid Stale Closures in React**. It might help you out understand closures better and how it can also create pitfalls in your code by accident if not used correctly.

And as always, thank you so much for reading my article to this point! If you think i have mistakes, feel free to write them in the comments. I will absolutely check out all of them and make the correct changes in my article.
Guess Number Higher or Lower
Tags: leetcode, dsa, theabbie
Published: 2022-06-09 13:00:46

We are playing the Guess Game. The game is as follows:

I pick a number from `1` to `n`. You have to guess which number I picked.

Every time you guess wrong, I will tell you whether the number I picked is higher or lower than your guess.

You call a pre-defined API `int guess(int num)`, which returns three possible results:

*   `-1`: Your guess is higher than the number I picked (i.e. `num > pick`).
*   `1`: Your guess is lower than the number I picked (i.e. `num < pick`).
*   `0`: your guess is equal to the number I picked (i.e. `num == pick`).

Return _the number that I picked_.

**Example 1:**

**Input:** n = 10, pick = 6
**Output:** 6

**Example 2:**

**Input:** n = 1, pick = 1
**Output:** 1

**Example 3:**

**Input:** n = 2, pick = 1
**Output:** 1

**Constraints:**

*   `1 <= n <= 231 - 1`
*   `1 <= pick <= n`

**SOLUTION:**

    # The guess API is already defined for you.
    # @param num, your guess
    # @return -1 if my number is lower, 1 if my number is higher, otherwise return 0
    # def guess(num: int) -> int:
    
    class Solution:
        def guessNumber(self, n: int) -> int:
            beg = 1
            end = n
            if guess(beg) == 0:
                return beg
            if guess(end) == 0:
                return end
            while beg <= end:
                mid = (beg + end) // 2
                curr = guess(mid)
                if curr == 0:
                    return mid
                elif curr == -1:
                    end = mid
                else:
                    beg = mid
Why isn't there Tinder for coding partners?
Tags: beginners, javascript, webdev, discuss
Published: 2022-06-09 12:58:40

I'm a person who really enjoys having a partner to work on stuff with. Maybe there is some obscure syntax that needs googling -- one of you can go look it up while the other keeps working on the actual logic challenges. 

Perhaps you're just struggling with motivation, or your sleep cycle, and knowing that someone is waiting on you to get up off your lazy backside and get on voice chat and get to work is important to you.

Maybe you just enjoy bouncing ideas off of another person, and hearing their ideas, then working together to make them a reality. 

Not only that, but for a lot of new coders who might want to go on to make a career of this you're going to need to learn how to talk to other humans about code. 


I can fire up an app on my phone and find almost anything I want. I can buy a broken refrigerator, sell a camera lens, or as the title implies find someone to go on a 'date' with. 

I know there are lots of great communities (my favorite being dev.to due to the diversity of skill level, writing style, and culture) but there isn't a centralized place to say "I'd like to build my first Vue/React/Vanilla-ts/Python/whatever, anyone want to learn with me?"

I know the webdev community loves to think of itself as super inclusive and open and friendly but to be honest, it is a little cliquey. Go on any Discord server about webdev and you'll find there is a group of people who are usually highly skilled and very tight knit. Open source projects are even more intimidating.

I wish I could swipe ... right? left? I've never used Tinder but whichever way you swipe to say "We're a match!" and find people to work on projects with.


People often say learning to code on your own is an "adventure" but in all my years I've never once been on an adventure that wasn't enhanced by having someone else along for the ride.

Stay healthy,
- Jas
Using 1Password CLI for secrets locally
Tags: programming, security, 1password, secrets
Published: 2022-06-09 12:52:04

Secrets are the backbone of how developers work in today's data-driven and service world. Password manager apps like 1Password, Lastpass, and Bitwarden have been keeping our passwords safe for years.

Developers have not stuck with the same approach when it comes to secrets though. In the best-case scenario secrets are encrypted and worst case they are plaintext stored within config files.

With that in mind, this article will aim to help you source secrets from your 1Password vault locally leading to better security and a single source of truth.

First thing is to make sure you have the [1Password CLI](https://1password.com/downloads/command-line/) installed and configured. Now we can start configuring our .env file to load things from the vault.

Here I've created an API Credential that lives in the "Secrets" vault which I've named "Demo Secret".
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/pqsw33ig9ahwa6qgj1pt.png)

We can access this secret using the [following schema](https://developer.1password.com/docs/cli/secrets-reference-syntax)
`op://vault-name/item-name/[section-name/]field-name`

Create a file in your home directory somewhere, I'll be using `$HOME/personal/.env` but feel free to change this. 

Example:
```bash
SECRET_DEMO="op://secrets/demo secret/credential"
```
Now we'll want to create a nice shell helper function that can go into your profile.
```bash
# added to my $HOME/.zshrc file
# where we will store the env file
ENV_PATH=$HOME/personal/.env

# call this function anything you'd
function sec {
  # see if we are logged in, will return exit code > 0 if not
  op whoami
  
  # if we are logged skip if not ask for master password
  if [[ $? != 0 ]]; then 
    eval $(op signin)
  fi

  # this will inject the env vars we defined in our .env file
  op run --env-file=$ENV_PATH -- $@
}
```
Make sure to [reload your shell](https://coderwall.com/p/wyvcuq/reload-your-shell) so we have access to the new `sec` helper function we made.

Now clone the demo repo, change into the new directory, and start the app with the `sec` util.

```bash
# clone the demo project
git clone https://github.com/Hacksore/demo-1pass-secrets.git

# change directory
cd demo-1pass-secrets

# start with the prefixed util
sec npm start
```

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

And there you have it! You can now start apps that require secrets in environment variables just by prepending the `sec` util.

It should work well for any language as long as you can start your app from the CLI.

![hacker man gif](https://c.tenor.com/TbTe1Nc6j34AAAAC/hacker-hackerman.gif)

**Additional Resources**
[Demo Repo](https://github.com/Hacksore/demo-1pass-secrets)
[1Password Docs](https://developer.1password.com/docs/cli/secrets-environment-variables)
[1Password Blog](https://blog.1password.com/1password-cli-2_0)
[Inspiration](https://rossedman.io/blog/computers/setting-env-vars-from-1password/)
The Giveaway for you😍
Tags: webdev, beginners, programming, discuss
Published: 2022-06-09 12:45:45


Hello friends!

I am **jackson kasi**

I have swag coupon code for participating in Azure contest.

But I can't use it. Because these swags will only be delivered in **USA** country.

If any of you want this you have a very simple thing to do.

Whether you have your open-source project or portfolio project & web link or any project you have done, please comment about it below.

[any - GitHub project link, web link with your repo link, portfolio link with your repo link] 

I will share this coupon code to whoever of you gets the most likes.

winner will announced - **June 12**

--- 

Redeem your swag prize here: https://aka.ms/azure_swag

Please use the above to redeem your swag prize and note the following.

1.  Go to the swag redemption portal linked above.
2.     Use the code to log in. Please note that this is a one-time usable unique code that will be valid to redeem any swag item from the portal.
3.     Select swag and checkout. Enter the U.S. address where you want the swag to be delivered.

Congratulations and have a wonderful day!


![swags](https://oshi.at/fCte/TyZH.png)
Webrtc Peer to Peer Dev Help?
Tags: discuss, communityquestion, webdev
Published: 2022-06-09 12:31:11

I originally created an older project that was basically stackoverflow plus zoom where developers could meet online and pair program/help each other and I was thinking about picking it up again.  At the time there was a more popular service and community so I stopped working on it, but that service has been discontinued. I am wondering if this is something other developers would actually use?  I did not have much luck with traction before so I am guessing not.  Here is a picture of the original concept: ![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/79doaoxhx7atq0rozz6e.png)
All Paths From Source to Target
Tags: leetcode, dsa, theabbie
Published: 2022-06-09 12:30:36

Given a directed acyclic graph (**DAG**) of `n` nodes labeled from `0` to `n - 1`, find all possible paths from node `0` to node `n - 1` and return them in **any order**.

The graph is given as follows: `graph[i]` is a list of all nodes you can visit from node `i` (i.e., there is a directed edge from node `i` to node `graph[i][j]`).

**Example 1:**

![](https://assets.leetcode.com/uploads/2020/09/28/all_1.jpg)

**Input:** graph = \[\[1,2\],\[3\],\[3\],\[\]\]
**Output:** \[\[0,1,3\],\[0,2,3\]\]
**Explanation:** There are two paths: 0 -> 1 -> 3 and 0 -> 2 -> 3.

**Example 2:**

![](https://assets.leetcode.com/uploads/2020/09/28/all_2.jpg)

**Input:** graph = \[\[4,3,1\],\[3,2,4\],\[3\],\[4\],\[\]\]
**Output:** \[\[0,4\],\[0,3,4\],\[0,1,3,4\],\[0,1,2,3,4\],\[0,1,4\]\]

**Constraints:**

*   `n == graph.length`
*   `2 <= n <= 15`
*   `0 <= graph[i][j] < n`
*   `graph[i][j] != i` (i.e., there will be no self-loops).
*   All the elements of `graph[i]` are **unique**.
*   The input graph is **guaranteed** to be a **DAG**.

**SOLUTION:**

    class Solution:
        def allPathsSourceTarget(self, graph: List[List[int]]) -> List[List[int]]:
            n = len(graph)
            op = []
            paths = [([0], {0})]
            while len(paths) > 0:
                curr, visited = paths.pop()
                if curr[-1] == n - 1:
                    op.append(curr)
                for newcurr in graph[curr[-1]]:
                    if newcurr not in visited:
                        paths.append((curr + [newcurr], visited.union({newcurr})))
            return op
Create connect wallet button with React + Web3.js + Bootstrap
Tags: react, web3, bootstrap, metamask
Published: 2022-06-09 12:30:04

I will teach you how to create a button that will interact with MetaMask to let the user connect their wallet on your app.

`npx create-react-app wallet-connect
cd wallet-connect`

Check the react-scripts version in package.json, the version need to be 4.0.3 to be compatible with web3.js

Run this command line to install everything we need :
`yarn add web3 react-bootstrap bootstrap react-bootstrap-icons`

add this line in index.js : 

```
import 'bootstrap/dist/css/bootstrap.css';
```

Final App.js file :
```
import React from 'react';
import Web3 from "web3";
import { Button } from 'react-bootstrap';
import { Wallet } from 'react-bootstrap-icons';
import './App.css';

class App extends React.Component {

  constructor(props) {
    super(props);
    this.state = {
      web3: null,
      currentAccount: null,
      ethBalance: 0,
      networkId: null
    };
  }

  componentDidMount = async () => {
    this.connectWalletHandler();
  };

  connectWalletHandler = async () => {
    try {
      const web3 = new Web3(Web3.givenProvider);
      this.setState({ web3: web3});
      const accounts = await web3.eth.requestAccounts();
      if (accounts.length !== 0) {
        const networkId = await web3.eth.net.getId();
        const ethBalance = await web3.eth.getBalance(accounts[0]);
        this.setState({currentAccount: accounts[0], ethBalance: Web3.utils.fromWei(ethBalance), networkId: networkId});
      } 
    } catch (error) {
      console.error(error);
    }
  }

  connectedWallet = () => {
    return (
      <div>
        <p>{parseFloat(this.state.ethBalance).toFixed(4)} ETH</p>
        <p>{this.state.currentAccount.slice(0,5)+'...'+this.state.currentAccount.slice(38,42)}<br />WALLET CONNECTED</p>
      </div>
    )
  }

  connectWalletButton = () => {
    return (
      <Button variant="outline-primary" onClick={() => this.connectWalletHandler()}><Wallet />&ensp;Connect wallet</Button>
    )
  }

  render() {
    return (
      <div className="App">
         {this.state.currentAccount ? this.connectedWallet() : this.connectWalletButton()}
      </div>
    );
  }
}

export default App;
```
The Plunge
Tags: ubuntu, linux, beginners
Published: 2022-06-09 12:21:28


Attachment  to  norms is what  hinders us  from  achieving our true power.
How is that possible  you may  ask?
  
  Well  lets get  to it ...


There I stood   thinking  whether to  take the  plunge or not ;  tell  you what   I swam even before feeling the waters and evaluated every  single  outcome ,but then I recalled the only way  to be a dreamer was to  dream so  the only way  id   be  a swimmer was by  definitely taking  the plunge .
Well  truth  be  be told ,   I had to  snap  out of it  and  and  make  my decision,,,
I took  the dive ……..,
just  so  you  know neither did I freeze nor drown the waters weren’t what they looked like. Invigorating is quite the term  for effect  the  waters   had  on  me ... 

Damn logical reasoning ,hell bent on making Me believe that the waters were icy  and  I’d freeze 🥶 on  diving. 

Enough  with  the Ngũgĩ wa Thiongo spirit and  lets get  back  to business ,I recently  shifted to  the **Debian** based distro   **Ubuntu** from  Windows and  have  loved my  stay there,because with an  environment  that  allows you  to  do   what you want  you  definitely  rise  with  the  power to  do more & be  more  

Tell  you  what ,Shifting  to  Ubuntu   is  something  you  should add on to  your bucket- list , Developer or  not forget about the yammering around you and  think  about how it feels to venture into something new
Reasons you should take the plunge if you haven't💣:


 1.As a developer one should be flexible and be exposed to  working  in new Operating system  environments without lessening  productivity .

2.Ubuntu helps in  familiarizing  with  the terminal  also  referred to as the Command line interface (CLI)

3.Wide range of technical  support on how to get started on your journey and advance to higher levels
4.Linux based operating systems are one way  to  breathe life to old PC's and Laptops,this is because they  ensure optimal hardware utilization while ensuring efficient resource allocation.
5.Needless to say Ubuntu boasts of a rich & Friendly Graphical User Interface GUI hence making  the go to destination for newbies who want to  familiarize with  command line without getting the “shift shock”.
6.Ubuntu allows you to test it and get a hang of  it  before fully installing  it  as your Daily  drive /Host  operating system.
  
7.Ubuntu is free to download and use.
      
8.Ubuntu  is where developers are😎.
   
      



**Resources**

[More about  Ubuntu](https://ubuntu.com/blog/ubuntu-22-04-lts-whats-new-linux-desktop)


[Wanna try or install  Ubuntu](https://ubuntu.com/download/desktop)

[Become a better“Luser”  linux User](https://linuxjourney.com/)



Well  till next time
   fly on  birdie 🐦