teleren/devto huggingface dataset:
Advent of Code 2020: Python Solution Day 21
Tags: adventofcode, algorithms, python, challenge
Published: 2020-12-21 06:47:59

Today's challenge was very easy but was pretty tricky to tackle. I found the solution to first part by using python sets and for the second part, I used help from [Reddit](https://www.reddit.com/r/adventofcode/comments/khaiyk/2020_day_21_solutions/ggk6wjs?utm_source=share&utm_medium=web2x&context=3).

**Please share your solution too.**
```python
with open("day21.txt") as fp:
    lines = fp.read().splitlines()

food_dict = {}
safe_ingredient = set()
all_ingredients = []
for food in lines:
    ingredients, allergens = food.split(" (contains ")
    allergens = allergens[:-1]
    ingredients = ingredients.split(" ")
    all_ingredients.extend(ingredients)
    unique_in = set(ingredients)
    safe_ingredient=safe_ingredient.union(unique_in)
    allergens = allergens.split(", ")
    
    for allergen in allergens:
        if food_dict.get(allergen) is None:
            food_dict[allergen] = unique_in
        else:
            food_dict[allergen] = food_dict[allergen].intersection(unique_in)

safe_ingredient = safe_ingredient.difference(set(k for value in food_dict.values() for k in value))
safe_count = sum([ingredient in safe_ingredient for ingredient in all_ingredients])
print(f"Safe ingredients: {safe_count}")



while any([len(i) > 1 for i in food_dict.values()]):    
    for a, i in food_dict.items():                      
        if len(i) == 1:                                 
            alg = list(i)[0]                            
            for a2, i2 in food_dict.items():            
                if a2 == a:                             
                    continue                            
                if len(i2) > 1:                         
                    if alg in i2:                       
                        food_dict[a2].remove(alg)       

                                                             

names = list(food_dict.keys())                          
names.sort()                                            
print("My dangerous list: ", ",".join([",".join(food_dict[i]) for i in names]))
```
Boilerplate for React-Typescript projects
Tags: webdev, react, typescript, javascript
Published: 2020-12-21 06:41:24

# Brief description
Starter for React projects following Atomic design structure, i found it clear and intuitive to use and works for most projects.

## Files structure

If you are new and want to learn more about atomic design i suggest reading this blog post: https://medium.com/@WeAreMobile1st/atomic-design-getting-started-916bc81bad0e

