teleren/devto huggingface dataset:
Good code Practices
Tags: codenewbie, codequality, beginners
Published: 2020-10-27 14:56:34

Recently I learned a few best code practices, and I want to share them.
* When you are writing a function multiple times that may cause buffer overflow. So the better practice is to store the function value and reuse it again.

> Example:

```
int main()
{
    int size;
    cin>>size;
    vector<int> arr(size);
    for(int i=0;i<arr.size();i++)
    cin>>arr[i];
    for(int i=0;i<arr.size();i++)
    {
      if(arr[i]==*max_element(arr.begin(),arr.end()))
      {
        max_index=i;
        break;
      }
    }
}
```
* In the above code instead of using the function arr.size() and max_element we can just store them in a variable and use it.
* The naming of variables and functions:

 So while you are naming any variable or function, use a name in such a way that others who see your code will understand what it is doing without prior knowledge of that language. I think many companies also follow this rule from what I heard.
* Don't write complicated code. Make use of other alternative ways that are simple and easy to understand. 

* Use separate functions for different issues so that we can enhance the code reusability factor of object-oriented programming instead of writing all the functionality in the main function.

* Object oriented programming principles are best ones to follow so that the code can be modified or extended by others later.

* At the end but most important is to write efficient code in terms of time and space by using appropriate algorithms and data structures.

` Note: I collected these from various sources, Feel free to add more in the comments so that others can learn! Happy Learning `
Power Up Your Java Using Python With JPype - Episode 286
Published: 2020-10-29 13:31:51

<p>Python and Java are two of the most popular programming languages in the world, and have both been around for over 20 years. In that time there have been numerous attempts to provide interoperability between them, with varying methods and levels of success. One such project is JPype, which allows you to use Java classes in your Python code. In this episode the current maintainer, Karl Nelson, explains why he chose it as his preferred tool for combining these ecosystems, how he and his team are using it, and when and how you might want to use it for your own projects. He also discusses the work he has done to enable use of JPype on Android, and what is in store for the future of the project. If you have ever wanted to use a library or module from Java, but the rest of your project is already in Python, then this episode is definitely worth a listen.</p><p><a href='https://www.pythonpodcast.com/jpype-java-python-bridge-episode-286/'>Listen Now!</a></p>
MY Hacktoberfest Experience
Tags: hacktoberfest
Published: 2020-10-29 13:31:42

<!-- ✨This template is only meant to get your ideas going, so please feel free to write your title, structure, and words! ✨ -->


### [My first ever Contribution]
<!-- If you are new to the DEV community, introduce yourself and share a bit about why you joined DEV and decided to participate in Hacktoberfest this year.  --> 
Hi Everyone! I am a 2nd-year student pursuing computer science, my name is Phagun, for about a year. I was struggling on how to get started with open source contributions, all I was doing is searching and more searching but could not find the right project, this hacktoberfest thingy helped me in making my first contribution as many beginners friendly projects came out in which I could contribute with my little experience.  

### Background

<!-- Are you brand new to open source? What about coding in general? Tell us about how you got here → -->

I got to know about this event organized by @DigitalOcean around the 11th of October, I was not very positive about the event but registered myself anyway.
 
### Progress

<!-- Share a bit about where you’re at in your Hacktoberfest journey. What stage are you at? How has the process been?  --> 

I am not a hardcore coder but I know front-end quite well so I contributed to various front-end projects or minor c++ code patches.
and I have finally completed this year's challenge, next time I will try to contribute to some major projects too


### Reflections
<!-- Overall, how has your Hacktoberfest 2020 experience been? If you’re a first-timer, will you participate again? What have you learned? Have you made any interesting connections? What is your next step in open source?  -->

This was my first time participating in this event and it helped me a lot, I would love to do it again.
Persist state and settings in Microsoft office add-ins
Tags: officejs
Published: 2020-10-29 13:30:10

The Office JavaScript API provides objects for your add-in to save state across user sessions. 
Office js api provides following objects to save state according to user sessions

``Office.CustomProperties``

``Office.CustomXmlParts``

``Office.RoamingSettings``

``Office.Settings``  

**Settings** office api object is used to store data on the document, workbook, or presentation
**CustomXmlParts** object is used to store data in a custom XML part of the document or workbook.
**CustomProperties** and **RoamingSettings** office api objects are supported MailApp add-ins.data is stored as Data is stored  user's Exchange mailbox as key value pair

