teleren/devto huggingface dataset:
Serverless web API with Deno and Begin - Part 2
Published: 2021-01-06 19:34:21

In a previous post, we wrote a single serverless function in TypeScript and Deno to display a random quote with HTML. The response was overwhelming, and now the public demands an API they can integrate into their applications. Let's add a `/api` route! 

## Adding a new route

We're going to add a new route for our API by modifying the `app.arc` file. 

```bash
# app.arc
@app
your-app-name

@http
get /
get /api
```

Next, we will make a new directory and file for our HTTP function. Copy the following code into `src/http/get-api/index.ts`.

```javascript
// src/http/get-api/index.ts
import { quote } from "https://gist.githubusercontent.com/pchinjr/75027d05c5844d2f2364e1acbb2c8c37/raw/2ff84587ba01d6d262125fe8c22c27d4b704a837/quote-zotic.js"
export async function handler (req: object) {
return {
  statusCode: 200,
  headers: {
  'cache-control': 'no-cache, no-store, must-revalidate, max-age=0, s-maxage=0', 'content-type': 'application/json; charset=utf8'},
  body: JSON.stringify( {data: quote() } )
  }
}
```

We also need to supply a small config file to change from the default Node.js runtime to Deno with a `.arc-config` file in the function folder. 

```bash
# src/http/get-api/.arc-config
@aws
runtime deno
```

The `get-api` function uses the same `quote()` logic from `get-index` but now we've got more quotes to choose from, and it returns JSON that can be consumed by other applications.

To see it in action, run `npm start` from your command line and navigate to http://localhost:3333/api