![files structure](https://dev-to-uploads.s3.amazonaws.com/i/mgtntpdiyv67weikq8m5.PNG)

**Git clone here:** https://github.com/axibord/react-typescript-starter

## What is included in this boilerplate ?

* Support for both JSX and TSX
* Support for SASS/SCSS using `sass-loader`
* Support for TailwindcssV2 with the help of `postcss-loader`
* Strict linting with Eslint and Prettier configured for typescript
* Finally everything is compiled with Webpack 5 

To run a build for production with minimal bundle size possible make sure to follow the steps in the repository.

### Future improvements
* Support for **scoped** css and sass/scss in each component
* Better Eslint rules by following Airbnb style for exemple
* Improve `tsconfig.json` file for better compilation and debugging
* Tslint instead of Eslint (_not sure its an improvement_)


If you find this helpful, please follow my Twitter [profile](https://twitter.com/Axibord1)

---

Feel free to `git clone` it and tell me what you think, if you have any suggestions and want to contribute just fork it and make a request or reach out to me.
My first Serverless service
Tags: serverless, cloudflare, workers
Published: 2020-12-21 06:33:17

Recently I was going to run a service on [Fandogh Paas](https://www.fandogh.cloud/) with a custom domain and ended up using [Cloudflare](https://www.cloudflare.com/). When setting up stuff something caught my eye: ***Workers***. I knew about the concept of *Serverless* a little but due to the circumstances using *AWS* is somewhat out of reach for me, so why not use this instead?!

I tried to create something with it. But the big question was what to build. Last year I created a little *Discord* bot to retrieve the current AQI of the provided city but since we are not using Discord anymore it's obsolete. Let's do it serverless this time!

The idea of using serverless to just call another API and pass the response on looks a bit redundant, but I guess it's good enough for learning new stuff. So I got an API token from [Air Quality Open Data Platform](https://aqicn.org/api/) and started coding.

There's a fair amount of documents and examples on the [Cloudflare Workers](https://workers.cloudflare.com) site, and of course, you will need enough JavaScript knowledge.

Here's my code :
```
const aqiInfoUrl = "https://api.waqi.info/feed/"

addEventListener('fetch', event => {
  event.respondWith(handleRequest(event.request))
})

/**
 * Respond to the request
 * @param {Request} request
 */
async function handleRequest(request) {
  const queryString = request.url.split('?');
  let city = queryString[1].split('=')[1];

  let response = await getAQIFromAPI(city);
  return new Response(response.data.aqi, {status: 200});
}

async function getAQIFromAPI(city) {
  let fullUrl = aqiInfoUrl + city + '/?token='+ API_TOKEN;
  const response = await fetch(fullUrl);
  return await response.json();
}
```
What it basically does is that when called, tries to find the city from the query string and sends a request to "https://api.waqi.info/feed/" with the provided city and the token which is saved as an environment variable.

It is not the best way it could be written, but I'm very new to this! Please give me your suggestions in the comment section. 


PS: I'm thinking about a Telegram bot using the KV store ... Maybe the next post!
How to cover code coverage for IF/ELSE condition with the node using the JEST unit test
Published: 2020-12-21 06:24:28

We are trying to cover code coverage for the node js function but for the if-else condition, we can't get code coverage, so any idea about that how to cover code coverage for the if-else condition.

Please refer screenshot for sonar code coverage. 

###exports.findMyCompanies = function(user) {return new Promise(function(resolve, reject) {
    
    let query = `SELECT id,name,description,TYPE,website,org_type,linkedin_profile,logo_url,entity_type,(SELECT  count(*) from pages_access as pa where pa.shared_with_org_id = ? and pa.org_id = org.id) as privileges_count FROM organization org WHERE active=true  and org.id in (SELECT  distinct company_org_id org_id from company_advisor where advisor_org_id=?)`;

    dbClient.getConnection().then(function(connection) {
      connection.beginTransaction(function(error_connection, resultData) {
        if (error_connection) {
          dbClient.END_TRANSACTION(connection, "ROLLBACK");
          reject(new Error(error_connection));
          return;
        }

        let orgGetQuery = "select * from `organization` where id=?";
        connection.query(orgGetQuery, [user.org_id], function(err, results) {
          if (err) {
            dbClient.END_TRANSACTION(connection, "ROLLBACK");
            reject(new Error(err));
            return;
          }

          if (
            results.length > 0 &&
            (results[0].type == SYSTEM_ADMIN_ORG ||
              results[0].type == "capitalprovider")
          ) {
            query = `
                SELECT id,
                     name,
                     description,
                     TYPE,
                     website,
                     org_type,
                     linkedin_profile,
                     logo_url,
                     entity_type
                FROM organization org where type='company' and active=true `;
          } else if (results.length < 1) {
            dbClient.END_TRANSACTION(connection, "ROLLBACK");
            reject(new Error("Unknown organization of user"));
            return;
          }

          connection.query(query, [user.org_id, user.org_id], function(
            error_getting_shared_companies,
            results_getting_shared_companies
          ) {
            if (error_getting_shared_companies) {
              dbClient.END_TRANSACTION(connection, "ROLLBACK");
              reject(new Error(error_getting_shared_companies));
              return;
            }

            dbClient.END_TRANSACTION(connection, "COMMIT");
            resolve(results_getting_shared_companies);
          });
        });
      });
    });});};

Jest Unit test case for node js function

it("The function find my company", async () => {

    user = { org_id: "92e1f7fe-93fc-4e51-a86e-8c4962dcef49" };
    await advisor
      .findMyCompanies(user)
      .then(companyData => {
        expect(companyData).not.toBeNull();
      })
      .catch(err => {
        console.log("Error:- ", err);
      });  
});
Project 21 of 100 - Only Fans React Carousel
Tags: react, javascript, html, css
Published: 2020-12-21 06:17:02

*Hey! I'm on a mission to make 100 React.js projects ending March 8th. Please follow my dev.to profile or my [twitter](https://www.twitter.com/jwhubert91) for updates and feel free to reach out if you have questions. Thanks for your support!*

