teleren/devto huggingface dataset:
Day 25 Of 100DaysOfCode : Python Decorators
Tags: 100daysofcode, codenewbie, beginners, python
Published: 2021-01-18 14:20:07

This is my 25th day of #100DaysOfCode and Python. Today I am not able to give my  time more than 2 hours. Because of my own personal work. So I learned something about python decorators. And Tried to do some code on it.

Some of the code which I practice today and tried to write are given below.

# Some Simple Code On Python Decorators

While I studied I learned that python has a interesting features called decorators to add functionality to an existing code. This is also called meta programming because a part of the program tried to modify another part of program.

```python
def make_pretty(func):
    def inner():
        print("I got decorated")
        func()
    return inner


def ordinary():
    print("I am ordinary")

pretty = make_pretty(ordinary)
pretty()
```
When this program run its output is

```python
I got decorated
I am ordinary
```
In the above code `make_pretty` is decorator, ordinary got decorated and returned function was given by the name preety.

```python
def smart_divide(func):
    def inner(a, b):
        print("I am going to divide", a, "and", b)
        if b == 0:
            print("Whoops! cannot divide")
            return

        return func(a, b)
    return inner


@smart_divide
def divide(a, b):
    print(a/b)

divide(2,0)
```
Above function is the example of decorator with parameter. Here a and b are two parameter .

Here is some other example of decorators,

```python
def printer(text):
    print(text)
printer = star(percent(printer))

printer('Durga')
```
Output of this code is

```python
******************************
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Durga
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
******************************
```
<blockquote class="twitter-tweet"><p lang="en" dir="ltr">Day 25 of <a href="https://twitter.com/hashtag/100DaysOfCode?src=hash&amp;ref_src=twsrc%5Etfw">#100DaysOfCode</a> and <a href="https://twitter.com/hashtag/Python?src=hash&amp;ref_src=twsrc%5Etfw">#Python</a> <br>* Python functions , Argument and Parameter<br>* Python Higher Order Function <br>* Python Decorators <br>* Some Simple Code On Python Decorators Tried To Learn Today<a href="https://twitter.com/hashtag/100DaysOfCode?src=hash&amp;ref_src=twsrc%5Etfw">#100DaysOfCode</a> ,<a href="https://twitter.com/hashtag/CodeNewbie?src=hash&amp;ref_src=twsrc%5Etfw">#CodeNewbie</a> ,<a href="https://twitter.com/hashtag/beginner?src=hash&amp;ref_src=twsrc%5Etfw">#beginner</a> ,<a href="https://twitter.com/hashtag/Python?src=hash&amp;ref_src=twsrc%5Etfw">#Python</a> <a href="https://t.co/t302xx1TlK">pic.twitter.com/t302xx1TlK</a></p>&mdash; Durga Pokharel (@mathdurga) <a href="https://twitter.com/mathdurga/status/1351166442511724552?ref_src=twsrc%5Etfw">January 18, 2021</a></blockquote> <script async src="https://platform.twitter.com/widgets.js" charset="utf-8"></script>
Local Hack Day: BUILD and why you should join it?
Tags: mlhgrad, localhackday, codenewbie, hackathon
Published: 2021-01-18 14:12:54

So as the weeklong grand hackathon organized by Major League Hacking comes to an end, I am feeling a cocktail of emotions. I am exhausted, happy, sad and excited. being a newbie in the field of coding and hackathons, I had a vague idea as to what exactly I would be expected to build at this hackathon. Nonetheless, I joined the hackathon and now I can confidently say that I am a more experienced programmer than I was a week ago.
the hackathon not only had workshops to help you build something that you can gladly show off on your resume, it also had mini-events such as "Cup-stacking" and "Chrome-Dino Game"(which i am surprisingly good at) to help you relax and take a break from an otherwise busy schedule.
I learned a new language called "EmojiCode" , built a chess game in Java, built a tic-tac-toe game, and also followed tutorials to build something and earn points. One of the most important and relevant experience I had was networking. Networking with people I had not known before and competing with a guild made me more confident in my abilities. And I gotta tell you the joy and rush you get when you see your name on the leaderboard is something I cannot convey in words.
And if this is not enough to get you to participate in such hackathons , I have one last thing to motivate you... SWAGS. yes, you read it right for each and every hacker who completes a single challenge, MLH provides stickers and masks that you can deck out on your laptop and show off.

 Now, here are a list of few hackathons that you can attend even if you missed out on LHD: Build. Remember that it is never too late or never too early to take part in a hackathons. There are hackathons for high-school students as well so you should definitely be on a lookout for such events:
1. HackTheNorthEast
2. RoseHacks
3. HackDavis
4. ElleHacks
5. HackViolet

And many more..
You can check out various hackathons at https://mlh.io/

Keep LEARNING. Keep CODING.
Personal Spending Tracker
Tags: mongodb, react, node, javascript
Published: 2021-01-18 14:09:08

Hey DEV.to. For the past 2-3 weeks (mostly over weekends) I was working on one of my personal project. It got me so intensively so I said to myself "You really need to finish this first, before anything else". Well today I finished it. 

To not talk about some "feelings around" let's get into it...

I've build Personal Spending Tracker in MERN stack deployed on Heroku. For those who never heard about it MERN stands for MongoDB,ExpressJS,React,Node.


In more tech way I used the MongoDB to handle my database stuff like user-registration, user-login, adding spending into dashboad, quering and summarising data on the dashboard.

Then for my BE(backend) I've used ExpressJS and Node to handle my endpoints which are being called from Front End also handling security with loooooads of useful node modules most like known as npm modules like HelmetJS and so on...

Aaand at the end I was running ReactJS on the Front End.

App is currently supporting adding and displaying your overall spending and some small statistics like "total spend" and "most expensive item so far". Sooner or later I will add some more functionality for it :)

If you would like to review the app here's the link:
[App here](https://budget-manager-app28.herokuapp.com/)
Running Rust in WebAssembly in a Pool of Concurrent Web Workers in JavaScript
Tags: showdev, javascript, webdev, rust
Published: 2021-01-18 14:06:12

---
title: "Running Rust in WebAssembly in a Pool of Concurrent Web Workers in JavaScript"
published: true
description: "A mad experiment: distributing a heavy task over a pool of web workers which call a rust library compiled to WebAssembly."
tags: showdev, javascript, webdev, rust
canonical_url: https://alesgenova.github.io/concurrent-wasm-workers/
cover_image: https://dev-to-uploads.s3.amazonaws.com/i/k0fudj2h5len0zng3875.png
---

> _Your scientists were so preoccupied with whether or not they could, that they didn't stop to think whether they should._


I would like to share a little experiment I did for no other reason than to show I could.

In this proof of concept, the main application starts a pool of web workers that it later uses to offload a series of heavy tasks.

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

The task in question is to to render a single frame of a simple 3D scene using ray-tracing (path-tracing). The computationally intensive rendering is performed by a `rust` library compiled to WebAssembly.

These are the tools I used:
- {% github alesgenova/post-me no-readme %}
- {% github alesgenova/ray-tracer no-readme %}
- {% github rustwasm/wasm-bindgen no-readme %}
- Small in-house task queue to dispatch tasks to workers when available.
- `react` for the skeleton of the app.

If you would like to run this madness, an instance of this application is deployed [here](https://alesgenova.github.io/ray-tracer-app/).

[![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/lzmn68bd61pl8ujwysdj.gif)](https://alesgenova.github.io/ray-tracer-app/)

If you would like to see the details of the implementation, you can find the source code of the app on [Github](https://github.com/alesgenova/ray-tracer-app)

## Bonus

Using a similar approach, I also created an app that can detect the pitch of sounds being captured by the device's microphone.

[Try it out ](https://alesgenova.github.io/pitch-detection-app/)

[![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/o2k6nvswa0qft7f3m6wa.gif)](https://alesgenova.github.io/pitch-detection-app/)

- {% github alesgenova/post-me no-readme %}
- {% github alesgenova/pitch-detection no-readme %}
OhSnap! Instantly Improve Your Git Commit Messages
Tags: productivity, todayilearned, github, beginners
Published: 2021-01-18 14:00:34

*The "OhSnap!" series explores bite-sized tips that you can apply today.*

---

Sometimes becoming a better developer comes down to slight course corrections in our daily workflows.

Recently I came across [this awesome article by, Chris Beams,](https://chris.beams.io/posts/git-commit/) that explains how to do that with an action we all perform  — **git commits**.

### The Tip
Write git commits **imperatively**, not as a ***description***. 

####The Wrong Way
`git commit -m "Added new page"`

`git commit -m "Fixed margin above the hero banner for a better layout"`

`git commit -m "This adds a new color"`

####The Right Way
`git commit -m "Add About page"`

`git commit -m "Fix spacing above the hero banner"`

`git commit -m "Change headline color"`


#### What is the difference? 
The second versions are all actions. They sound abrupt, but they are meant to instruct what is about to happen, not describe why you did something. 

Notice that even as imperative actions, they still communicate with specificity on exactly what was done.

At the end of the day, all we really want to know is what this commit will do to our main branch if merged. The body of the commit or a pull request can always hold the details of why you did something. 

### How do I write these correctly? 
Chris Beams gives a fantastic sentence to test your commits against. If the sentence still makes sense afterwards, then it is a strong imperative commit.


>If applied, this commit will ***your message here***

`git commit -m "If applied, this commit will Change headline color"`

vs.


`git commit -m "If applied, this commit will changes new color"`


---

I highly encourage you to [read the full article](https://chris.beams.io/posts/git-commit/), as there are many more great tips in there. 

---

*Header image designed with [Adobe Photoshop](https://www.adobe.com/products/photoshop.html) and [Unsplash](https://unsplash.com/)*
Summing up numeric properties of objects in an array in Swift
Tags: swift, ios, programming
Published: 2021-01-18 13:53:57

> You can read this blogpost also [here](https://hoyelam.com/summing-up-numeric-properties-of-objects-in-an-array-in-swift/).

You may want to sum up properties from an object. For example, you may retrieve log data from your analytics web server.

A struct could be the following:

``` swift
struct ActionLog: Codable {
    var actionId: Int
    var actionPerformed: Int
    var creationDate: Date
}
```

This struct could for example contain a log of a certain action taken within a software product. 

- actionId = the ID of a certain action (i.e button press, purchase, authentication)
- actionPerformed = the number of times this action was performed during a log

With these logs, you may have as aim to calculate the total amount of actions performed of a certain action. How do you this?

First, let’s break down the requirement into smaller pieces. 
1. Filter all the actions based on the `actionId`
2. Get all the `actionPerformed`  Integer based on the actionId
3. Sum all the retrieved `actionPerformed` Integers. 

Now that we know what we want to do, let’s code it as well.


``` swift
// 1. Filter step
let desiredActionId = 1
let filteredLogs = logs.filter( {$0.actionId == desiredActionId} )

// 2. Get the `actionPerformed` integers
let numbers = filteredLogs.map( {$0.actionPerformed })

// 3. Sum all the integers up
let totalAmount = numbers.reduce(0, +)
```

Or if you want much shorter.

``` swift
let totalAmount = logs
    .filter( {$0.actionId == desiredActionId} ) // Step 1
    .map( {$0.actionPerformed }) // Step 2
    .reduce(0, +) // Step 3
```

This a solution on how to sum up numeric properties of an object in an array.

You can test the code with a  here:

``` swift
struct ActionLog: Codable {
    var actionId: Int
    var actionPerformed: Int
    var creationDate: Date
}

var logs: [ActionLog] = []

for _ in 0..<100 {
    logs.append(.init(actionId: 1,
                      actionPerformed: 1,
                      creationDate: Date()))
    
    logs.append(.init(actionId: 2,
                      actionPerformed: 2,
                      creationDate: Date()))
}

// 1. Filter step
let desiredActionId = 1
let filteredLogs = logs.filter( {$0.actionId == desiredActionId} )

// 2. Get the `actionPerformed` integers
let numbers = filteredLogs.map( {$0.actionPerformed })

// 3. Sum all the integers
let total = numbers.reduce(0, +)

print("Total amount of actions performed of action 1: \¡(total) times")

// shorter
let totalShort = logs
    .filter( {$0.actionId == desiredActionId} ) // Step 1
    .map( {$0.actionPerformed }) // Step 2
    .reduce(0, +) // Step 3

print("Total amount of actions performed of action 1: \(totalShort) times")

```
The Real Reason We Procrastinate and How to Stop
Tags: productivity
Published: 2021-01-18 13:43:00

We have all been there. A huge deadline is looming and you have yet to take one step towards completing the project. You are given months to prepare for a big meeting or event and you wait until the last minute to sort out all the details.

[Read more...](https://blog.doit.io/procrastinate/)
Flutter - Packages are not supported when using legacy build locations, but the current project has them enabled.
Tags: flutter, xcode, legacy, ios
Published: 2021-01-18 13:36:53

When you will build a flutter application to iOS maybe you can stumble in that error message: 

```Packages are not supported when using legacy build locations, but the current project has them enabled.```

What I did for solve that problem was change advanced settings on project.

So open the `Runner.xcworkspace`, go to `File->Workspace Settings->Per-User Workspace Settings->Advanced` and change from `Legacy` to `Xcode default`. 

Also open the `Runner.xcodeproj`, go to `File->Project Settings->Per-User Project Settings->Advanced` and change from `Legacy` to `Xcode default`. 

It's done. Try again run `flutter build ios` and see it works for you.
Milliseconds to minutes
Tags: javascript, html, css
Published: 2021-01-18 13:33:48

Please guys, I have a countup timer with three different intervals that displays time the time in milliseconds. Is there anyway I can change the milliseconds to minutes

Below is the code for further clarification

JAVASCRIPT
```javascript
 window.addEventListener('load', () => {   // <====== Wait for the window to finish loading
        // GRAB TIMER-DISPLAY ELEMENT
        let timerDisplay =  document.getElementsByClassName( 'timerDisplay')[0];
        
        // TIMER DATA
        const myFootballMatch = {
          'firstHalf' : { 
            'start' : 0,
            'end' : 6
          },
          
          'interval' : { 
            'start' : 0,
            'end' : 1.5
          },
          
          'secondHalf' : { 
            'start' : 4.5,
            'end' : 9
          }
        };
        
        // THE FUNCTION
        const runTimer = (timerObject, timerId = 0) => {
        
           // EXIT FUNCTION IF THERE ARE NO MORE TIMERS
           if (parseInt(timerId) === Object.keys(timerObject).length) {
             return;
           }
        
          let timerName = Object.keys(timerObject)[timerId];
          let timerCount = parseFloat(timerObject[timerName]['start']);
          let timerEnd = parseFloat(timerObject[timerName]['end']);
          
          const timer = setInterval(() => {
          
            timerCount = timerCount + 0.01;
            
            if (timerName === 'interval') {
              timerDisplay.textContent = 'HT';
            }
            
            else {
              timerDisplay.textContent = timerCount.toFixed(2);
            }
          
            if (timerCount > (timerEnd - 0.01)) {
          
              clearInterval(timer);
              runTimer(myFootballMatch, timerId + 1);
              timerDisplay.textContent = 'FT';
            }
          }, 10);
        }
        
        // RUN THE FUNCTION
        runTimer(myFootballMatch);
    });
```
CSS
```css
    .timerDisplay {
  margin: 0;
  font-size: 96px;
  text-align: center;
  font-weight: bold;
}
```
HTML
```html
<h1 class="timerDisplay"></h1>
```
Recover anything in git with 'git reflog' | Notes
Tags: notes, git
Published: 2021-01-20 09:08:37

---
title: Recover anything in git with 'git reflog' | Notes
published: true
date: 2021-01-18 13:26:00 UTC
tags: notes,git
canonical_url: https://abhi.page/notes/recover-anything-in-git/
---

> **Direct Links:**
> - [gitready.com/intermediate/2009/02/09/reflog-your-safety-net](http://gitready.com/intermediate/2009/02/09/reflog-your-safety-net)

To recover from almost anything in git, even if you have done a `git reset --hard origin/main` and lost all your last commits, use the following command:

```
git reflog
```

From the [official documents](https://git-scm.com/docs/git-reflog):

> Reference logs, or “reflogs”, record when the tips of branches and other references were updated in the local repository. Reflogs are useful in various Git commands, to specify the old value of a reference. For example, HEAD@{2} means “where HEAD used to be two moves ago”… This command manages the information recorded in the reflogs.

It gives the historical info like this:

```bash
$ git reflog
c5f76d2 (HEAD -> beta) HEAD@{0}: pull origin main: Fast forward
0e373cb HEAD@{1}: commit: Updated base styles
b7aece4 HEAD@{2}: commit: Updated README
eff2f57 HEAD@{3}: commit: Added shortURL filter...
```

The first 7-characters _(sha-id)_ are the beginning of the SHA1 for that commit. You can use this to recover any lost data from that point in history.

For example, to apply our last commit back into the code base _(sha-id = 0e373cb)_, we can merge it back with the command:

```
git merge 0e373cb
```

We can do other stuff as well, like `checkout`, `cherry-pick` or use `git show` to see the diff.

* * *

[**Read on abhi.page**](https://abhi.page/notes/recover-anything-in-git/)
Integrating FTP with Rails
Tags: rails, technology, webdev
Published: 2021-01-28 14:16:04

---
title: Integrating FTP with Rails
published: true
date: 2021-01-18 13:24:39 UTC
tags: RubyonRails,Technology,WebDevelopment
canonical_url: https://www.botreetechnologies.com/blog/ftp-integration-in-rails-app/
---

![FTP Integration in Rails App](https://www.botreetechnologies.com/blog/wp-content/uploads/2021/01/ftp-integration-in-rails-app.png)

FTP stands for File transfer protocol. It is basically used to transfer files from the local computer to the client/remote server and manage client and server-side data of the application. 

Ruby provides a **‘net/ftp’** library to implement FTP into your web application.

Experts at any [Ruby on Rails development company](https://www.botreetechnologies.com/ruby-on-rails-development) need to understand how to integrate FTP in a rails application. Here you go.

**In this article we will learn how to**

- Integrate FTP in rails application.
- Methods of FTP library and use of these methods.
First you need a library of FTP class.

__require 'net/ftp'__

**There are some methods which will be useful to users.**

- ::open
- getbinaryfilefile
- gettextfile
- putbinaryfile
- puttextfile
- chdir
- rename
- Delete
- Login

The post [FTP Integration in Rails App](https://www.botreetechnologies.com/blog/ftp-integration-in-rails-app/) appeared first on [BoTree Technologies](https://www.botreetechnologies.com/blog).
Как писать полезные комментарии к коммитам
Tags: git
Published: 2021-01-18 13:17:43

У меня был коллега, который коммиты сопровождал одним и тем же комментарием, изредка играя с заглавными буквами. Его история изменений выглядела так:

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

Такие комментарии — ад. Они не говорят о том, что изменилось и почему. Они не помогают при ревью и откате изменений. В них нет ни смысла, ни логики, ни пользы.

Чтобы комментарии к коммитам были полезны и вам, и коллегам, договоритесь об их стиле и содержимом. А я пока поделюсь своим вариантом.

-------------------------------------------

## На каком языке писать

В коде вы работаете с Post, Blog, User. Вы мыслите ими и не задумываясь используете в речи: добавим юзеру аватарку, покажем популярные посты в блоге.

Комментарии на русском сбивают с толку и заставляют вспоминать, что это и где:

```
f0b4ac поправил верстку подвала статьи
```

«Статья». Это у нас что? Article, Post, BlogEntry? Если коммит на английском, проблем нет:

```
f0b4ac fix post footer markup
```


## Что писать в комментарии

Дифф коммита рассказывает, _что_ изменилось. Единственный способ рассказать, _зачем_ эти изменения, какая от них польза — комментарий к коммиту.

Полезный комментарий описывает не что было сделано, а результат в мире ~~клиента~~ разработчика:

```
# Плохо: это мы и в диффе видим.
# Зачем добавляли-то? Что пытались поправить?
d77d9f add <div> wrap

# Хорошо: ясно, зачем сделаны изменения, какую проблему решали
d77d9f fix Firefox issue with flexbox padding
```


## В каком времени

Я рассматриваю историю Гита как историю команд, приказов, приводящих репозиторий из одного состояния в другое. Поэтому пишу в повелительном наклонении. Чтобы было проще писать, [использую шаблон-скороговорку](http://codeinthehole.com/writing/a-useful-template-for-commit-messages/):

```
# If applied, this commit will
mention Ubuntu installation instructions in README
```

<div class="outstanding outstanding--therule">
В&nbsp;повелительном наклонении
</div>

ПРОТИП: если в комментарии есть and, скорее всего, в коммите несколько несвязанных изменений:

```
fix ... and update ...
introduce ... and correct ...
```

-------------------------------------------

## Дополнительное чтение

* [Past Tense](http://stackoverflow.com/a/8059167) vs [Present Tense](http://stackoverflow.com/a/3580764)
* [How to Write a Git Commit Message](http://chris.beams.io/posts/git-commit/)
* [A Note About Git Commit Messages](http://tbaggery.com/2008/04/19/a-note-about-git-commit-messages.html)
* [Atomic Commits](http://www.freshconsulting.com/atomic-commits/)
* [Git Commit Good Practice](https://wiki.openstack.org/wiki/GitCommitMessages)
* [GIT Conventions](https://medium.com/@tjholowaychuk/git-conventions-a940ee20862d#.vacbx5a0o)