## Importing code with Deno
Deno uses ES Modules to import third-party code. I wanted to give this feature a try by taking the `quote()` logic from our `get-index` function and hosting it in a [GitHub Gist](https://gist.github.com).

You can see the gist here: 
[https://gist.github.com/pchinjr/75027d05c5844d2f2364e1acbb2c8c37](https://gist.github.com/pchinjr/75027d05c5844d2f2364e1acbb2c8c37)

```javascript
// gist.js
export function quote() {
 let quotes = ['first quote', 'second quote', 'third']
 let min = 0
 let max = quotes.length - 1
 let rando = ~~(Math.random() * (max-min) + min)
 return quotes[rando]
}
```

Using this kind of import gives us more control over dependencies without a centralized package manager. You can create your private package registry without any extra tooling. A change like this causes me to think more intentionally about the code I'm going to import. 

[For more info, the Deno docs have a helpful explanation about linking to third party code.](https://github.com/denoland/deno/blob/master/docs/linking_to_external_code.md)

## Deploy with CI/CD on Begin
A new API is only func when it becomes available to the public. Deploying is just one `git push` away. Each push to your default branch will start a new deployment to `staging`. Go ahead and show it off by sharing it with us on [Twitter](https://www.twitter.com/begin).

It's an exciting time to try new workflows as development tools continue to fade into the background. It allows all of us to focus on and explore what's possible in our core application logic.
How to scrape Google Maps in Python
Tags: google, maps, scrape, python
Published: 2021-01-06 19:33:28

## Creating the scraper from scratch
Developing your own Google Maps scraping tool might be a big challenge in case you don't have a few years of experience behind you. You will need to be prepared for plenty of challenges from Google - IP protection (proxies), cookies & sessions, browser emulation, site updates, etc.

## More quick and stable way
Fortunately, there are some good 3-rd party tools that you can easily integrate with your code and start scraping Google just within 5 minutes.

## Getting started

Installation (Python 3+) 
```
pip install google-services-api
```

Usage
```python
from outscraper import ApiClient

api_cliet = ApiClient(api_key='SECRET_API_KEY_FROM_OUTSCRAPER')
response = api_cliet.google_maps_search('restaurants brooklyn usa', language='en', region='US', limit=100)
```

Response
```
{
  'id': '3f6f8bd0-4073-4ca3-b92f-4caff9cb0456',
  'status': 'Success',
  'data': [
    {
      'name': 'The Loft Steakhouse',
      'full_address': '1306 40th St, Brooklyn, NY 11218',
      'borough': 'Borough Park',
      'street': '1306 40th St',
      'city': 'Brooklyn',
      'postal_code': '11218',
      'country_code': 'US',
      'country': 'United States of America',
      'us_state': 'New York',
      'state': 'New York',
      'plus_code': None,
      'latitude': 40.639734499999996,
      'longitude': -73.9868193,
      'time_zone': 'America/New_York',
      'site': 'http://www.theloftsteakhouse.com/',
      'phone': '+1 718-475-5600',
      'type': 'Steak house',
      'subtypes': 'Steak house, Fine dining restaurant, Kosher restaurant, Delivery Restaurant, Takeout Restaurant, Restaurant',
      'posts': None,
      'rating': 4.9,
      'reviews': 1638,
      'photos_count': 1054,
      'google_id': '0x89c25ad4507a6e2f:0x135c0e38302054ac',
      'place_id': 'ChIJL256UNRawokRrFQgMDgOXBM',
      ...
    }
   ...
  ]
}
```



[Python package page](https://pypi.org/project/google-services-api/)

[API docs](https://app.outscraper.com/api-docs)
Strength of for-of loop over for-in and foreach loops in ES6.
Published: 2021-01-06 19:30:41

Iterators are helpful to know because they serve as the basis for generators, which open new doors to asynchronous programming. ES6 came with for-of loop to beat some pitfalls found for-in loop. 

## Some drawbacks which are found in for-in loop:
1.The values assigned to the index are the strings, not actual numbers.
   Look here:
```javascript
var arr = [111, 222, 333];
for(var i in arr) {
    if(i === 1) {
        // Never execute
    }
```
2.for-in loop can iterate over the array elements in the arbitrary order.
3.In foreach loop, we can't break out of the loop using break statement. Another drawback is that no returning from the enclosing function using return statement.

## What for-of loop holds for us?
1.It avoids all pitfalls of for-in loop and works with
          **break**, **continue** and **return** statements.
   Here is an example:
```javascript
for (var num of arr) {
    if (num % 2 == 0) {
        continue;
    }
    console.log(num)
}
```
2.It also works on strings, where it treats strings as a sequence of Unicode characters
```javascript
for (var ch of "😺😲") {
    console.log(ch);
}
```
## Conclusion
Fellow guys, now I can recommend you to use this syntax sugar of for-of loop as it can help us in most cases. But, if you find some cases where you need such for-in and foreach loops, don't hesitate to use them as they are still useful.

Thank you!!!
My Personal Portfolio at DigitalOcean App Platform
Tags: dohackathon, showdev, portfolio, digitalocean
Published: 2021-01-06 19:29:18

###What am I building

I was thinking about creating a **portfolio** because it's a perfect way to show the qualities I would mention in a resume or talk about in an interview. Which provides proof of my applicable expertise and abilities.

###Category Submission

Personal Site/Portfolio

###App Links 

You can view my portfolio here 🚀:
https://sewvandiwickramasinghe-if8nt.ondigitalocean.app/ 

###Screenshots

####About me
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/7ggf8woqykjstcbw2udp.png)

####Experiences
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/izwfmxvo8arcja92gnrn.png)

####My Projects
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/r1bda2i8aiic2tohaa2n.png)

####My Blog
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/h86ibqejusdugfc4kngj.png)

####My Gallery
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/g8a7rib4j200nlkmleo1.png)

####Contact Me
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/4c26ebbut7v7cgbrvxfx.png)

###Demo video 🤓
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/avhmm24ng3dssjtjrrhc.gif)

###Description

My personal portfolio shows some of my education history, achievements,  volunteering experiences, tools expertness, dev articles and the projects that I've done. I developed this website using JavaScript, Html, and CSS. I used DigitalOcean App Platform to host my portfolio. It is amazing and convenient to build. 

###Link to Source Code

You can find the source code here 🚀:
https://github.com/Sewvandiii/sewvandiwickramasinghe

###Permissive License