Link to today's deployed app: [link](https://100-react-projects-day-21-only-fans-carousel.netlify.app/)
Link to the repo: [github](https://github.com/jwhubert91/100daysofreact/tree/master/day-21-only-fans)

After a multi-week break from creating daily projects in React I realized yesterday that there were some concepts that I knew but was rusty on, and a few simple practices creating yesterday's project that intimidated me.

I wanted to brush up on some simple skills today and create just the hero section of a simple e-commerce website. This website is dedicated to selling only fans- personal, office, commercial, you name it. The site is called Only Fans (not my original joke I assure you). 

Creating a carousel in React from scratch was surprisingly hard. I've been getting used to writing most of my components to be functional rather than class-based, so I needed to use useState and useEffect to change a number in state later used to reference an image in an array of images.

I found out the hard way that setInterval in React is somewhat tricky because every time the setInterval method counts down, in my case it sets state and thus causes a re-render, which causes an infinite loop. So the solution for this was useEffect. 

See my code below for this rather difficult but neat implementation:

```
function Hero() {
  const [heroImageIdx, setHeroImageIdx] = useState(0);

  const runCarousel = () => {
    const interval = setInterval(() => {
      setHeroImageIdx((prevIdx) => prevIdx + 1);
    }, 5000);
    return () => clearInterval(interval);
  };

  useEffect(() => {
    runCarousel();
  }, []);
  
  return (...)
}
```
Day 21 of JavaScriptmas - Sum of Two Solution
Tags: 24daysofjavascriptmas, scrimba, javascript
Published: 2020-12-21 06:07:35

Day 21 Challenge is to find out does the value is the sum of 2 values that coming from 2 different arrays.

For instance, 
Does `42` is the sum of `2` (that in array_1) and `40` (that in array_2)?
If it does then return `true`, because `42` can be produced from number `2` and `40` that coming from those two array. If not just return `false`

Today, I tested it with 
```javascript
const nums1 = [1, 2, 3];
const nums2 = [10, 20, 30, 40];
const value = 42; 
```

This is the JavaScript Solution
```javascript
function sumOfTwo(nums1, nums2, value) {   
    
    let sum = value;
    
    for(let i=0; i < nums1.length; i++) {
        for(let j=0; j < nums2.length; j++) {
            // console.log(`${nums1[i]} + ${nums2[j]} is ${nums1[i] + nums2[j]}`);  

            // return true if FOUND  
            if(sum === nums1[i] + nums2[j]) {
                return true;
            }   
        }
    }
    
    // return false if NOT found 
    return false;
}
```
How do I add padding lines in IntelliJ?
Tags: java, intellij, watercooler, help
Published: 2020-12-21 05:56:45

The lines are too close to the left and I want to add a padding of at least 3 or 4 pixels. How do I do this?

Also, how can I get a theme, and color-scheme similar to the one I had in VSCode, like the one here?: ![Dark gray bg, with colorful syntax highlighting.](https://dev-to-uploads.s3.amazonaws.com/i/5lhouim3tu75h4kq6s4s.png)

And one more question, how can I have a "view" similar to VSCode, where the side-panel isn't taking up half the fucking window?

<div>
##<b><center><b>Thanks!<br/>Cheers!</b></center></b>
</div>
Speedtest.net on Python!
Tags: python, performance
Published: 2020-12-21 05:51:30

Most of you are probably familiar with https://speedtest.net, a website that measures the speed of your internet connection and reports your download, upload and ping speeds.

Did you know that Speedtest made a Python module for it? It is called `speedtest-cli`, and it's a little old but still works admirably well. I'm going to show you how to use it to measure your network speed from within Python?

What if I told you that this `speedtest-cli` module powers the speedtest-cli command line program as well? The one referenced in their [announcement](https://www.speedtest.net/apps/cli). It may even be powering the main speedtest.net site as well.

So by understanding how this program works, you gain the enormous potential of making something scalable using speedtest.net services.

## Why measure within Python?

There are some advantages to running a speedtest using an API vs. a shell command.

- You can easily parse the output and errors
- No informational output is printed to standard error
- It is easier to pass arguments to an API call than a shell script called from a Python program.

So let's see how this speedtest-cli thing works, shall we?

## The API calls

Installation is dead simple; you just run `pip install speedtest-cli`. This doesn't need it's own section.

Note: installing the speedtest-cli module also installs the speedtest-cli command line program.
 
### Getting a list of servers

```python
import speedtest

s = speedtest.Speedtest()
servers = s.get_servers()
```

This returns 49 speedtest.net servers for now, this number will go up or down depending on if speedtest.net creates and deletes servers, which are hosted by ISPs at their datacenters. The result is a **dictionary** of servers categorized by distance. In other words, the distances are the dictionary keys, and they are floating-point numbers. The best way to iterate through this structure therefore is using `[*s.get_servers().values()]`.

```python
s.get_best_server()
```

Returns the nearest server, the one with the smallest distance.

```python
s.download(threads=None)
s.upload(threads=None, pre_allocate=True)
```

These two functions perform the download and upload tests respectively and return similar structures. The `threads` keyword argument takes a number that determines the number of threads to use for the test. By default it is `None`, which means the speedtest.net server decides how many threads to use.


If `pre_allocate=True` (`upload()` only), then the entire upload data is stored in memory before running the test. This improves the upload performance and thus result somewhat, but it might cause you to run out of memory on small-memory systems, so you can set it to `False` to disable that, and store the upload data piece by piece.

`s.results.share()`

Makes an HTTP POST request to speedtest.net with your results and returns a link to an image of your results, such as this:

![speedtest results as image](https://www.speedtest.net/result/10619143537.png)

## Thanks for reading

If you see any errors in this post, please let me know so I can correct them.
Many bot accounts using 1 Twitter Developer account
Tags: twitter, node, tutorial, codenewbie
Published: 2020-12-21 05:00:08

Hey everyone! Did you know that there's a way to read/write/send messages to other twitter accounts with your Twitter Developer Account? (All discussions below are in context of the Twitter API v1.1)

# How is that possible?🤔

![pic1](https://dev-to-uploads.s3.amazonaws.com/i/g69y57bf0edz2tr5r05g.png) 
In your Twitter Developer Account, you can find:
1. **API key and secret** - belongs to your Twitter App(which you made inside your Twitter Developer Account)
2. **Access token and secret** - belongs to the Twitter Account where you want to tweet/send messages etc..(The Access token & secret given in your Twitter App will let you tweet/send messages etc.. to the Twitter Account which you used to register for a Developer Account)

# How do we do it?👩‍💻

We can get API key & secret from your Twitter App. But how do we get the Access token & secret of your bot account where you want to tweet? Unfortunately, there is no GUI feature currently to support this. We have to make our own server to run the authorisation of the bot account and get access tokens.

1. Go to your [Twitter Developer Account](https://developer.twitter.com/en/portal/dashboard).
2. Create a standalone app - this will give you your API key and secret. You can Choose your App Permissions also here.(For example: Read, Write, and Direct Messages)
3. Enable 3-legged OAuth.
4. Enter the callback URLs and website URLs as:
    * callback URL - http://localhost:3456, http://localhost:3456/auth
    * Website URL - your twitter bot account would do
![pic2](https://dev-to-uploads.s3.amazonaws.com/i/fvf9bfc4apq89lkw6ueg.png)
5. Create a new folder in your computer and create 2 new files - authorize.js and package.json
6. Get the file contents [here](https://gist.github.com/moonmilk/035917e668872013c1bd).
7. In your terminal, run `npm install` to install the Nodejs dependencies.
8. Run `node authorize.js` to start the server.
9. Double check that you are logged in to your Twitter bot account and visit http://localhost:3456.
10. Click "authenticate"
11. You will be redirected to a page where you can collect your Access token & secret.
12. Yay! Now you can tweet in your bot account.🤖
13. Still a bit worried whether your Twitter app has been connected to your Bot account? Still logged in to your bot account, go to https://twitter.com/settings/connected_apps to see if your Twitter App is connected.

# Conclusion:

Congrats! You can now control your bot account with a single Twitter Developer Account.

![f85547cc09fbd80b484f656ea30b7eab](https://dev-to-uploads.s3.amazonaws.com/i/6kjlrmh10x1xkq93giey.gif) 

# References:
1. https://gist.github.com/moonmilk/035917e668872013c1bd
2. https://twittercommunity.com/t/multiple-bot-accounts/128332/2
Why my Magento 2 is not generating Gifcard's code?
Tags: magento, ecommerce
Published: 2021-05-05 21:19:21

---
title: Why my Magento 2 is not generating Gifcard's code?
published: true
date: 2020-12-21 05:00:00 UTC
tags: Magento,ecommerce
canonical_url: https://blog.rafaelcg.com/why-my-magento-2-is-not-generating-giftcards-code
---

Analyzing some orders workflow to a client we saw that in some orders the gift card code wasn’t generated. Inside the order’s details, it was showing as below.

**Gift Card Accounts: N/A**

Analyzing the situation it was caused because of one specific payment method, it was set as Authorize only and not Authorize & Capture, the gif card code is generated only when the invoice is created.

So if you did a test order and didn’t have the gift card code, try to invoice it, you will receive a new email with the code.

To check all the Giftcard codes generated you can go to the admin panel in **Marketing > Promotions > Gift Card Account**.

If you can you might able to fix it by changing the payment method to Authorize & Capture or restricting the payment methods allowed to buy the gift cards.
What kind of developer are you?
Tags: discuss, watercooler, programming
Published: 2020-12-21 04:43:04

Introduction
---
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/wuhzze0mss8frjkzttrt.gif)

**Developers come in all size, shapes & flavours but which one is you?**

One of the ways to better understand your style, approach & way of working, is to see what kind of work you are into & what type of development you actually like.

So, are you one of those badass **Backend Developers** who love to get their hands dirty with a lot of amazing stuff that happens behind the scenes OR you are that artistic **Frontend Developer** guy with the magic touch to transform any piece of code into stunning design? OR you are just a flawless mixture of both worlds as a **Full-stack Developer**?


Let me start
---
- I am most probably a Full-stack Developer, although I used to love Frontend more, I personally had issues with Backend during my college days.😂
- I think Frontend is beginner-friendly as anyone can easily get started with it.

I know it's really hard to pick which one is better because as we know, there can never be a satisfying answer for this as both fields, Frontend as well as Backend, are required for Development of impactful services, and without one of them, the existence of other will be pointless.

Now it's your turn to share your opinion on this & which type of Development you prefer and with which one you actually started with...

Discuss
---
- Which kind of developer for you? 🤔
- How you got started? 🐱‍🏍
- How was your experience? 🙌
- Any mixed feelings or regrets you have? 🥺
Simplifying Auth With Static Web Apps and React
Tags: javascript, azure, serverless, auth
Published: 2021-01-11 04:58:26

---
title: Simplifying Auth With Static Web Apps and React
published: true
date: 2020-12-21 04:41:00 UTC
tags: javascript,azure,serverless,auth
canonical_url: https://www.aaron-powell.com/posts/2020-12-21-simplifying-auth-with-static-web-apps-and-react/
---

It’s no secret that I’m a fan of [Azure Static Web Apps](https://docs.microsoft.com/azure/static-web-apps/?WT.mc_id=javascript-12079-aapowell) and I’m constantly looking for ways to make it easier for people to get working with it.

Something I hadn’t done much with until recently was work with the [Authentication and Authorization](https://docs.microsoft.com/azure/static-web-apps/authentication-authorization?WT.mc_id=javascript-12079-aapowell) aspect of it; I knew it was there, but I wasn’t building anything that required it.

While [building a video chat app](https://dev.to/azure/building-a-video-chat-app-part-1-setup-l71) on [Twitch](https://twitch.tv/NumberOneAaron) I found myself jumping back and forth to the documentation to make sure that I was creating the login URLs correctly, loading the profiles, etc. and so it’s time to do something about it.

## Introducing `react-static-web-apps-auth`

I created a npm package, [`@aaronpowell/react-static-web-apps-auth`](https://www.npmjs.com/package/@aaronpowell/react-static-web-apps-auth), which helps simplify development.

It introduces a component, `<StaticWebAppsAuthLogins />`, which will display all the auth providers (you can hide them by setting their corresponding prop to `false`), as well as a `<Logout />` component and a React Context provider, `<UserInfoContextProvider>`, to give up access to the current user profile.

If you’re interested in the process of building it, I streamed that, including setting up a GitHub Actions pipeline with package deployment ([like I blogged recently](https://dev.to/aaronpowell/deploy-to-github-packages-with-github-actions-1274)).

{% youtube MjHRSueoNsM %}