teleren/devto huggingface dataset:
Magic with vim global command
Tags: vim
Published: 2019-06-22 17:04:59

---
title: Magic with vim global command
published: true
description: How to use global command to filter files
tags: vim
---

# Intro
The vim global command is a very powerful command, of course 
in the comments sections many more will appear, just to give you
an idea on how useful it can be let's look to some situations.

## create a new file based on a global pattern
+ https://stackoverflow.com/a/56716368/2571881
+ https://unix.stackexchange.com/a/257472/3157

Let's say we have this file:

    this line contains cat
    this contains dog
    other nothing
    more one with fish
    this line contains cat
    this contains dog

And we want a new file with the lines containing "dog" and delete them from the original file.


    :g/\<dog\>/ .w! >> dog.txt | d

# Copy lines with a pattern to a register

First let's clean the register we want to use

    :let @a=''

Now we can copy the lines with a pattern to it 

    :g/pattern/y A
    :g/pattern/ .,+5 y A 

The uppercase version of the register allow us to append content to a register, otherwise it will be overwrited.

To paste a register just

    :0 put a

The above command says: at the line zero put the content of the register 'a'

    " move TITLE down one line
    :g/TITLE/ m+1   

    " copy 'pattern' to <line number>
    :g/pattern/t<line number> 

    " erase even lines
    :g/^/if line('.') % 2 == 0 | norm! cc

    " erase odd lines
    :g/^/if line('.') % 2 | normal! cc

    " add a line before a pattern
    :g/^wget/ normal O
No max/min function for integer in GoLang 
Tags: go
Published: 2019-06-22 16:45:43