The project is covered under [MIT Licence](https://github.com/Sewvandiii/sewvandiwickramasinghe/blob/main/LICENSE)

###Background
(What made you decide to build this particular app? What inspired you?)

Starting with the software engineering industry, I felt the need to be able to bring more expertise out there and still practice what I've learned. 

###How I built it
(How did you utilize DigitalOcean’s App Platform? Did you learn something new along the way? Pick up a new skill?)

I used CSS, JavaScript, SCSS (Sassy CSS😌) and HTML basically. I have worked with JavaScript to dynamically modify the website theme. I learned about deployment by reading How to deploy an app guide. I  deployed my very first static app, select GitHub repo and boom💥. I am really glad that DigitalOcean App Platform support it! It was so easy to setup when I choose to start from App Platform portal. They guide me to setup my application and recommend a number of options that would be helpful.

###Additional Resources/Info

Deployment on the Digital Ocean platform is very simple and effective. I genuinely liked and enjoyed my journey while I set up my App on DigitalOcean. Kudos to the team! 🥳
Ring Upp - DO Hackathon - Part 1/4 - First Steps
Tags: dohackathon, node, javascript, webdev
Published: 2021-01-06 19:22:52

---
title: Ring Upp - DO Hackathon - Part 1/4 - First Steps
published: true
description: The first part of our Ring Upp journey for the DO Hackathon.
tags: dohackathon, node, javascript, webdev
cover_image: https://dev-to-uploads.s3.amazonaws.com/i/vn9qpemo9vgv5ivuxi7c.png
series: Ring Upp DO Hackathon
---
First off, I was super excited to have an excuse to work on a side project with a deadline and an end goal. As well as have a chance to try hosting my project on DigitalOcean App Platform.

Usually taking time to work on a side project is difficult because the project may be fun but not have a clear way to make money or a project may have a way to make money/be successful but then can feel like regular work.

This is a great balance between working on something I enjoy and being able to share with the community and also win a contest.

Now to the first steps.

## First steps

What to work on? So many projects so little time.

Three projects came to mind for this contest.

1. Covid related dashboard or something related to tracking helpful covid data.
2. A QA app to track test cases in test suites to be run by QA engineers.
3. A video chat app.

The covid dashboard would be an interesting project to work on, but with a short timeline, it's not something I would want to start. It would take more time to research and more effort than I could give right now.

The QA application is something that has been on my list for a while. I had previously built an MVP that works well enough to build user stories and run through tests. Unfortunately, I built it 2 years ago and know so much more about development and what I would want out of the QA project that I may as well rewrite the entire application. This is a useful application that is on my list but once again would take too much time.

So that leaves the video chat app.

## The video chat app

I am a Development Manager and Video Engineer as my full-time job and love working on video applications. On my list for a long time is a video application using WebRTC.

A few months ago I listened to an episode of [Syntax.fm](https://syntax.fm/show/256/webrtc-and-peer-to-peer-video-calling-with-ian-ramzy) that interviewed a developer talking about a simple video chat application they built. It is a great episode about learning new technology and building a simple app while learning. That along with the changing landscape of video moving towards WebRTC made this a great application to build right now.

So that's what I set out to build! Oh also the app won't just be between peers it will be between a max of three. So added a bit more of a challenge there.

Let's lay out what we need for the project:

- Landing page
- A page to create a new call
- A page for the video chat to take place
- Pages to direct unsupported browsers to
- All of the business logic of connecting users with WebRTC and keeping them connected

I won't go too deep into every part of every feature. But in my next post, I'll give some high-level overviews of everything listed above.
COMPLETE GUIDE TO HOTEL AGGREGATOR API
Tags: computerscience, testing, productivity, programming
Published: 2021-01-06 19:20:21

In this post, we will learn how hotel price comparison API can help to generate more bookings & generate discounted hotel prices by tracking the competitors. 

* Hotel Aggregator Technology
* Price Comparison
* Competitive advantage
* Data from niche websites
* Track Competitors

Complete Guide - [Hotel API](http://www.makcorps.com/)
Creating a Notepad using Java and JavaFX
Tags: java, sideprojects, codenewbie
Published: 2021-01-06 19:15:04

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/5amb9y16mytqfzagrdcq.png)
<br>

Hello friends so I decided to learn a bit of JavaFX this year, it wasn't for any other reason than pure curiosity so without further ado I'll tell you what I did. It's far from perfect but if you'd like I could do a small tutorial for you guys so just let me know below!
<br>
 
Okay so for starters I wasn't new to Java I just had to re-acquaint myself with some syntax but aside from that this was all new to me. I tried watching some YouTube videos but none of them really caught my eye in the sense of learning because they were either outdated or was a speed code, so I went to the next best thing.. Books! I don't have the names on hand but they helped me a little so much so that I decided that I wanted to make a small app to test.
<br>

<h4>Planning</h4> 
This project was fairly simply considering all I wanted to do was make a dark themed version on Windows' Notepad, and for the most part I accomplished that except for the bugs and other things that proved to be difficult. I originally had my own design that I wanted to do but I bit off more than I could chew 😅 here is the design if you wanted to see, feel free to use it just give credits and tag me if you do!
<br>
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/qpnh6wlvkcq7s1p9l6oy.png)

##### That's all for now, if there's anything you'd like to ask contact me in the comments or via [Twitter](https://twitter.com/MeshaMakes) let me know you're coming from here :)
Trying Hashicorp Nomad 1.0 with LXD and Terraform
Tags: nomad, terraform, lxd, containers
Published: 2021-01-06 19:05:50

---
title: Trying Hashicorp Nomad 1.0 with LXD and Terraform
published: true
description: Simulate a Nomad cluster using LXD to emulate machines using containers, Terraform to provision infrastructure and Packer to build container images
tags: Nomad, Terraform, LXD, Containers
cover_image: https://dev-to-uploads.s3.amazonaws.com/i/yl6889zz3zla4oh9e622.png
---

A while ago I wrote an article about [deploying Hashicorp Nomad using LXD and Ansible](https://dev.to/livioribeiro/using-lxd-and-ansible-to-simulate-infrastructure-2g8l) and since Nomad hit 1.0 I decided to revisit it. It is an interesting and I wanted to try [Terraform](https://terraform.io) and learn a bit about it.

You can find everything [in this repository](https://github.com/livioribeiro/nomad-lxd-terraform).

To deploy the cluster, install Terraform and Packer and then `terraform apply`.

I used [Packer](https://packer.io), another tool from Hashicorp, to create the container images and I also added a Prometheus instance to monitor the Nomad cluster and services. I will probably add Grafana in the future and if you know a good dashboard for Nomad, please share :)

Terraform is a great tool, but Ansible is still more flexible, although it can be a bit harder to deal with and sometimes I feel lost in its documentation.

Nomad is a good alternative to Kubernetes, specially if you are deploying your own cluster, with focus in simplicity and it is so easy to test it on your own machine.
DX stands for developer experience
Tags: beginners
Published: 2021-01-06 18:53:29

I came across this interaction around the use of the term "DX" in [this pull request](https://github.com/forem/forem/pull/12155) within the [Forem repo](https://github.com/forem/forem). 

![Screen Shot 2021-01-06 at 1.51.14 PM](https://dev-to-uploads.s3.amazonaws.com/i/wd6vmd6ti5bcjtn4yvmc.png)

I thought it would be useful to share this for anybody else who might come across this term and be confused. Acronyms can be passed around with few explanations.

Happy coding ❤️
Day 6 - Kth Missing Positive Number
Tags: leetcode, python
Published: 2021-01-06 18:27:40

## The Problem

>Given an array `arr` of positive integers sorted in a strictly increasing order, and an integer `k`.

>Find the `kth` positive integer that is missing from this array.

__Example 1:__

```
Input: arr = [2,3,4,7,11], k = 5
Output: 9
Explanation: The missing positive integers are [1,5,6,8,9,10,12,13,...]. The 5th missing positive integer is 9.
```

__Example 2:__

```
Input: arr = [1,2,3,4], k = 2
Output: 6
Explanation: The missing positive integers are [5,6,7,...]. The 2nd missing positive integer is 6.
```

__Constraints:__

* `1 <= arr.length <= 1000`
* `1 <= arr[i] <= 1000`
* `1 <= k <= 1000`
* `arr[i] < arr[j] for 1 <= i < j <= arr.length`

## My Tests

[Link to code](https://github.com/ruarfff/leetcode-jan-2021)

```python
import pytest
from .Day6 import Solution

s = Solution()


@pytest.mark.parametrize(
    "arr,k,expected",
    [
        ([2, 3, 4, 7, 11], 5, 9),
        ([1, 2, 3, 4], 2, 6),
        ([9, 10, 11, 12], 4, 4),
        ([], 2, 2),
        ([], 0, 0),
        ([3, 10], 2, 2),
    ],
)
def test_find_kth_positive(arr, k, expected):
    assert s.findKthPositive(arr, k) == expected
```

## My Solution

```python
from typing import List


class Solution:
    def findKthPositive(self, arr: List[int], k: int) -> int:
        missing_numbers = 0
        next_expected = 1

        for x in arr:
            while x != next_expected:
                missing_numbers += 1
                if missing_numbers == k:
                    return next_expected
                next_expected += 1
            next_expected += 1

        if len(arr) > 0 and missing_numbers < k:
            return arr[-1] + (k - missing_numbers)

        return k
```

## Analysis

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/nop7z3pen06q0fdxnsw3.png)

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/yzrt0p6g2xturs5701a7.png)

## My Commentary

This one was actually OK. We needed to keep track of the number of missing positive numbers and keep track of the next expected positive number. 

As we go through the list we increment the missing numbers as we find them and then set the next expected to the current number + 1. 

I think I could have used a bit of math here to make this a lot faster but my brain is far too fried to figure that one out right now.

If the `kth` number goes beyond the bounds of the list we handle that later with `arr[-1] + (k - missing_numbers)`.

Finally, we just return `k`. This only happens if the list is empty which we could and maybe should have checked for at top also. 

There is a bit in that loop where I am doing `next_expected += 1` in 2 places which really irks me but I am out of time so leaving it as is.
Detailed template for running a virtual pitch competition
Tags: startup, tutorial, career
Published: 2021-01-06 18:25:25

[Check out a post I wrote detailing the exact steps](https://twitter.com/jackmmcclelland/status/1346870108774232065) the Contrary Boston team took in planning and running our Boston-wide virtual pitch competition in December.

You could use this as inspiration / a template for future virtual pitch competitions, hope it's useful!

Background: Contrary's pitch competition had a couple hundred RSVP's / live attendees, and pitch applications were open to university students and recent alumni (less than two years out of undergraduate and graduate school) from schools in the Boston area. Judges included Jamie Goldstein (Founding Partner @ Pillar VC), Christina Qi (CEO @ Databento), Paul English (Founder & CTO @ Lola.com and KAYAK), and Alexandra Sukin (Investor @ Bessemer). Read more about the ten finalists here.
#Day 22: HackerRank Gold Badge/ 5 star ⭐ for PS
Tags: 100daysofcode, hackerrank, datastructure
Published: 2021-01-06 18:20:45

Finally, I achieved the Gold badge on HackerRank. I must say the questions here are good for beginners to know the new concepts. The questions are not explained so well but the discussion forum helps you to learn a lot from others.

![hackerrnk 5 star](https://dev-to-uploads.s3.amazonaws.com/i/ppt6yukdnw1akxvezg86.png)

Few problems of Medium and Hard level are still left to be completed.
Now I'll switch to LeetCode and Codechef.
Day 4 :100DaysOfCode

Tags: 100daysofcode, productivity, programming
Published: 2021-01-06 18:17:00

Not much today,

Just few basic leetcode ques.
Tried one hashcode problem.
.
.
.
nd EOD.

You can Follow me->
https://github.com/singhtaran1005
https://www.linkedin.com/in/taranpreet-singh-chabbra-27517918a/
How did you break the habit of writing procedural code?
Tags: javascript, beginners, discuss, webdev
Published: 2021-01-06 18:11:48

Procedural programming is the first programming paradigm I learned and felt most comfortable with. Even as I learned functional programming, my code has retained a very top-to-bottom, declarative structure, which is limiting in multiple ways. 

I'm moving on to object oriented programming role, but still resisting the urge to default to procedural. Even with solving code challenges, I've noticed tendency.

What are some ways to break out of this habit?
Dynamic Memory Allocation for NxM (2D) Array Using Pointer | C++
Tags: cpp, dynamic, memory, array
Published: 2021-01-06 17:59:36

### Define `class MxN_matrix`
```cpp
#include <iostream>
using namespace std;

class MxN_Matrix
{
    int row, col;
    int *Matrix;

public:
    MxN_Matrix()
    {
        row = 0;
        col = 0;
    }
    ~MxN_Matrix()
    {
        // deallocate memory
        delete[] Matrix;
    }
    void create(int row, int col);

    void print();
};
```

### `void create(int row, int col)`
```cpp
void MxN_Matrix::create(int row, int col)
{
    this->row = row;
    this->col = col;

    // Dynamically allocate memory of size row*col
    Matrix = new int[row * col];

    // assign values to allocated memory
    for (int i = 0; i < row; i++)
        for (int j = 0; j < col; j++)
        {
            cout << "row = " << i << " col = " << j << ": ";
            cin >> *(Matrix + i * col + j);
        }
}
```

### `void print()`
```cpp
void MxN_Matrix::print()
{
    cout << "\nMatrix" << endl;
    // print the matrix
    for (int i = 0; i < row; i++)
    {
        for (int j = 0; j < col; j++)
            cout << *(Matrix + i * col + j) << "\t"; // or (Matrix + i*col)[j])

        cout << endl;
    }
}
```

### `int main()`
```cpp
int main()
{
    MxN_Matrix *matrix = new MxN_Matrix();

    matrix->create(2, 3);

    matrix->print();

    delete matrix; // deallocate memory

    return 0;
}
```

Also available on YouTube
{% youtube klXl-10oEAY %}