teleren/devto huggingface dataset:
DeepCode’s Top Findings#7: Python Use Real Floor Division
Tags: deepcode, staticcodeanalysis, python
Published: 2020-01-20 07:32:22

**Language:** Python
**Defect:** DivisionRounding
**Diagnose:** Use `//` instead of `/` to make sure the value is rounded to an integer and not fractional. %function% expects an int as its first argument.

This example is sponsored by `tensorflow / models` and you can follow along by loading it into your dashboard on [deepcode.ai](https://deepcode.ai)

![Screenshot](https://thepracticaldev.s3.amazonaws.com/i/p0nakdq8mktikk8ttgo3.PNG)

I was fascinated by this as it shows a difference between Python 2.7 and 3. The code snippet below shows the interesting parts.

```
...
 def take_action(self, current_node_ids, action, step_number):
...
    goal_number = step_number / self.task_params.num_steps
    ...
      if n == self.episode.goal_node_ids[goal_number][i]:
    ...

```

`step_number` and `self.task_params.num_steps` are both integers. In Python 2.7, the division operator `/` works as a floor division. But dividing integers will always result in an integer.

```
Python 2.7.16 (default, Jul 13 2019, 16:01:51)
[GCC 8.3.0] on linux
> 3/4
0
> 9/10
0
```

This is no longer true with Python 3. 
```
Python 3.7.4 (default, Jul  9 2019, 00:06:43)
[GCC 6.3.0 20170516] on linux
> 3/4
0.75
> 9/10
0.9
> 4/2
2.0
```

See the difference? In Python 3, the division behaves differently, so you need to be careful. A division between two integers results in a floating-point number, even if there is no remainder. 
What DeepCode did under the hood was a type analysis and it inferred that `goal_number` is a floating-point number. It traced `goal_number` to its definition and found it to be a result of a division of two integers. But it is later used as the parameter for an index operator which needs to be an integer. If the program calls the index-operator with float, it results in `TypeError`. DeepCode learned from scanning thousands of open source repos that typically this should have been a real floor division `//` instead of a division `/ `. And it happens quite frequently when porting code from Python 2.7 to Python 3.

```
Python 3.7.4 (default, Jul  9 2019, 00:06:43)
[GCC 6.3.0 20170516] on linux
> table = [1,2,3,4,5,6,7,8,9,10]
> a = 30
> b = 10
> table[a/b]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: list indices must be integers or slices, not float
> table[a//b]
4
```

To "simulate" the Python 2.7 behavior, you can use the floor division operator `//`.

```
Python 3.7.4 (default, Jul  9 2019, 00:06:43)
[GCC 6.3.0 20170516] on linux
> 3//4
0
> 9//10
0
```

Not sure if this still is of interest but in Python 2.7 `//` works on integers just as expected so it is safe to use.
To the point: options as function for your APIs
Tags: go, design, tutorial, beginners
Published: 2020-01-20 06:59:47


## Problem
You have created a super performant csv reader that look like:

```go
package awesomecsvreader

type csvReader struct{
    filename string
    delim string
    escape string
}

func (*csvReader) Read() {
    //...your awesome secret sauce
}
```

But whats missing it a simple API for users to use your module, that doesn;t look like this:
```go
func NewCsvReader(filename string, delim string, escape string) {
    ....
} 
// ? what happens when new options are added like "separator". 
// red alert: api could break!
```


## Solution 

### Thoughts:

One could use structs for options but that has the following demerits:
- there is no good way of setting up default values for the options, unless the defaults are equal to zero values
- an empty options struct needs to be passed by the user of the api

> **So, instead of using struct, use the power of functions with closures**

# Let's code

Commented inline for brevity.

```go
// your module
package awesomecsvreader

import (
    "fmt"
)

// this is what my csvReader struct looks like
type csvReader struct{
    filename string
    delim string
    escape string
}

// I define a type that is a func that takes csvReader and sets the option
type option func(*csvReader)

// Take the delim string and return the option
func SetDelim(delim string) option{
    return func(cr *csvReader) {
        (*cr).delim = delim
    }
}

// Take the escape string and return the option
func SetEscape(escape string) option{
    return func(cr *csvReader) {
        cr.escape = escape
    }
}

// Constructor that takes required values like filename
//  and setters that are of type option
func NewCsvReader(filename string, setters ...option) *csvReader{
    
    // construct a csvReader with default values
    cr := csvReader{
        filename: filename,
        delim: "CRLB",
        escape: "ESC",
    }
    
    // change the default values as per those supplied by the user
    // by calling the option
    for _, setter := range setters {
        setter(&cr)
    }
    
    return &cr
}
```

```go
// I am a user of your API
package main

func main() {

    //
    // create a csvReader with default options
    fmt.Println(NewCsvReader("file123"))
    
    //
    // create a csvReader with mix of default and custom options
    r1 := NewCsvReader("file123", SetDelim("XXX"))
    fmt.Println(r1)
    
    //
    // create a csvReader with all custom options
    r2 := NewCsvReader("file123", SetDelim("XXX"), SetEscape("YYY"))
    fmt.Println(r2)
}
```

```bash
// output
&{file123 CRLB ESC}
&{file123 XXX ESC}
&{file123 XXX YYY}
```



Good ref: https://dave.cheney.net/2014/10/17/functional-options-for-friendly-apis
The 2020s is the decade of remote transformation
Tags: remote
Published: 2020-01-20 06:44:35

<a href="https://www.buymeacoffee.com/peacefullatom" target="_blank"><img src="https://cdn.buymeacoffee.com/buttons/default-orange.png" alt="Buy Me A Coffee" style="height: 51px !important;width: 217px !important;" ></a>

The current decade is a time of explosive growth of a remote lifestyle.

Why?

These changes are upcoming thanks to world-wide-web that has reached every corner of our home planet and stretches to the orbit of the Moon.

Even Mars is nowadays is a part of the global web, though it is not yet publicly accessible.

The trick is that the web is not only the way to communicate.

It also allows you to share your goods, service, or content and to transfer money.

It is also important that it is irrelevant what kind of values are you offering - real-world or digital.

The modern logistics is a wonder of speed and quality.

Let's sum it up:

- you can reach any person on this planet

- you can deliver whatever you able to produce

- you can receive money as a reward to your efforts

Doesn't it sound very attractive?

For me, it sounds very promising!

What is your opinion?
Linked Lists and the "Runner" Technique
Published: 2020-01-20 06:39:57

A couple weeks ago I was at an algorithm practice meetup, and our group was tasked with finding the middle node of a linked list (if the list has an even number of nodes, we were to return the second of the two middle nodes). 

We worked through it together and did fairly well. The solution we came up with involved iterating through the list one and a half times, and had O(n) time complexity. We looped through the list once, updating a counter to find out how long the list was. Then we calculated which number in the list we wanted based on that length, and looped through again. We stopped and returned the node when the counter was pointing at the one we wanted. 

This was pretty good, but I just _knew_ there must be some trick to do this more easily. And indeed, when we were done, the host let us know the trick for solving  it simply. It was one of those moments where once I saw the answer, it made so much sense that I was grumpy I couldn't see it before.

The answer is to use what is sometimes called the "Runner" technique. Essentially, instead of having one pointer as you loop through the linked list, you have two, and each moves at a different speed. 

Imagine you have two carts moving down a track. One is moving exactly twice as fast as the other. At the moment the faster cart reaches the end, you know that by definition the slower cart must be exactly half way down the track. 

That's how this works! In your loop, track two variables, say A and B. For each new node, add 1 to A and 2 to B. End the loop when B points to null (when there are no more nodes and so the list has ended), then A is pointing right where we want it! If there are an odd number, it's right in the center. 

![a diagram showing the runner method on an odd-numbered linked-list](https://res.cloudinary.com/dwfqeeh5f/image/upload/v1579502068/Blog%20Images/Screen_Shot_2020-01-19_at_10.33.14_PM.png)

If there are an even number, it's on that second middle node. 

![a diagram showing the runner method on an even-numbered linked-list](https://res.cloudinary.com/dwfqeeh5f/image/upload/v1579502068/Blog%20Images/Screen_Shot_2020-01-19_at_10.33.19_PM.png)

I love little tricks like this, even as they infuriate me when I don't stumble upon them myself. Linked lists were long a confusing foe for me, but these days I'm not intimidated. I still don't like them, I think they're obtuse, but I can work with them for your average algorithm. 

I look forward to continuing to learn hacks like this and to mastering more data structures.
0365 CLI on Windows Terminal
Tags: 0365, terminal, windowsterminal, tools
Published: 2020-01-20 06:11:04

Since a few months, I like to manage my Office 365 development tenants with the command line tool instead of the Office 365 portal.
The main reason is I created some scripts to clean up everything after deploy and to reset all the settings from a team or something similar.

In addition, I fell in love with Windows Terminal since the firsts beta version. :)

## Create an O365 CLI Profile
Basically the only requirement to run an O365 CLI is a command prompt.
For this reason, create a profile on Windows Terminal is very easy.
In my profile, I launch a Powershell Core instance with the parameter o365.
I also configured Cascadia Code as font to have some addinational features during the reading of the console commands and results.
I added an image as background to recognize instantly the 0365 CLI.

I shared my Json configuration below.
You can just copy and paste on your Windows Terminal profile. :)

```json
    {
      "guid": "{61c54bbd-c2c6-5271-96e7-009a87ff44bd}",
      "name": "O365 CLI",
      "commandline": "pwsh.exe o365",
      "icon": "https://www.pinclipart.com/picdir/big/7-77422_microsoft-office-365-icon-clipart.png",
      "hidden": false,
      "cursorColor": "#FFFFFF",
      "cursorShape": "bar",
      "fontFace": "Cascadia Code",
      "fontSize": 10,
      "acrylicOpacity": 0.5,
      "background": "#012456",
      "closeOnExit": true,
      "colorScheme": "Dracula",
      "padding": "0, 0, 0, 0",
      "snapOnInput": true,
      "tabTitle": "O365 CLI",
      "startingDirectory": "%USERPROFILE%",
      "useAcrylic": true,
      "backgroundImage": "https://tech4logic.com/Content/Images/office365.png",
      "backgroundImageOpacity": 0.5,
      "backgroundImageStretchMode": "uniform"
    }
```

This is how my O365 CLI looks like.
![Alt Text](https://thepracticaldev.s3.amazonaws.com/i/wrzepxkzoagw21799vu0.PNG)
Contribuir a proyectos Open Source como reto profesional
Tags: spanish, opensource
Published: 2020-01-20 04:42:16

---
title: Contribuir a proyectos Open Source como reto profesional
published: true
description: Desde los inicios de la computación los Hackers de la época, tenían clara una misión, compartir su conocimiento...
tags: spanish, opensource
canonical_url: https://arepa.dev/contribuir-a-proyectos-open-source-como-reto-profesional/
cover_image: https://s3.amazonaws.com/arepadev/2020/01/open-source-oscar-barajas.png
---

Desde los inicios de la computación los Hackers de la época, tenían clara una misión, compartir su conocimiento, Hoy en día, con mas de 30 años desde la primera computadora personal, seguimos compartiendo nuestro conocimiento a través del código libre.

En esta charla en formato "ignite" donde tenemos 5 minutos y 20 diapositivas las cuales se van mostrando cada 15 segundos fue presentada en la pasada [Platzi Conf Colombia 2019](https://platzi.com/blog/platziconf-colombia-resumido-en-45-frases/).   

{% youtube dsnN1x48kVs %}
Difference Between Recursion and Iteration
Tags: recusrion, iteration, recursionvsiteration
Published: 2020-01-20 04:32:05

What is the difference between recursion and iteration? Both recursion and iteration are running instruction repeatedly. However, they are totally different. At the first time I was also a little bit confuse. But after read some article and reference, finally I understand. I will summarize it for you and make it very simple to be understood.

Recursion is call a function from inside it's function. This will make a repetitive process.

We can take example a film titled "Inception" as a recursion process. In this film, the actor Leonardo DiCaprio as Dominic Cobb, and his team must go inside into someone's dream. If the mission is not succeed, they must go into deeper dream. And it happen repeatedly until they accomplish the mission.

So recursion is somehow go deeper inside by repeatedly doing such a function from inside the function.

Next, what is iteration? Even though it has similarity with recursion in term of repeated. But it has different meaning. Iteration is doing instruction repeatedly within a function.

For example, when our mom are making soup with love, she cuts the carrots repeatedly until they all be cut. So, she will chop the carrots  for more than once, in order to make delicious soup.

I hope my explanation can be understood in a very easy way.
Upload Multiple Image Upload using Angular 8
Published: 2020-01-20 04:38:29

---
title: Upload Multiple Image Upload using Angular 8
published: true
date: 2020-01-20 04:19:39 UTC
tags: 
canonical_url: https://www.itsolutionstuff.com/post/angular-8-multiple-image-upload-with-previewexample.html
---

In this example i am going to explain you how to upload multiple images in angular 8 with web api you need to follow few step for multiple image upload in angular 8 you can easily understand this example of angular 8 multiple image upload with previewi will give you very simple example from sc
Different ways of using Bootstrap 4 in React application
Tags: react, javascript, node, bootstrap
Published: 2020-01-20 03:49:36

In this article, We will discuss about the different ways by which Bootstrap 4 can be added in React application. 

What is Bootstrap?
As per Official Website:

It is the most popular HTML, CSS, and JS framework for developing responsive, mobile-first projects on the web. Bootstrap 4 is the latest version of Bootstrap.

In layman’s terms:

Bootstrap is a giant collection of handy, reusable bits of code written in HTML, CSS, and JavaScript. It’s also a front-end development framework that enables developers & designers to quickly build fully responsive websites.

Bootstrap saves you from writing lots of CSS code, giving you more time to spend on designing webpages.

 

What Is React?
React is a declarative, efficient, and flexible JavaScript library for building user interfaces. It lets you compose complex UIs from small and isolated pieces of code called “components”.

 
Different Ways to Include Bootstrap 4 in Your React Application
There are different ways by which you can add Bootstrap 4 into your application.

By Installing Bootstrap NPM library
By using Bootstrap CDN 
Using React-Bootstrap library in React
Using Reactstrap


The above article is republished from https//jsonworld.com. Click here https://jsonworld.com/blog/different-ways-of-using-bootstrap4-in-react-application to read the complete article.
Hobby Project: Adding CI
Tags: ci
Published: 2020-01-20 03:40:03

This next session was to get some tests up and running. As it is 2020 this means adding a CI system [(which is not continuous integration)](https://dev.to/jessekphillips/git-branch-strategy-part-1-3m80). 

First thing I did was to refactor the query method so I can verify parsing out the data I am interested in. I don't really view this as a valuable test, but I now have a helper method to hide the deserialization in. 

I created [merge request 1](https://gitlab.com/jessephillips/devarticlator/merge_requests/1) which includes steps for unittesting and build. Which has already paid dividends as I forgot files and parts of files. This allows me to work through desired changes.

Next I expect I'll be building out how I want to write out the articles and their Metadata.
Best Practices for Kubernetes Runners
Tags: kubernetes, devops, tutorial
Published: 2020-01-20 03:37:16

Are you sure you know what is happening in your GitLab Runners?  GitLab CI is extremely powerful and flexible, however with that users can easily make mistakes that could take out a GitLab Runner, and potentially clog up Sidekiq bringing your entire GitLab instance to it’s knees. In this talk, Senior Software Engineer Sean Smith discusses some situations that F5 Networks ran into in their installation, for example CI jobs growing exponentially; as well as how monitoring was implemented after incidents occurred and how to limit the impact of incidents when they occur.

{% youtube O0_bFSg1Zo4 %}
How to Publish ASP.NET Core RESTful API to Azure
Tags: restfulapi, netcore
Published: 2020-01-20 03:25:14

In this [tutorial](https://github.com/patricksameerajayalath/AzureTutorials/blob/master/How%20to%20Publish%20ASP.NET%20Core%20RESTful%20API%20to%20Azure.pdf) I’m going to show how to:

•	Create a SQL Database
•	Create a .Net Core RESTful API
•	Deploy REST API to Azure
•	Test REST API using Postman

![Alt Text](https://thepracticaldev.s3.amazonaws.com/i/tz9r9vj4enqi44y4cnj2.jpg)

You can find the PDF version of this tutorial [here](https://github.com/patricksameerajayalath/AzureTutorials/blob/master/How%20to%20Publish%20ASP.NET%20Core%20RESTful%20API%20to%20Azure.pdf).

You can find all my Azure/.Net tutorials [here](https://dev.to/patricksameerajayalath) and [here](http://sameerajayalath.blogspot.com/).

Enjoy !!
Material UI + React Final Form = MUI-RFF (forms made easy)
Tags: materialui, react, finalform, typescript
Published: 2020-01-20 03:12:18

In order to integrate [React Final Form](https://final-form.org/react) with a UI component library such as [Material UI](https://material-ui.com), you'll need to create a thin wrapper that passes properties between MUI and RFF components. After searching around for who else has done this, you've stumbled across this project.

Sadly, figuring out the nuances of passing properties across multiple components is non-trivial. It takes a lot of trial and error and hopefully you're writting tests along the way too (hahaha yea, right). Since you are probably in a rush and just want to get onto building features, this repo provides a set of modern and unit tested React components that make it easy to drop into your own Javascript or Typescript project as a small NPM dependency.

Please try things out and review the code first. Take a look at the [demo](https://lookfirst.github.io/mui-rff/), [demo source](https://github.com/lookfirst/mui-rff/tree/master/example), [codesandbox](https://codesandbox.io/s/react-final-form-material-ui-example-tqv09), and the [tests](https://github.com/lookfirst/mui-rff/tree/master/test).

One thing to note in the [demo](https://lookfirst.github.io/mui-rff/) is the ability to control the react form rendering. This is what really motivated me to go with RFF. With a small [configuration tweak to RFF](https://final-form.org/docs/react-final-form/types/FormProps#subscription), it is easy to cut the number of renders down to the bare minimum. This improves performance significantly, especially with larger forms.
Packt Publishing is having a sale!
Tags: beginners, codenewbie, 100daysofcode
Published: 2020-01-20 02:30:51

I just wanted to post this real quick in case some people haven't seen it. Packt Publishing ( packtpub.com) is having a Giant sale. I think It's been going awhile. Everything is $5 each, so if you're looking for any books or videos on programming or technologies now would be a great time to get them. I just bought 3 solid Java books.I don't know when the sale ends, I couldn't find an expiration, so get them while you can!
What you need to know about Leetcode’s Count and Say: My thought process as a beginner.
Tags: algorithms, tutorial, datastructures, codenewbie
Published: 2020-01-20 02:02:07

This is another [Leetcode Problem](https://medium.com/@codechunkers/what-you-need-to-know-about-leetcodes-count-and-say-my-thought-process-as-a-beginner-9d531fb1639b): You are given an integer to generate the nth term of its count and say.The count and say is a way of reading off digits from the previous member. So 1 would read as “One 1” or 11 and 11 would read as “Two 1s” or 21 etc.

<h1>ALGORITHM</h1>
1.Get the first character of the string. This would serve as the previous;
2.Loop through every other character (i.e from the next character after step 1). This would serve as the next character.
3.Compare if step 1 and 2 (previous and next) are equal.
4.If they are equal, increment the global counter.
5.If they are not equal, append the current value of global counter and the previous character (in that order) into a global result StringBuilder. The previous character now becomes the current next character (previous = next). Then reset global counter (count = 1).
6.Outside the loop, append the global counter and previous to the global result.This is majorly for edge cases.


**MY CODE**
```
class Solution {
    public String countAndSay(int n) {
          if (n == 1)
            return "1";
        else {
            return doCounting(countAndSay(n - 1));
        }
    }
    
    private String doCounting(String value) {
        int length = value.length();
        int count = 1;
        StringBuilder result = new StringBuilder();
        int i;
        char previous = value.charAt(0);//initial
        for (i  = 1; i < length; i++) {
            char next = value.charAt(i);
            if (previous == next) {
                count++;
            }else {
                result.append(count).append(previous);
                previous = next;
                count = 1;//reset
            }
        }
        result.append(count).append(previous);

        return result.toString();
    }
}

```

**OUTCOME**
![outcome image]
(https://miro.medium.com/max/1040/1*WSgEFt5g1xnbfDA0SCo4Eg.png)


**IMPROVEMENT**
At first, the solution was a bit slower so I had to scan through to look for a way to make my solution a bit faster. Found out where I got it wrong: For every loop, I was calling value.length(). This should be reusable, so I initialized it to a variable. Did the same thing for charAt(i).
After the cleanups, I got the above scores, which I feel is very OK.


**LESSONS**
Always initialize some library functions to variable to prevent calling it multiple times e.g, value.length(), value.charAt(i) etc. I’m sure you get the point. This also applies to Object creations or instances.

**CONCLUSION**
I hope you keep solving problems by chunking them. Please leave a comment, correction or suggestion (I'd really love that). Thank you.