teleren/devto huggingface dataset:
This Week in Python (July 08, 2022)
Published: 2022-07-15 08:52:39

---
title: This Week in Python (July 08, 2022)
published: true
date: 2022-07-08 12:00:00 UTC
tags: 
canonical_url: https://bas.codes/posts/this-week-python-019
---

 **Fri, July 08, 2022**

This Week in Python is a concise reading list about what happened in the past week in the Python universe.

## [<svg aria-hidden="true" focusable="false" height="16" version="1.1" viewbox="0 0 16 16" width="16"><path fill-rule="evenodd" d="M4 9h1v1H4c-1.5 0-3-1.69-3-3.5S2.55 3 4 3h4c1.45 0 3 1.69 3 3.5 0 1.41-.91 2.72-2 3.25V8.59c.58-.45 1-1.27 1-2.09C10 5.22 8.98 4 8 4H4c-.98 0-2 1.22-2 2.5S3 9 4 9zm9-3h-1v1h1c1 0 2 1.22 2 2.5S13.98 12 13 12H9c-.98 0-2-1.22-2-2.5 0-.83.42-1.64 1-2.09V6.25c-1.09.53-2 1.84-2 3.25C6 11.31 7.55 13 9 13h4c1.45 0 3-1.69 3-3.5S14.5 6 13 6z"></path></svg>](#python-articles)Python Articles