---
title: No max/min function for integer in GoLang 
published: true
description: golang
tags: golang
--- 
![](https://thepracticaldev.s3.amazonaws.com/i/cobjirtkqvv6qyilq5un.jpg)

There is no min/max function in the core golang module. Why?  Because floating point numbers are not easy to compare.

To avoid trouble, the **min/max functions** are provided in the **GoLang math package** as built in functions.

    math.Min(float64, float64) float64
    math.Max(float64, float64) float64

So that is for floating points. What if you want to compare integers? Then you have to write the functions yourself,

    func Min(x, y int64) int64 {
     if x < y {
       return x
     }    
     return y
    }
    
    func Max(x, y int64) int64 {
     if x > y {
       return x
     }
     return y
    }

More on golang: https://golangr.com
Image converter in python
Tags: images, convert
Published: 2019-06-22 16:36:06

---
title: Image converter in python
published: true
description: images, image, convert
tags: images, convert
---
![](https://thepracticaldev.s3.amazonaws.com/i/1bnkx4nwpdgukcshfxai.png)

It's easy to create an image converter gui in Python. You can use the **PyQt module** to create desktop software. Then simply design your user interface it in designer and then load it with the code.

In the case of this app, just link the button clicks to the command line program "convert".
         
        # connect clicks to callback functions
        self.pushButtonDir.clicked.connect(self.onClick)
        self.pushButtonConvert.clicked.connect(self.onConvert)
        
    def onClick(self):
        self.thedir = str(QFileDialog.getExistingDirectory(self, "Select Directory"))
        print('select dir ' + self.thedir)

    def onConvert(self):
        images = glob.glob(self.thedir + "/*")
        print(images)
        for image in images:
            # no dot in filename allowed
            newImage = image[:image.index(".")] + self.comboBox.currentText()
            cmd = "convert " + image + " " + newImage
            os.system(cmd)

More on PyQt:

* https://github.com/petercour/image-converter-pyqt
* https://pythonbasics.org/pyqt/
* https://pythonprogramminglanguage.com/pyqt-tutorials
ALGORITHM CHALLENGE: 2
Tags: rust, algorithms, interview
Published: 2019-06-22 15:56:55

---
title: ALGORITHM CHALLENGE: 2
published: true
description: 
tags: rust, go , algorithm, interview
---

# Challenge
>
Return the number (count) of vowels in the given string.
We will consider a, e, i, o, and u as vowels for this Kata. The input string will only consist of lower case letters and/or spaces.


# Solution

#### rust

```rust
fn get_count(string: &str) -> usize {
  let vowels: &str = "aeiou";
  let mut vowels_count: usize = 0;
  for c in string.chars() {
      if vowels.contains(c) {
          vowels_count = vowels_count + 1; 
      }
  }
  vowels_count
}
```
Practice Makes Perfect
Tags: help, discuss, beginners
Published: 2019-06-22 15:49:58

Coding student here! I am studying Web Development with the [Web Developer Bootcamp](https://www.udemy.com/the-web-developer-bootcamp/) on Udemy. I have learned so much! I am working with Bootstrap4 now and will be moving on to Javascript soon. The only issue I have now is, I need more practice. I am hoping some of you can give me some ideas for ways I might be able to apply what I've learned. Our instructor does give us some great exercises, but I feel I need more...I am also following the FreeCodeCamp course, which is helpful. Do you guys have any other ideas? Homework! I need homework!
How to link to a specific gist version in dev.to
Tags: question
Published: 2019-06-22 15:49:02

---
title: How to link to a specific gist version in dev.to
published: true
description: 
tags: question
---

The syntax to link to a specific gist file from `dev.to` is:

```
{% gist https://gist.github.com/CristinaSolana/1885435 file=gistfile1.md %}
```

but how to link to a specific gist version of that file? 

I tried to replace the above url with url to that specific version, but got `500 Internal` error when publishing it.
JavaScript and Scope VI - Closures
Tags: javascript
Published: 2019-06-22 15:38:54

In [JavaScript and Scope II](https://blog.toddbiz.com/blog/2019-06-03-javascript-and-scope-ii/) we saw that function scope is not determined by where a function is run. Instead, it is determined by where a function is declared. 

```js
var i = 10;

function foo() {
  var i = 2;
  
  function bar() {
    i = i + 1;
    console.log ('value of i when bar is declared inside foo: ', i);
  }
  
  bar();

}

foo(); // logs 3
```
<div class="jsfiddle-link">
  <a href="https://jsfiddle.net/tchaffee/x3f1Ln8e/" target="_blank">Edit in JSFiddle</a>
</div>

But the example above doesn't fully illustrate lexical scope because the `bar` function is also *run* inside the `foo` function. Let's run the `bar` function outside of the `foo` function.

```js
var i = 10;

function foo() {
  var i = 2;
  
  function bar() {
    i = i + 1;
    console.log ('value of i when bar is declared inside foo: ', i);
  }
  
  return bar;
}

var barFunc  = foo();

barFunc(); // Runs in global scope but logs 3
```
<div class="jsfiddle-link">
  <a href="https://jsfiddle.net/tchaffee/so324k6x/" target="_blank">Edit in JSFiddle</a>
</div>

In the code above, we no longer run `bar` inside of `foo`. Instead we return the inner function without running it. Then we run the function on the last line of code: it runs in the global scope. Most importantly it runs *after* `foo` is done running. But it does not use the global `i` variable. Instead it uses the `i` variable from the function that has already finished running!

The official name for what you just saw is closure. That's how simple closure is. All closure means is that even when a function is run outside of the scope it was declared in, it still uses the scope from where it was declared. In this case, inner function `bar` uses the scope of outer function `foo`.  This is true even though `foo` has stopped running by the time we run `bar`. 

This breaks our expectation that the scope of `foo` no longer exists when it stops running.
Micro Dark Theme
Tags: css, theming, responsive
Published: 2019-06-22 15:28:07

---
title: Micro Dark Theme
published: true
description: Achieve a dark theme in <10 lines of generic CSS
tags: CSS, theming, responsive
---

I'm rewriting my personal website at the moment to make it easier to update and add things to. In the process I'm trying to keep things as simple as possible.

When I started designing it, I decided to keep the colour scheme completely black and white, with a few splashes of colour. What I realised was that some might prefer a darker colour scheme as opposed to the brilliant white pages I was developing.

But in my mission for simplicity I was determined to use the simplest implementation to achieve my dark theme.

It just so happens that the W3C is drafting up a new standard for a CSS media query that indicates whether the user has requested a light or dark colour theme for the current website. A few browsers support this today including Chrome, Firefox and Safari. See [MDN](https://developer.mozilla.org/en-US/docs/Web/CSS/@media/prefers-color-scheme) for the details.

By offloading the responsibility of theme preference to the browser, a dark theme implementation can be as simple as a few lines of CSS:

```css
      #root {
        background: white;
      }     
 
      @media (prefers-color-scheme: dark) {
        #root, img, .no-invert {
          filter: invert(100%);
        }
      }
```

The way this works is fairly straight-forward:
 - When the OS or browser "dark mode" is activated, the CSS in the media tag is applied. 
 - The `#root` element is inverted from a white background with black text to black with white text (the background colour is required for this to work).
 - Elements _within_ the root element are inverted _again_ to appear as they normally do.

![](https://thepracticaldev.s3.amazonaws.com/i/58wzavoz8hkpxyuv7n74.gif)

As expected, elements inverted twice are displayed correctly - see the pills in the top-right:

![](https://thepracticaldev.s3.amazonaws.com/i/8o2p9utue50m5uwvy54f.png)

And for some interesting modifications, other filters could be used in conjunction with `invert()` such as `contrast()`:

![](https://thepracticaldev.s3.amazonaws.com/i/ai9ph9tmltwbkrm3gjt6.png)
![](https://thepracticaldev.s3.amazonaws.com/i/al6imzkkznuhb88l7djp.png)

Oh and if you hadn't already guessed, there's also a draft for `prefers-contrast` in the works - [find the draft here](https://drafts.csswg.org/mediaqueries-5) - so that the user can avoid a low contrast theme altogether with a bit of CSS!

## Fin

Thanks for reading! Follow me for more posts like this 🚀
How do you store/manage your knowledge?
Tags: help, learning
Published: 2019-06-22 15:12:58

---
title: How do you store/manage your knowledge?
published: true
description: There is a lot to learn out there... and a lot to forget. How do you organize your knowledge and references?
tags: help,learning
---

I may be obsessed with this question for the last few weeks, as I started reading quite a few articles and began reading programming books. I know that I can't keep all the new information in my memory, so I need a preferably simple system to organize them.

The information I want to organize mainly comes in the form of online articles, interesting repositories/projects, notes to books I read, (YouTube) videos, perhaps a few PDFs and plain old text notes.

So far I haven't found the proper solution to my problem. I basically tried Pocket and Memex and had a look at Evernote. I am keen to learn how you solved this problem for yourselves.

I can't be the only one struggling with this, right?
Blocking external connections to Docker
Tags: docker, iptables, firewall, devops
Published: 2019-06-22 14:45:58

On Linux, Docker manipulates iptables rules to provide network isolation, by default, **all external source IPs are allowed to connect to the Docker daemon** :/

To allow only a specific IP or network to access the containers insert the rules below in iptables file **`/etc/sysconfig/iptables`**

In this case we will block all connections on port 80 and allow only the Office IP.

```bash
-N DOCKER-USER
-I DOCKER-USER -p tcp --dport 80  -j DROP
-I DOCKER-USER -p tcp --dport 80 -s 185.2.46.131 -m comment --comment "My Office" -j ACCEPT
```
After add the rules restart iptables and Docker, after it check the access.


### What we are doing here

`-N DOCKER-USER` —  The first rule create the chain used by Docker
`-I DOCKER-USER -p tcp --dport 80  -j DROP` —  All connections in port 80 are blocked
`-I DOCKER-USER -p tcp --dport 80 -s 185.2.46.131 -m comment --comment "My Office" -j ACCEPT` —  Allow Office IP


Use `iptables -nL DOCKER-USER` to check the rules:
```bash
[root@server ~]# iptables -nL DOCKER-USER
Chain DOCKER-USER (1 references)
target     prot opt source               destination        
ACCEPT     tcp  --  185.2.46.131    0.0.0.0/0            tcp dpt:80 /* My Office */
DROP       tcp  --  0.0.0.0/0            0.0.0.0/0            tcp dpt:80
RETURN     all  --  0.0.0.0/0            0.0.0.0/0          
[root@server ~]#
 ```
Now all external connections on port 80 are blocked
![Ok](https://media.giphy.com/media/D6WuLOKOpR2fK/giphy.gif)
back-to-front or front-to-back?
Tags: help, java, angular, webdev
Published: 2019-06-22 10:34:02

---
title: back-to-front or front-to-back?
published: true
description: 
tags: help, java, angular, webdev
---
For a course I'm taking next semester I will be building a web app. It's nothing very complex - different types of users can view and create/update different types of stored information. The point of this course is more the opportunity to try out new technologies than to create a great product. 

I intend to use Spring (or Spring Boot? I haven't yet figured out the difference) for the backend and probably Angular for the frontend. I have never used either of these frameworks before, nor do I have any idea how they work.

Which side should I start working from? I'd at least like to be able to make a start on figuring out one end before I start to confuse myself by mixing the two.

I've tentatively selected Angular over React or Vue for the frontend because I've heard it's popular / in demand here in New Zealand, but is there a solid reason I should consider using something else?

Do you know of any extremely beginner-friendly resources I should look at for any of these frameworks? I'm hoping to spend the next couple of weeks starting to get familiar with them before the semester begins.
freeCodeCamp's Random Quote Machine project built in Elm
Tags: elm, freecodecamp, webdev
Published: 2019-06-22 13:50:27

---
title: freeCodeCamp's Random Quote Machine project built in Elm
published: true
description: 
tags: elm, freecodecamp, webdev
cover_image: https://thepracticaldev.s3.amazonaws.com/i/3allp5h8h9hu3ju86bxs.png
---

[freeCodeCamp](https://www.freecodecamp.org/) has a nice [collection of projects](https://learn.freecodecamp.org/front-end-libraries/front-end-libraries-projects) that they describe for you to build to improve your front-end development skills.

Since I want to get better at building web apps with Elm, I thought I'd tackle them one by one.

I recently completed the [Random Quote Machine](https://learn.freecodecamp.org/front-end-libraries/front-end-libraries-projects/build-a-random-quote-machine/) project which I thought I'd share with you all.

Here's my [demo](https://dwayne.github.io/elm-random-quote-machine/) and you can find the code for it [here](https://github.com/dwayne/elm-random-quote-machine).

If you read the code you will learn the following:

- How to deal with randomness.
- How to fetch JSON data and decode it.
- How to build URLs.
- How to use CSS transitions to enhance an Elm app.

> Exposure to high quantity, high quality examples of expertise is one of the two main factors that dictate how quickly and effectively people learn new skills. (*The other is deliberate practice.*) ~ Kathy Sierra, [Badass: Making Users Awesome](http://shop.oreilly.com/product/0636920036593.do)

In the future I may write a step by step tutorial about it. Show some love if you'd like that. :)
A Code For Fun
Tags: go, code
Published: 2019-06-22 12:44:34

---
title: A Code For Fun
published: true
description: generate one random number and another one until they match
tags: #Go #golang #code
---

I was bored. I couldn't code anything for my work or even revise some past work. I felt too lazy to do anything. So I sit down and kept thinking.. until an idea hit my mind.

I thought how many times does the auto-generated random number need to match another auto-generated random number. SO I thought of coding this question in code. As you know I love [Go](https://dev.to/devabanoub/why-i-love-go-h3c) so I choose it to write my little code.

In code, I generated a random number and assigned it into x. Then generated another random number and assigned it to y. If x != y then I re-generate y random number until it matches the x random number. I added a counter for the false guesses of the random number.

My thinking conclusion is __I need somewhat fixed number of guesses to match two random generated numbers__ as you can see in the [video on YouTube](https://youtu.be/pRKrl-83ZTc).

I published the [code on my github here](https://github.com/DevAbanoub/Just_A_Developer/blob/master/Go/match-random-number-with-another-generated-random-number.go) and this is the code itself.

```golang
package main

import "fmt"
import "math/rand"

func main() {
	x := rand.Intn(33)
	y := rand.Intn(33)
	numberOfFalseGuesses := 0
	
	for x != y {
		fmt.Printf("x = %v and y = %v\n", x, y)
		y = rand.Intn(100)
		numberOfFalseGuesses++
	}
	fmt.Printf("finally x = y = %v\n", x)
	fmt.Printf("number of false guesses are %v", numberOfFalseGuesses)
}
```

See you next blog. Keep in touch.
Python Checklist: Publishing a package to PyPi
Tags: python, productivity, opensource, beginners
Published: 2019-06-22 12:23:16

*(Originally published on [https://github.com/prahladyeri/CuratedLists/](https://github.com/prahladyeri/CuratedLists/blob/master/check_lists/python-pypi.md))*

# Checklist: Publishing a package to PyPi

1. Register an account on [PyPi](https://pypi.org/) if you don't have one.
2. Install `setuptools` and `twine` using `pip` if they aren't already. Create a `setup.py` in your source folder as follows (check out [setuptools docs](https://setuptools.readthedocs.io) for more detailed setup options):

		# replace:
		# <your_package> with your actual package name.
		# <you> with your name.
		# <your_email> with your public email address.
		# <your_github_repo_url> with your github project's url.
		from setuptools import setup, find_packages
		
		s = setup(
			name="<your_package>",
			version="1.0.0",
			license="MIT",
			description="Foo App",
			url='<your_github_repo_url>",
			packages=find_packages(),
			install_requires=[],
			python_requires = ">= 3.4",
			author="<you>",
			author_email="<your_email>",
			)


3. Optional: Bump up the version number (and git commit) if this isn't your first release:

		git add . && git commit -m "chore: released 1.0.1" && git push

4. Run `python setup.py sdist` from your source folder to generate a source distribution.
5. Optional: Sign the newly generated package with your `gpg` signature:

		gpg -a --detach-sign dist/<your-package>-1.0.0.tar.gz
	
6. Upload your package using `twine`:

		twine upload dist/<your-package>-1.0.0.tar.gz -u <your-pypi-username> -p <your-pypi-password>
	
	If you've signed the package, then you may also add the signed .asc file as the argument like this:
	
		twine upload dist/<your-package>-1.0.0.tar.gz dist/<your-package>-1.0.0.tar.gz.asc -u <your-pypi-username> -p <your-pypi-password>

7. Visit <https://pypi.org/project/your_package> to verify that your package has been uploaded.
8. Run `pip install <your_package>` to verify the package installation using pip package manager.
9. Optional: Tag the commit with the new version number:

		git tag "1.0.1"
		git push --tags
What I learned after a year and half of developing
Tags: webdev, javascript, css, vscode
Published: 2019-06-22 12:21:20

I started to code in January 2018. After more than a year I changed a lot of things in my development process.

First of all, I am a frontend developer. This means that I use HTML, CSS, JS.

Let's start with a list:
- Atom → Sublime Text → VS Code.
I started to code on codecademy (it's first in [Google](https://www.google.com/search?client=firefox-b-d&q=learn+to+code)). My first HTML code I copied to Atom and saved on a computer. I have chosen Atom because a long time ago I've searched for a good text editor and see a lot of recommendations. Next, I switched to Sublime Text and loved it. I write a lot of non-realise websites and some realized. Next, I heard about the VS Code. It's been very complicated for me but after a few weeks, I completely switched.
- Beautify → Prettier. It's very hard to format code by hands, so I need to automize this process. I have used Beautify but recently switched to Prettier with config files.
- Default monospace font → Fira Code. The font is a very important thing in the development process. I didn't think much of it before. And once I saw in Twitter some interesting font with a new thing for me — ligatures support. It was Fira Code. Now it's a very popular font.
- jQuery → clean JS. I started to code in JS from jQuery tutorial on YouTube. The tutorial said that jQuery is cleaner, smaller, easier and with jQuery you can write a solution for the task in a few strings that take in JS 200 strings. But after some time I've understand that clean JS has more support, cleaner, easier and takes a minimum of space with default support in browsers.
- CSS → SASS. Just love this ```parent { child }``` syntax.
- Jekyll → Gatsby. Gatsby is a more progressive static site generator with a lot of default optimizations.
- Lighthouse → PageSpeed Insights. So I love green scores in Lighthouse and love it. Recently Google moved Lighthouse to the web with more stability.

If I remember more, I'll extend an article.

Write in comments your openings.
Covering more micro frontends and styled-components v5, the second episode of the Tech Red Pill video podcast is here!
Tags: javascript, webdev, react, css
Published: 2019-06-22 12:19:28

---
title: Covering more micro frontends and styled-components v5, the second episode of the Tech Red Pill video podcast is here!
published: true
description: The second instalment of the Tech Red Pill video podcast featuring Patrick.
tags: javascript, webdev, react, css
cover_image: https://thepracticaldev.s3.amazonaws.com/i/gu7fur8cy7p8fjvvpiw2.png
---

I'm happy to announce that the second episode of Tech Red Pill is here!

Check out our last episode here: [Micro Frontends: a deep dive into the latest industry trend.](https://dev.to/parkroolucas/micro-frontends-a-deep-dive-into-the-latest-industry-trend-3i7a)

If you are unfamiliar, we cover a variety of tech-related topics on this weekly video podcast, mostly focused around the latest tech news and our opinions from a professional standpoint.

In this episode we review a micro-frontends practical implementation and provide our further thoughts in this issue; however, the majority of the video is dedicated to a thorough review of the upcoming styled-components v5, and some longstanding issues with the library in terms of philosophy and future direction.

{% youtube _tlcI1dLM7s %}

Happy coding!