{% gist https://gist.github.com/asithw/401b0e535d75c387b638af42810c2dce %}
Define regex constraints to your Laravel routes easy.
Tags: laravel
Published: 2020-10-29 13:22:35

---
title: Define regex constraints to your Laravel routes easy.
published: true
description: In the next version 8.x of laravel a method will be added that will save you several lines of code if you are defining restrictions on your routes.
tags: #laravel
---

In the next version 8.12.x of laravel a method will be added that will save you several lines of code if you are defining restrictions on your routes.

Previously, in most projects that implemented this feature, you would see code like the following.

```php
<?php

use Illuminate\Support\Facades\Route;

Route::get('articles/{article}', 'ArticleController@show')
  ->where(['article' => '[0-9]+']);
```

With this syntax we would match with a route similar to the following.

| URL                                   | HTTP Status Code |
| ------------------------------------- | ---------------- |
| `https://example.com/articles/123456` | 200              |
| `https://example.com/articles/abcdfg` | 404              |

This is fine, but some users may not understand this syntax at first glance. Therefore, now we will have a series of explicit methods that will allow the developer to save code and obtain the same result without writing "complex" expressions.

## New route regex registration methods

| Method      | Regex                                                        |
| ----------- | ------------------------------------------------------------ |
| whereNumber | `[0-9]+`                                                       |
| whereAlpha  | `[a-zA-Z]+`                                                    |
| whereUuid   | `[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}` |

Finally you can use these methods in the definition of the routes as follows.

```php
<?php

use Illuminate\Support\Facades\Route;

Route::get('articles/{article}', 'ArticleController@show')
  ->whereNumber('article');

Route::get('user/{user}', 'UserController@show')
  ->whereUuid('user');

Route::get('book/{author}/{title}', 'BookController@show')
  ->whereString(['author', 'title']);
```

As you know this feature will be available from version 8.12.0 of the framework, I hope it will be useful for you.

We read soon.
Introducing the Web Performance Quiz 🏆🏅🎖️
Tags: challenge, webperf, webdev, quiz
Published: 2020-10-29 13:20:39

This time my blog post is a bit different. In the last weeks, I worked on something new, and today I want to introduce you to my new web performance quiz.

You can challenge your knowledge in 30+ questions about browser work, web performance metrics, performance culture, user experience, image handling, and web performance patterns.

So what are the questions? The questions cover some of the main parts of web performance. They are starting with the web performance culture. Who is solely responsible for web performance?

The questions will also include some abbreviations you should know. What does the abbreviation WPO stand for? Items like this are too easy?

What about "To render 60 frames every 1000ms, how much time is available to render a single frame?"

Are you curious? Then start right away, and don't forget to publish your results. 🏆🏅

{% twitter 1321408871253057536 %}

---


<center> [Start the web performance quiz](https://marcradziwill.com/web-performance-quiz/) </center>

---

The quiz will be an ongoing project, and I'm happy if someone wants to collaborate on it together. I'll publish the source on Github as soon as the quiz is public for everyone.

The quiz aims to give you an overview of some of the main topics in web performance if you are curious about knowing more about each, [subscribe to my newsletter](https://marcradziwill.com/newsletter/), [follow me on Twitter](https://twitter.com/marc_radziwill) or feel free to [ask me](https://marcradziwill.com/contact/).

I hope you have fun and I'm looking forward to your results. 

Note on answer data persistence: Your answers to all quiz questions are stored locally in your browser's local storage. To delete the data, you can clear the browser's local storage.

## Conclusion <div id="conclusion"></div>

In this post, I presented you with my new web performance quiz.

If you like this article, smile for a moment, share it, follow me, [check out my RSS feed](https://marcradziwill.com/blog/rss.xml), and [subscribe to my newsletter](https://marcradziwill.com/newsletter/).

Cheers Marc
Reasons to choose Hyperledger as open-source blockchain for business
Tags: hyperledger, opensource, blockchain, webdev
Published: 2020-10-29 13:14:20

Using blockchain in business projects saves time and money usually spent on developing unification and automation-related solutions. Blockchain finds use in many different industries. By deconstruction of business processes of a company, you can identify dozens of potential uses for blockchain and implement it in software. [Hyperledger](https://evrone.com/hyperledger?utm_source=devto&utm_medium=article&utm_campaign=hyperledger-0) is already widely implemented by large corporations in their products.

[Learn more](https://evrone.com/hyperledger-0?utm_source=devto&utm_medium=article&utm_campaign=hyperledger-0) about how you can use Hyperledger technology in your project.
How garbage collection in Erlang helps us to create scalable applications
Tags: erlang, webdev, coding, programming
Published: 2020-10-29 13:09:18

Erlang is a functional programming language with dynamic tupization. Its primary feature is working at a separate-process level. Personal computer CPUs have almost plateaued in terms of frequency and now develop mostly through increasing the number of cores. Apps written in Erlang allow you to fully utilize the advantages of multi-threaded CPUs and handle a large number of concurrent activities.

Use cases for Erlang include, for example, developing backend for fault-resistant web applications, messaging apps, task managers and server monitoring systems. Evrone engineers use Erlang in the company’s projects. One of Erlang’s biggest perks is its mechanism for garbage collection.

[Learn more](https://evrone.com/garbage-collection-erlang?utm_source=devto&utm_medium=article&utm_campaign=erlang) about how we use Erlang in our projects.
How to keep node_modules in sync with package.json
Tags: npm, node, productivity, git
Published: 2020-10-29 16:51:34

---
title: How to keep node_modules in sync with package.json
published: true
date: 2020-10-29 13:03:05 UTC
tags: npm,nodejs,productivity,git
canonical_url: https://bharathvaj.me/blog/how-to-keep-node_modules-in-sync-with-package.json
---

As a JS developer, while working on projects we frequently need to run `npm install` command on git pull or checkout to a different git branch where _package.json_ is modified.

In majority of the cases, the dependencies won’t cause any issues, but if there any breaking change introduced by the dependency packages then we need to reinstall. We somehow forget to run the command. *(I mostly forget it at least* :stuck_out_tongue:).

How do we automate this?

Well, it's quite simple. Hooks!!!

Yes. Git hooks.

We can make use of git hooks to trigger `npm install` command if a _package.json_ file has been modified.

**Script to run inside git hooks.**

```
#/usr/bin/env bash

changed_files="$(git diff-tree -r --name-only --no-commit-id ORIG_HEAD HEAD)"

check_run() {
	echo "$changed_files" | grep --quiet "$1" && eval "$2"
}

check_run package.json "npm install"
```

Here we check whether _package.json_ file is present in the diff between the current HEAD and original HEAD. To learn more about these refer to this [Q&A](https://stackoverflow.com/questions/964876/head-and-orig-head-in-git)

In order to do the magic,

1. Save the script with git hook name (eg. `post-merge`)
2. Make it executable by running `chmod +x {HOOK_NAME}`
3. Finally put the file into git hook by `mv {HOOK_NAME} .git/hooks/`

**Git Hooks**

| Name  | Invoked By               |
|----------------|--------------------------|
| post\-merge    | git pull / git merge     |
| post\-checkout | git checkout / git clone |



References:

- [HEAD and original HEAD in git](https://stackoverflow.com/questions/964876/head-and-orig-head-in-git)
- [Sindre Sorhus’s gist](https://gist.github.com/sindresorhus/7996717)
- [Git Hooks](https://git-scm.com/book/en/v2/Customizing-Git-Git-Hooks)
Tree Exchange App
Tags: dev, servers, digitalocean
Published: 2020-10-30 09:45:01

---
title: Tree Exchange App
published: true
date: 2020-10-29 12:57:33 UTC
tags: dev, servers, digitalocean,
canonical_url: https://steadfastcollective.com/articles/tree-exchange/
cover_image: https://steadfastcollective.com/app/uploads/2020/10/Screenshot_2020-10-27_at_13.32.14-1000x488.png
---

In early September, we made a radical change to our working week at Steadfast Collective.

We started The Friday Collective, an initiative for all team members to make Fridays a time for learning, teaching and exploring new ideas.

André (our Technical Lead) got to work on a new project idea; [TreeExchange.app](http://TreeExchange.app), a micro-app encouraging companies to think green and to plant trees. 

![](https://steadfastcollective.com/app/uploads/2020/10/Screenshot-2020-10-29-at-12.55.52.png)

### But how many trees? And what could be the basis for planting them?

Each month, as a studio, we spend a large amount of money on server costs to keep our websites and web apps running.

So we wondered what it would look like to spend a proportionate amount of money on something that would keep the planet up and running.

As a studio, we rely on [Digital Ocean](https://www.digitalocean.com/) to host our websites and applications online and know that thousands of other companies and organisations use Digital Ocean for their hosting. We decided to utilise the amazing Digital Ocean API to convert the size and number of Digital Ocean Droplets (servers) people have into planted trees.

We had a feeling we wouldn’t be the only ones interested in this.

![](https://steadfastcollective.com/app/uploads/2020/10/Screenshot_2020-10-27_at_13.32.14.png)

### How does Tree Exchange work?

Log in securely with your Digital Ocean credentials and, using the Digital Ocean API, we pull a count of your Droplets and their sizes. 

We then use some magic (basic math really), to calculate how many trees we believe you should exchange for your usage.

For example, for a droplet up to $40 we add 20 trees. For a droplet that costs more than $40 and up to $80 we will add 30 trees, and so on. At this point, you are able to increase (or decrease) your monthly tree commitment, add your payment details and hit save. 

Automagically (see what we did there?!), each month, we will send an API call to Ecologi to plant the agreed number of trees into our new Tree Exchange forest – [https://ecologi.com/treeexchange](https://ecologi.com/treeexchange). 

Each person signed up will then receive an email celebrating the total of numbers of trees you have planted, so that you can give yourself a high five.

Why did we choose Ecologi for the tree planting? Read our previous post about why we believe in the work Ecologi is undertaking.

You can give our Tree Exchange app a go over at [https://treeexchange.app/](https://treeexchange.app/) 

 

The post [Tree Exchange App](https://steadfastcollective.com/articles/tree-exchange/) appeared first on [Steadfast Collective](https://steadfastcollective.com).
Best jobs remotely for developers 
Tags: devops, angular, leadership, motivation
Published: 2020-10-29 12:57:27

Click for more information: https://www.remotely.jobs/remote/programming-jobs/

1. Angular Developer (https://www.remotely.jobs/remote-angular-developer-job-at-mailshake) (Mailshake)

2. Senior Developer – Full-time (https://www.remotely.jobs/remote-senior-developer-full-time-job-at-toptal) (Toptal)

3. Lead Developer (Rails / React) (https://www.remotely.jobs/remote-lead-developer-rails-react-job-at-1848-ventures) (1848 Ventures)

Join us on Telegram: https://t.me/remotely_jobs
Also we have bot:  https://telegram.me/remotely_bot
Why Rust is meant to replace C
Tags: rust, webdev, programming, coding
Published: 2020-10-29 12:53:33

The Rust programming language is an ambitious project of the Mozilla Foundation — a language that claims to be the next step in the evolution of C and C++. Over the years of existence of these languages, some of their basic flaws still haven’t been fixed, like segmentation errors, manual memory control, risks of memory leaks and unpredictable compiler behavior. Rust was created to solve these problems while improving security and performance along the way.

[Learn more](https://evrone.com/rust-vs-c?utm_source=devto&utm_medium=article&utm_campaign=rust-vs-c) about how Evrone engineers have found the use of Rust in a lot of projects.
console.time(), parsing api response as json and a little test python server
Published: 2020-10-29 12:44:23

I wanted to set up a fake API that gives me test data and find out how long does my javascript function (that is wrapped deep inside some react components) execute. 

Python - fake API

server.py:
```
from flask import Flask, jsonify
from flask_cors import CORS

app = Flask(__name__)
cors = CORS(app)
@app.route('/get-data', methods=['GET'])
def get_data():
    data = getData() # generate fake data, much bigger than real
    return jsonify(data)


if __name__ == "__main__":
    app.run()

```

Javascript - index.html
```
<html>
<body>
<script>
function doExpensiveThings() {
   ...
}

fetch('http://localhost:5000/get-data', {mode: 'cors'}).then(response => {
    response.json().then(jsonResponse => {
        console.time("doExpensiveThings");
        doExpensiveThings(jsonResponse);
        console.timeEnd("doExpensiveThings");
    }).catch(err => {
        console.warn(err);
})
}).catch(err => {
    console.warn(err);
})

</script>
</body>
</html>
```

And then in the console, one would see: `doExpensiveThings: 1.3291015625 ms`. 

`fetch` returns a promise, if everything went alright, the promise is resolved and the value is an instance of the Response class. I wanted to parse the response as json, so I called `.json()` method on the instance, this again returns a promise.
RubyRussia: How the barcamp turned into the largest Russian Ruby conference
Tags: ruby, webdev, programming, eventsinyourcity
Published: 2020-10-29 12:40:45

RubyRussia is the key Russian conference on the Ruby programming language that is held by Evrone in Moscow for 10 years in a row. Let’s remember how it all began.

In 2007 the developers Ivan Yevtukhovich, Oleg Balbekov and Yuri Gurzhiy began using the Ruby language and the Rails framework in projects. The people also interested in the technology has started to grow around them. In 2009, they decided to organize a small gathering of like-minded people.

The Gogol restaurant was chosen as a place for the gathering. We agreed that the restaurant will provide a small room, and we will try to make a profit for their bar that day. We have prepared three reports. In addition to our acquaintances, we have invited the participants of the profile chat groups.

On April 19, 2009, we had held the first gathering with beer that had been attended by around 30 people. Then the gathering has grown into RailsClub, and in 2018 we have changed the name to RubyRussia because we received a change request, which we could not refuse.

[Learn more](https://evrone.com/rubyrussia-2019?utm_source=devto&utm_medium=article&utm_campaign=rubyrussia) about the history of the biggest Ruby/Ruby on Rails event in Russia.
Code Smell 10 - Too Many Arguments
Tags: codenewbie, beginners, 100daysofcode, oop
Published: 2020-10-29 12:36:24

*Objects or Functions need too many arguments to work.*

TL;DR: Don't pass more than three arguments to your functions.

# Problems

- Low maintainability

- Low Reuse

- Coupling

# Solutions

- Find cohesive relations among arguments

- Create a "context".

- Consider using a [Method Object](https://wiki.c2.com/?MethodObject) Pattern.

- Avoid "basic" Types: strings, arrays, integers, etc. Think on objects.

# Exceptions

- Operations in real world needing not cohesive collaborators.

# Sample Code

## Wrong

[Gist Url]: # (https://gist.github.com/mcsee/ea7d32472830d5ea877be1438807fe89)
```java
public class Printer {   
  void print(String documentToPrint, 
         String papersize,
           String orientation, 
           boolean grayscales,
           int pagefrom,
           int pageTo,
           int copies,
           float marginLeft,
           float marginRight,
           float marginTop,
           float marginBotton         
        ){    
    }
}
```

## Right

[Gist Url]: # (https://gist.github.com/mcsee/200a18dd99a76a95155df4cb032b1d10)
```java
final public class PaperSize {
    //...
}

final public class Document {
    //...
}

final public class PrintMargins {
    //...
}

final public class PrintRange {
    //...
}

final public class ColorConfiguration {
    //...
}

final public class PrintOrientation {
    //...
}

final public class PrintSetup {
    public PrintSetup(PaperSize papersize,
           PrintOrientation orientation, 
           ColorConfiguration color,
           PrintRange range,
           int copiesCount,
           PrintMargins margins
           ){}
}

final public class Printer {   
  void print(Document documentToPrint, 
         PrintSetup setup        
        ){    
    }
}
```

# Detection

Most linters warn when the arguments list is too large.

# Tags

- primitive

# Conclusion

Relate arguments and group them.
Always favor real world mappings. Find in real world how to group the arguments in cohesive objects.

If a function gets too many arguments, some of them might be related to the class construction. This is a design smell too.

# Relations

{% post https://dev.to/mcsee/code-smell-34-too-many-attributes-584p %}

{% post https://dev.to/mcsee/code-smell-13-empty-constructors-4i4o %}

# Credits

Photo by <a href="https://unsplash.com/@tobiastu">Tobias Tullius</a> on <a href="https://unsplash.com/s/photos/loaded">Unsplash</a>

* * *

This article is part of the CodeSmell Series.

{% post https://dev.to/mcsee/how-to-find-the-stinky-parts-of-your-code-1dbc %}

*Last update: 2021/06/13*