- [Procedural music composition with Python](https://deepnote.com/@essia/Procedural-music-composition-with-arvo-9b35ebd7-63e0-47bc-a3d5-c503954a083d)
- [Design Patterns in Machine Learning Code and Systems](https://eugeneyan.com/writing/design-patterns/)
- [5 Levels of Handling Date and Time in Python](https://medium.com/techtofreedom/5-levels-of-handling-date-and-time-in-python-46b601e47f65)
- [A recipe recommendation system](https://duarteocarmo.com/blog/scandinavia-food-python-recommendation-systems)
- [10 Python Image Manipulation Tools You Can Try Today](https://builtin.com/data-science/python-image-processing)

## [<svg aria-hidden="true" focusable="false" height="16" version="1.1" viewbox="0 0 16 16" width="16"><path fill-rule="evenodd" d="M4 9h1v1H4c-1.5 0-3-1.69-3-3.5S2.55 3 4 3h4c1.45 0 3 1.69 3 3.5 0 1.41-.91 2.72-2 3.25V8.59c.58-.45 1-1.27 1-2.09C10 5.22 8.98 4 8 4H4c-.98 0-2 1.22-2 2.5S3 9 4 9zm9-3h-1v1h1c1 0 2 1.22 2 2.5S13.98 12 13 12H9c-.98 0-2-1.22-2-2.5 0-.83.42-1.64 1-2.09V6.25c-1.09.53-2 1.84-2 3.25C6 11.31 7.55 13 9 13h4c1.45 0 3-1.69 3-3.5S14.5 6 13 6z"></path></svg>](#projects)Projects

- [ast\_selector](https://github.com/guilatrova/ast_selector) – Query Python AST elements by using CSS Selector-like syntax
- [datamodel-code-generator](https://github.com/koxudaxi/datamodel-code-generator) – Pydantic model generator for easy conversion of JSON, OpenAPI, JSON Schema, and YAML data sources.
- [red-engine](https://github.com/Miksus/red-engine) – Modern scheduling library for Python
- [MostMinimalWebFramework](https://github.com/kadircancetin/MostMinimalWebFramework) – Most Minimal Python Web Framework
- [more-itertools](https://github.com/more-itertools/more-itertools) – More routines for operating on iterables, beyond itertools
Block scope in javascript
Tags: webdev, javascript, beginners, tutorial
Published: 2022-07-08 11:43:00

As discussed in the [last post](https://dev.to/aishanipach/let-const-in-js-3841), let & const keywords behave differently. You may have seen a point difference between them and var written as "let & const are block scoped".

But what is **block**.

Anything enclosed in braces `{}` is block. Basically, when we bunch together a couple of statements which js perceives as 1, that is a block.

```
{
}
```
*Classic example of a perfectly normal javascript code*😌

Let's take an example:
```
{
   let x=9;
   const y=10;
   var z=0;
}
console.log(z)
console.log(y)
console.log(x)
```

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/eg05f9n9qmgxzsd6kkxq.jpeg)
Output shows that only `var z` can be accessed. This is because when hoisted, z is allocated space in global space while let & const are allocated memory in `block space` which is available only inside the block.

Wh
Another example:
```
let x=100;
const y=98;
var z=78;

{
   let x=9;
   const y=10;
   var z=0;
   console.log(x)
   console.log(y)
   console.log(z)
}

console.log("Outside:")
console.log(x)
console.log(y)
console.log(z)
```

In this case:

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

The value of the `var z` outside the block is changed too but `x & y` outside the block have the same original value. 

This is because the z is pointing to same location in global space in both cases but x & y inside the block are in block memory space and x &y outside are in separate memory space. This is called **shadowing**.


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2c14qhah97b3hdpfy6jy.jpeg)
(Yes, I used light mode in ages, "until next time I want to burn my eyes light mode!")

But remember if we make it a function even var value won't be changed. As functions behave as seperate sub program and each has it's own execution context.

> You **cannot shadow a let declared data with var keyword**. Using `let k=10` outside the block and then `var k=10` inside will throw  a syntax error
>[⭐ Lexical scope in Javascript](https://www.educative.io/answers/lexical-scope-in-javascript)
Position elements.Absolute, fixed and sticky
Tags: position, absolute, fixed, sticky
Published: 2022-07-08 11:42:45

**Position** is used to make the element settle at a place in the page layout. 
Absolute, fixed and sticky are values to CSS position property.

Absolute: Element with position absolute is removed from the document. And no space is created for absolute element. It set in the page based on its nearest positioned ancestor. Otherwise, it is placed relative with its initial containing block. Final positions of the absolute element are set using top, left, right and bottom values.
Ex: place an element in element at a particular height, close icons modals.

Fixed: Fixed elements is removed from the normal document flow, and no space is created for the element in the page layout. It is positioned relative to the initial containing block(body/document). final position of fixed element will be also set using the top, left,right and bottom values.
Ex: chat icons, headers, bottom, navbars.

Sticky:  Element with sticky value is positioned according to the normal flow in the document. and then offsets relative to its nearest scrolling ancestor and containing block. Even though the element is in the document its offset position does not effect the nearest elements. A sticky element "sticks" to its nearest ancestor that has a "scrolling mechanism". even if that ancestor isn't the nearest actually scrolling ancestor.
Sticky element works can be visualised only when the immediate ancestor has scrolling.  

Ex: Scrollable headers, side headings, tab bars headers.

Reference:  https://developer.mozilla.org/en-US/docs/Web/CSS/position
129. Leetcode Solution in CPP
Tags: cpp
Published: 2022-07-08 11:32:37

```
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
 public:
  int sumNumbers(TreeNode* root) {
    int ans = 0;
    dfs(root, 0, ans);
    return ans;
  }

 private:
  void dfs(TreeNode* root, int path, int& ans) {
    if (!root)
      return;
    if (!root->left && !root->right) {
      ans += path * 10 + root->val;
      return;
    }

    dfs(root->left, path * 10 + root->val, ans);
    dfs(root->right, path * 10 + root->val, ans);
  }
};

```
#leetcode
#challenge
here is the link for the problem:
https://leetcode.com/problems/sum-root-to-leaf-numbers/
137. Leetcode Solution in CPP
Tags: cpp
Published: 2022-07-08 11:29:11

```
class Solution {
 public:
  int singleNumber(vector<int>& nums) {
    int ans = 0;

    for (int i = 0; i < 32; ++i) {
      int sum = 0;
      for (const int num : nums)
        sum += num >> i & 1;
      sum %= 3;
      ans |= sum << i;
    }

    return ans;
  }
};

```
#leetcode
#challenge
here is the link for the problem:
https://leetcode.com/problems/single-number-ii/
165. Leetcode Solution in CPP
Tags: cpp
Published: 2022-07-08 11:26:22

```
class Solution {
 public:
  int compareVersion(string version1, string version2) {
    istringstream iss1(version1);
    istringstream iss2(version2);
    int v1;
    int v2;
    char dotChar;

    while (bool(iss1 >> v1) + bool(iss2 >> v2)) {
      if (v1 < v2)
        return -1;
      if (v1 > v2)
        return 1;
      iss1 >> dotChar;
      iss2 >> dotChar;
      v1 = 0;
      v2 = 0;
    }

    return 0;
  };
};

```
#leetcode
#challenge
here is the link for the problem:
https://leetcode.com/problems/compare-version-numbers/
172. Leetcode Solution in CPP
Tags: cpp
Published: 2022-07-08 11:23:51

```
class Solution {
 public:
  int trailingZeroes(int n) {
    return n == 0 ? 0 : n / 5 + trailingZeroes(n / 5);
  }
};
```
#leetcode
#challenge
here is the link for the problem:
https://leetcode.com/problems/factorial-trailing-zeroes/
54. Leetcode Solution in CPP
Tags: cpp
Published: 2022-07-08 11:17:47

```
class Solution {
 public:
  vector<int> spiralOrder(vector<vector<int>>& matrix) {
    if (matrix.empty())
      return {};

    const int m = matrix.size();
    const int n = matrix[0].size();
    vector<int> ans;
    int r1 = 0;
    int c1 = 0;
    int r2 = m - 1;
    int c2 = n - 1;

    // repeatedly add matrix[r1..r2][c1..c2] to ans
    while (ans.size() < m * n) {
      for (int j = c1; j <= c2 && ans.size() < m * n; ++j)
        ans.push_back(matrix[r1][j]);
      for (int i = r1 + 1; i <= r2 - 1 && ans.size() < m * n; ++i)
        ans.push_back(matrix[i][c2]);
      for (int j = c2; j >= c1 && ans.size() < m * n; --j)
        ans.push_back(matrix[r2][j]);
      for (int i = r2 - 1; i >= r1 + 1 && ans.size() < m * n; --i)
        ans.push_back(matrix[i][c1]);
      ++r1, ++c1, --r2, --c2;
    }

    return ans;
  }
};

```

#leetcode
#challenge
here is the link for the problem:
https://leetcode.com/problems/spiral-matrix/
1706. Leetcode Solution in CPP
Tags: cpp
Published: 2022-07-08 11:11:40

```
class Solution {
 public:
  vector<int> findBall(vector<vector<int>>& grid) {
    const int m = grid.size();
    const int n = grid[0].size();
    // dp[i] := status of i-th column
    // -1 := empty, 0 := b0, 1 := b1, ...
    vector<int> dp(n);
    // ans[i] := i-th ball's final position
    vector<int> ans(n, -1);

    iota(begin(dp), end(dp), 0);

    for (int i = 0; i < m; ++i) {
      vector<int> newDp(n, -1);
      for (int j = 0; j < n; ++j) {
        // out of bound
        if (j + grid[i][j] < 0 || j + grid[i][j] == n)
          continue;
        // stuck
        if (grid[i][j] == 1 && grid[i][j + 1] == -1 ||
            grid[i][j] == -1 && grid[i][j - 1] == 1)
          continue;
        newDp[j + grid[i][j]] = dp[j];
      }
      dp = move(newDp);
    }

    for (int i = 0; i < n; ++i)
      if (dp[i] != -1)
        ans[dp[i]] = i;

    return ans;
  }
};

```
#leetcode
#challenge
here is the link for the problem:
https://leetcode.com/problems/where-will-the-ball-fall/
Importance of A Mobile App in Business!
Published: 2022-07-05 11:29:34

people spend most of their online time on mobile devices (51% of mobile digital media time in the US alone). So yes, if you’re not mobile, you will lose customers. But being mobile doesn’t necessarily imply investing in mobile app development.

A mobile-friendly business can follow two main paths: custom mobile app (native software) or the mobile web. A native application comes with lots of advantages such as easy push notifications, access to the hardware, and better performance. However, many businesses choose the mobile web and here’s why.

Adding Value to the Customer Experience
Before you start making calls to find a professional graphic designer that can build an awesome template for your app, stop and think. Will the app bring value to your customers’ experience? Are they going to use it to improve their day-to-day activities?

If the answer to these questions is ‘no’, then you probably don’t need an app. No one is going to download and install it if all it does is promote your products. You can still do this by using the mobile web and you have a better chance of getting new clients this way.

What will it do?
The main aspect you need to figure out in mobile app development is the purpose of the app. So what do you plan on doing with your app? Will you help users find your locations all over the country? Or maybe you’ll help them find products and compare prices.

Regardless of purpose, make sure you understand it clearly before you hire web development services. If you can’t clearly define a role for your app, then you should reconsider creating one.

How is it different from your site?
The site is a must-have these days, and it must be responsive. This means your user-interface will adapt to any screen type and resolution. So why do you need an app then?

If the custom mobile app you plan on developing doesn’t bring anything new compared to the site, then the app will be redundant.

How will an App benefit your Business?
As a Milwaukee-based web design company we’ve also seen many businesses benefit from their apps so let’s take a look at their real potential:

Camera usage – an app allows the user to take pictures of your products and share them on social media channels
Push notifications – you have direct access to your client’s phone and you can notify them of sales as they walk by your shop
You can implement a system where the app communicates with your store’s system to let you know the name and preferences of the client who just walked in
An app can offer discounts according to a customer’s social influence in regards to your products
Apps can offer customers the possibility to virtually try a product and test its features.
202. Leetcode Solution in Cpp
Tags: cpp
Published: 2022-07-08 10:47:29

```
class Solution {
public:
    map<int, int> terminate;
    bool isHappy(int n) {
        int temp = 0;
        if(n==1){
            return 1;
        }
        while(n!=0){
            temp += pow(n%10, 2);
            n = n/10;
        }
        
        if(terminate[temp] == 0){
            terminate[temp] = 1;
        } else{
            return 0;
        }
        return isHappy(temp);
    }
};
```
#leetcode
#challenge
here is the link for the problem:
https://leetcode.com/problems/happy-number/
React Bootcamp Note Taking App by Smit Shetye.
Tags: codesandbox, smitshetye, react, devtown
Published: 2022-07-08 10:51:59

{% codesandbox ug4pmc %}
React Bootcamp Note Taking App by Smit Shetye. https://codesandbox.io/s/reactbootcampsmitshetye-ug4pmc?fontsize=14&hidenavigation=1&theme=dark 
#smitshetye #shetyesmit #smitshetyelab #devtown
LeetCode - Contains Duplicate
Tags: java, leetcode, containsduplicate, solution
Published: 2022-07-08 10:51:42

Given an integer array nums, return true if any value appears at least twice in the array, and return false if every element is distinct.

Example 1:
`Input: nums = [1,2,3,1]
Output: true`

Example 2:
`Input: nums = [1,2,3,4]
Output: false`

Example 3:
`Input: nums = [1,1,1,3,3,4,3,2,4,2]
Output: true`

**Constraints:**

1 <= nums.length <= 105
-109 <= nums[i] <= 109

**Solution:**

```
class Solution {
    public boolean containsDuplicate(int[] no) {
         if(no==null || no.length==0)
        return false;
 
    HashSet<Integer> set = new HashSet<Integer>();
    for(int i: no){
        if(!set.add(i)){
            return true;
        }
    }
 
    return false;
        
    }
}
```

Fore more solutions [LeetCode](https://leetcode.com/VaishnveeShinde/)
Gitlab Runner errors and solutions
Tags: gitlab, runner, ci, cd
Published: 2022-07-08 10:50:00

## Error 1) open /root/.ssh/known_hosts: no such file or directory

```
Using SSH executor...

ERROR: Preparation failed: ssh command Connect() error:
getting host key callback: open /root/.ssh/known_hosts: 
no such file or directory

Will be retried in 3s ...
```

### Solution:

Follow the steps to resolve:

1) Login to `gitlab` instance via SSH
2) Become `sudo` via:
```
sudo su
```
3) Now, you need to connect gitlab instance to the host where runner is try to connect
```
ssh <host-username>@<host-ip>
```

`<host-username>` and `<host-ip>` should match with the `gitlab runner`, it will ask for `password` then it will ask to accept `key fingerprint`.

Now, try to run the job with the runner. It should be working

<hr/>

## Error 2) Job failed: prepare environment: Process exited with status 1.

If you are getting following error in your when running gitlab ci/cd job via `gitlab-runner`:


```
ERROR: Job failed: prepare environment: Process exited with status 1. 
Check https://docs.gitlab.com/runner/shells/index.html#shell-profile-loading 
for more information
```

### Solution:

Run following commands on the server where gitlab runner trying to login:
```
find / -name .bash_logout
```

and delete following files if exist

```
sudo rm -r /home/gitlab-runner/.bash_logout
sudo rm -r /home/<username>/.bash_logout
```

Try to re-run the jobs it should be working.

<hr/>

## Error 3) handshake failed: knownhosts: key is unknown

```
ERROR: Preparation failed: ssh command Connect() error: ssh Dial() error: ssh: handshake failed: knownhosts: key is unknown
```

### Solution:

#### Solution A

Verify your login credentials

#### Solution B

Verify that SSH port is open

#### Solution C

Edit your runner and add `disable_strict_host_key_checking = true`

```sh
sudo nano /etc/gitlab-runner/config.toml
```

```
[[runners]]
  name = "..."
  url = "..."
  token = "..."
  executor = "ssh"
  [runners.custom_build_dir]
  [runners.cache]
    [runners.cache.s3]
    [runners.cache.gcs]
    [runners.cache.azure]
  [runners.ssh]
    user = "..."
    password = "..."
    host = "..."
    port = "..."
    disable_strict_host_key_checking = true
```

Then restart the `gitlab-runner`

```
sudo gitlab-runner restart
```

#### Solution D

If you're using `WHM` as your hosting control panel, enable following settings:
```
SSH Password Authorization Tweak
```
How to easily rebuild an app after editing a resource?
Tags: mulesoft
Published: 2022-07-08 10:48:17

When editing resource files in [Anypoint Studio](https://www.mulesoft.com/platform/studio) such as the log configuration, property files, or DataWeave files, you probably noticed that the application is not automatically rebuilt and deployed by the Studio. This is because the Studio only tracks files in `src/main/mule` or files that are used as [resources of a Transform Message component](https://docs.mulesoft.com/mule-runtime/4.4/transform-move-transformations-separate-file-studio-task).

This is very inconvenient as starting a new runtime can take a very long time, even with good hardware. Fortunately, there is an easy way to manually trigger the build and redeployment of one or multiple applications that are already running.

Let me show you how to redeploy your app easily. First, open the Project menu and select "Clean...":

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

This opens a window where I can either clean all projects, triggering a rebuild of all projects, or select one or more projects that I want to rebuild:

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6ekh67jvlfrqbw9at8uc.png)

In this screenshot, only my Experience API will be rebuilt. If the application was already deployed, the runtime will now automatically redeploy it without restarting the whole runtime.

**Tip**: if your application does not automatically redeploy after editing a Mule Configuration File, make sure "Build Automatically" is checked in the Project menu (see the first screenshot above).
202. Leetcode Solution in Python
Tags: python
Published: 2022-07-08 10:45:57

```
class Solution(object):
    def isHappy(self, n, prev=[]):
        nums = sum([int(x)**2 for x in list(str(n))])
        if nums in prev:
            return False
        return self.isHappy(nums, prev+[nums]) if nums != 1 else True
```

#leetcode
#challenge
here is the link for the problem:
https://leetcode.com/problems/happy-number/
Talk @ Databricks Data and AI Summit 2022-”Machine Learning Hyper-Productivity with Transformers…
Tags: transformers, huggingface, machinelearning, nlp
Published: 2022-07-11 11:39:02

---
title: Talk @ Databricks Data and AI Summit 2022-”Machine Learning Hyper-Productivity with Transformers…
published: true
date: 2022-07-08 10:28:48 UTC
tags: transformers,huggingface,machinelearning,nlp
canonical_url: https://julsimon.medium.com/talk-databricks-data-and-ai-summit-2022-machine-learning-hyper-productivity-with-transformers-8ad23865d583
---

### Talk @ Databricks Data and AI Summit 2022-”Machine Learning Hyper-Productivity with Transformers and Hugging Face”

According to the latest State of AI report, “transformers have emerged as a general-purpose architecture for ML. Not just for Natural Language Processing, but also Speech, Computer Vision or even protein structure prediction.” Indeed, the Transformer architecture has proven very efficient on a wide variety of Machine Learning tasks. But how can we keep up with the frantic pace of innovation? Do we really need expert skills to leverage these state-of-the-art models? Or is there a shorter path to creating business value in less time?

In this code-level talk, we’ll gradually build and deploy a demo involving several Transformer models. Along the way, you’ll learn about the portfolio of open source and commercial Hugging Face solutions, how they can help you become hyper-productive in order to deliver high-quality Machine Learning solutions faster than ever before.

{% youtube dYRAUziei1U %}

New to Transformers?

- [https://huggingface.co/tasks](https://huggingface.co/tasks)
- [https://huggingface.co/course](https://huggingface.co/course)
- [https://discuss.huggingface.co](https://discuss.huggingface.co)
Talk @ PyData London 2022 — “Machine Learning 2.0 With Hugging Face”
Tags: huggingface, nlp, machinelearning, deeplearning
Published: 2022-07-11 11:39:21

---
title: Talk @ PyData London 2022 — “Machine Learning 2.0 With Hugging Face”
published: true
date: 2022-07-08 10:26:39 UTC
tags: huggingface,nlp,machinelearning,deeplearning
canonical_url: https://julsimon.medium.com/talk-pydata-london-2022-machine-learning-2-0-with-hugging-face-a78c8c680a86
---

### Talk @ PyData London 2022 — “Machine Learning 2.0 With Hugging Face”

In this session, we’ll introduce you to Transformer models and what business problems you can solve with them. Then, we’ll show you how you can simplify and accelerate your machine learning projects end-to-end: experimenting, training, optimizing, and deploying. Along the way, we’ll run some demos to keep things concrete and exciting!

{% youtube Hz4t_rAtdxg %}

New to Transformers?

- [https://huggingface.co/tasks](https://huggingface.co/tasks)
- [https://huggingface.co/course](https://huggingface.co/course)
- [https://discuss.huggingface.co](https://discuss.huggingface.co)
Naya Tab: A NEW TAB Browser extension like Brave Browser's new tab page
Tags: showdev, webdev, javascript, productivity
Published: 2022-07-08 10:07:24

I created this browser extension called "Naya Tab".

This new tab extension adds functionality similar to the brave browser's new tab page.

You can add shortcuts to websites and change wallpaper for the new tab page.


![1](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1jxtdpnywygi97oy5hxr.png)

![2](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/b88v7qy5di47i65su6xr.png)

![3](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/fd4dv6hs8jlqaf2ki6d5.png)

![4](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/d31xdewue1mc6kcplulc.png)

I was trying to publish it on Chrome Webstore but unfortunately I ran into some payment related issues so for now it's only available for firefox & edge.

You can install it on Firefox & Edge by visiting: 

https://addons.mozilla.org/en-US/firefox/addon/naya-tab/

https://microsoftedge.microsoft.com/addons/detail/naya-tab-a-new-tab-exte/nclaeoangfbocckefkmmiabicmfcpolg

---

You can support me at: https://github.com/sponsors/sharadcodes
for India UPI: `iamsharadraj@okaxis`

---

I will make it open source once it get published on chrome and edge webstore.