teleren/devto huggingface dataset:
My 5 favorite CSS tricks I learned this year
Tags: css, html, webdev
Published: 2020-06-27 20:57:50

This year has been very productive for me as i developed numerous UI/UX apps and websites. On the way i've picked up some useful tricks to enhance my designs.

<h4>1. CSS Variables</h4>
CSS variables are useful when we want to apply the same style to common elements. Instead  of adding a complex box-shadow, for example, to common elements we can initialize a variable and use that variable everytime we want to apply that style to an element

We initialize CSS variables with :root and the property we want to set, like so:

```CSS
:root {
    --shadow: 0 1px 3px rgba(0,0,0,0.1);
}
```
And we can then use it in any element we want to apply this box-shadow to:

```CSS
.container {
   box-shadow: var(--shadow);
}
```

<h4>2. Height Media Queries</h4>
Besides for screen width media queries, we can also apply screen height media queries, so devices with smaller screen height can be responsive. As well, when a device rotates its screen, the screen height changes and we need to reflect those changes for responsive purposes.

```CSS
@media only screen and (max-height: 800px) {
    .container {
        height: 95%;
    }
}
```
For screens at 800 or less pixels will change the grid element's height.

<h4>3. Calc Function</h4>
The CSS calc function can be very useful when setting dynamic widths. Say we want an element's width to be based on another element's width.

```CSS
.container {
    width: calc(100%-300px);
}
```
The width of our container element will be based on 100% of its parent container minus 300px, so if a container next to it is 300px, our dynamic container will respond accordingly.

<h4>4. Vertical Alignment</h4>
There are many ways to align an element vertically, But sometimes it can get complicated and not work, due to positioning complications of the parent element. One such method that works everytime is to position an element we want to align vertically, as absolute position and apply the following styles.

```CSS
.container {
    position:absolute;
    top: -50%;
    transform: translateY(50%);
    margin: auto;
}
```
This will vertically align the element to its parent container.

<h4>5. Border-Box Property</h4>
```CSS
.container {
    box-sizing: border-box;
}
```
Border box is one of the most useful properties in CSS. It allows us to create padding on elements while keeping the dimensions of the element uniform. So if we have a container with 300px width and 300px height and a padding of 30px, by default CSS will add those 30px to the container's dimensions thus causing many problems of alignment and other issues in our design. By applying a box-sizing: border box property, we can make all containers uniform in size.
box-sizing can also be used to make inputs, textareas and select boxes, the same size as well, to create a uniform look to our elements.


Website: www.flexrweb.com
Do you have a blog or a YouTube Channel?
Tags: javascript, react, webdev, codenewbie
Published: 2020-06-27 20:37:10

Greetings! How are you doing? Are you a content creator and have a blog or a YouTube channel? Share a link at the discussion section below and I'll check it out.

I have a YouTube Channel where I create coding content. I have been creating tutorials for 11 months now. So far it have been great. I have 38k total views, 870 subsribers, $0 earned. 

It's almost an year now. Although I haven't earned with YouTube yet, I have learnt extra skills like video editing, graphics design, communication skills(still working on this) and more. I have helped others in the field and this have helped me to deepen my knowledge as well.

My goal before an year ends is to reach 1k subscribers. You can check out my channel and subscribe if you find my content helpful. Here is the link: https://youtube.com/chaoocharles

You can also leave a link to your blog or channel at the discussion section below and I'll check it out.

Stay awesome! 💙
Road to Genius: advanced #31
Tags: beginners, javascript, computerscience
Published: 2020-06-27 20:15:54

Each day I solve several coding challenges and puzzles from Codr's ranked mode. The goal is to reach genius rank, along the way I explain how I solve them. You do not need any programming background to get started, and you will learn a ton of new and interesting things as you go.

```JS
function cross(a, b) {
  return [a[1] * b[2] - a[🐼] * 💧[1], a[2] * b[0] - ☃️[0] * b[2], 😈[0] * b[1] - a[1] * b[0]];
}
let out = cross([8, 4, 2], [2, 6, 2]);
let A = out[1];
A = Math.abs(A);

// 💧 = ? (identifier)
// ☃️ = ? (identifier)
// 😈 = ? (identifier)
// 🐼 = ? (number)
// such that A = 12 (number)
```

This challenge is about some pretty simple mathematical matrix operations. We need to fix 4 bugs, which all appear on the same line:
```JS
return [
  a[1] * b[2] - a[🐼] * 💧[1],
  a[2] * b[0] - ☃️[0] * b[2],
  😈[0] * b[1] - a[1] * b[0]
];
```

To solve this we have to carefully analyze the code. The name of the function `cross` already reveals a lot. If you had some algebra you may have heard of the cross-product of two (or more) matrices. If you haven't, or if you already forgot how it works (like me), a quick Google image search gives us the following formula:

![coding challenge extra](https://dev-to-uploads.s3.amazonaws.com/i/t2r1a62be7mz3tmpeyvn.png)

Our code looks very similar to this formula, except for the enumeration (the first element is 0 instead of 1). We can also solve these bugs using our prior knowledge of symmetry, since it's a mathematical function.
The first bug 🐼 has to be 2.
The 2nd bug 💧 has to be `b`.
The third bug ☃️ is `a`.
The final bug 😈 is `a` as well.

![coding challenge answer](https://dev-to-uploads.s3.amazonaws.com/i/plxlmv0nshr4zpeqab92.png)

By solving these challenges you train yourself to be a better programmer. You'll learn newer and better ways of analyzing, debugging and improving code. As a result you'll be more productive and valuable in business. Join me on the Road to Genius and upgrade your programming skills, at https://nevolin.be/codr/
Binary Search in JavaScript
Tags: binary, search, algorithms, javascript
Published: 2020-06-27 19:29:49

---
title: Binary Search in JavaScript
published: true
description: Implementation of binary search in JavaScript
tags: #binary, #search, algorithms, javascript
---

- Binary search works on *sorted arrays*.
- Binary search begins by comparing an element in the middle of the array with the target value.
- If the target value matches the element, its position in the array is returned.
- If the target value is less than the element, the search continues in the lower half of the array. If the target value is greater than the element, the search continues in the upper half of the array.

By doing this, the algorithm eliminates the half in which the target value cannot lie in each iteration.

A quick implementation of binary search in JavaScript

Let say's we have a array and we want to search for `7` and return it's index

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

#### Iterative Solution

```javascript
function BinarySearch(arr, value) {
  let start = 0;
  let end = arr.length - 1;

  while (start <= end) {
    let mid = Math.floor((start + end) / 2);

    if (value === arr[mid]) {
      return mid;
    }
    if (val < arr[mid]) {
      end = mid - 1;
    } else {
      start = mid + 1;
    }
  }

  return -1;
}
```

#### Recursive Solution

```javascript
function BinarySearch(arr, value, start = 0, end = arr.length - 1) {
  let mid = Math.floor((start + end) / 2);

  if (arr[value] === mid) {
    return mid;
  }

  if(start >= end) {
      return -1
  }

  return value < arr[mid] ? BinarySearch(arr, value, start, mid - 1) : BinarySearch(arr, value, mid + 1, end)
}

```

Thanks 

Follow me on twitter - https://twitter.com/_mohit_b
Is there any adult (+18) website developer here ?
Published: 2020-06-27 19:15:43

I use to see demand of every kind of developer out there by recruiters, but never heard of someone looking for a dev for adult website dev work. But i am sure there is a demand somewhere. 

I am interested in how it feel to work on that kind of projects ? Is there requirement on age ? Does that part of the industry allow freelancers or they prefer in-house developers ? Is it something you feel comfortable to talk about ? Anything else you would like to share.

I know it's a particular technical demanding field, i read somewhere a story on how a porn site dev team used Websocket and canvas to avoid Ad Blockers and show Ads.

Thanks
scalac -feature
Tags: scala, scalac
Published: 2020-06-27 19:13:34

---
title: scalac -feature
published: true
description: using scalac -feature flag 
tags: scala, scalac
//cover_image: https://direct_url_to_image.jpg
---

A useful option to turn on for the scala compiler is `-feature`. It emits warning and location for usages of features that should be imported explicitly.

An example such an advanced feature is implicit conversions. An implicit conversion is an implicit value of type `A => B`. e.g.

```scala
def main(args: Array[String]): Unit = {
    val s = "Hello, world!"
    val len: Int = s
    println(len)
}

implicit def stringToInt(s: String): Int = s.length
```

Compiling this piece of code with the `-feature` scalac flag enabled gives the following warning:
```
[warn] Main.scala:8:16: implicit conversion method stringToInt should be enabled
[warn] by making the implicit value scala.language.implicitConversions visible.
[warn] ----
[warn] This can be achieved by adding the import clause 'import scala.language.implicitConversions'
[warn] or by setting the compiler option -language:implicitConversions.
[warn] See the Scaladoc for value scala.language.implicitConversions for a discussion
[warn] why the feature should be explicitly enabled.
[warn]   implicit def stringToInt(s: String): Int = s.length
[warn]                ^
[warn] one warning found
```
Kotlin Type Aliases
Tags: kotlin
Published: 2020-06-27 19:06:49

---
title: Kotlin Type Aliases
published: true
date: 2020-06-27 19:06:09 UTC
tags: 
    - Kotlin
canonical_url: https://michael.codes/posts/kotlin-typealias/
---

Something I recently learned about in Kotlin, that I do not see talked about very often, are type aliases. Type aliases allow for custom names to be specified for existing types. This is convenient for long or complex types.

These are particularly useful for function types that have particularly complex syntax. For example if we have a function that takes a handler function as a parameter.

```
fun handleEvent(handler: (type: EventType, message: String) -> Unit) {
  // Some logic...
}
```

We can use a type alias to make a bit more readable by defining a name to the function type.

```
typealias EventHandler = (EventType, String) -> Unit

fun handleEvent(handler: EventHandler) {
    // Some logic...
}
```

Note that type aliases are not creating new types. Behind the scenes the Kotlin compiler takes the custom name and replaces it with the actual type. This means you can work with the original type and the alias interchangeably.

```
typealias CharacterString = String

fun pl(s: CharacterString) = println(s)

fun main() {
  val test1: CharacterString = "Test String"
  val test2: String = "Test String 2"

  pl(test1)
  pl(test2)
}
```

Obviously, overusing this feature could result in less readable code, but used appropriately can be very useful. For more details see the [Type Aliases](https://kotlinlang.org/docs/reference/type-aliases.html) section of the Kotlin documentation.
What would you choose if you'd go against the trends?
Tags: discuss, webdev
Published: 2020-06-27 18:50:15

A new site these days:

1. Node
2. Babel
3. React / Vue
4. Redux / GraphQL / Saga
5. CSS-in-JS / Styled Components
6. Universal Single Page App
7. Code splitting
8. TypeScript

This seems like a typical combination that "everyone" wants to have, and what everybody tells everyone else to learn and use.

But if you were given the choice to do otherwise, which techs would you go for instead and why?

In case the above list is what you would choose, what would you choose instead if your most liked half of the choices were banned?
Wow can python do that 🤔
Tags: python, webdev, todayilearned, beginners
Published: 2020-06-27 18:49:36

Hey, everyone. I hope you find this post interesting and useful.

For devs who are new here, please check out my previous posts in the series, I feel you will definitely include them your arsenal.

![Hello](https://media.giphy.com/media/l4FsCR2hFJnGh18IM/giphy.gif)

Let's get things started 💨
As a ritual we follow in the series, we discuss three libraries in the post. 

Let's see a glance on their names 👀
- Bokeh
- Chartify
- Falcon

Let's dive deep 🌊

## [Bokeh](https://bokeh.org/)

![Logo](https://static.bokeh.org/logos/logotype.svg)

Bokeh is an interactive visualization library for modern web browsers. It provides elegant, concise construction of versatile graphics, and affords high-performance interactivity over large or streaming datasets. Bokeh can help anyone who would like to quickly and easily make interactive plots, dashboards, and data applications.

[Tutorials](https://mybinder.org/v2/gh/bokeh/bokeh-notebooks/master?filepath=tutorial%2F00%20-%20Introduction%20and%20Setup.ipynb)
[Docs](https://docs.bokeh.org/en/latest/index.html)

## [Chartify](https://github.com/spotify/chartify)
Chartify is a Python library that makes it easy for data scientists to create charts.

Consistent input data format: Spend less time transforming data to get your charts to work. All plotting functions use a consistent tidy input data format.

Smart default styles: Create pretty charts with very little customization required.

Flexibility: Chartify is built on top of Bokeh, so if you do need more control you can always fall back on Bokeh's API.

**Chartify is from [`Spotify`](https://spotify.github.io/)**

[Docs](https://chartify.readthedocs.io/en/latest/)
[Tutorial](https://github.com/spotify/chartify/blob/master/examples/Chartify%20Tutorial.ipynb)

## [Falcon](https://falconframework.org/)
![Logo](https://falconframework.org/img/logo.svg)
Falcon is a blazingly fast, minimalist Python web API framework for building reliable app backends and microservices. The Falcon web framework encourages the REST architectural style. Resource classes implement HTTP method handlers that resolve requests and perform state transitions.
Falcon complements more general Python web frameworks by providing extra performance and flexibility wherever you need it.

TBH `Falcon` is really great. There is this comparison on the website which captured my eyeballs 👇.

![Amazing](https://dev-to-uploads.s3.amazonaws.com/i/qhzfr60m616rfs7s0cqp.png)

That's all for this week. See you all next week 🙌🏻.


![Thanks](https://media.giphy.com/media/3oz8xIsloV7zOmt81G/giphy.gif)

Peace ✌🏻,
Rohith Gilla
How to 'Not Advertise' Your API Key in React Apps
Tags: react, javascript, security, webdev
Published: 2020-06-27 18:42:32

Update note: I have revised this article to be more specific about which kind of API I'm talking about after receiving the first several comments. 
____
In this article, I talk about how to make your frontend API key environment specific. This is for a client-safe key that you would need to use for Google maps or Stripe, for example. I am NOT talking about an AWS key. 

**Why you shouldn't advertise your frontend API key:** 

When my instructor told me to never push code to Github that had my API key on it, I wondered how it could possibly matter. His answer was essentially, web crawling software is all over the internet and looks through places like Github, searching for low hanging fruit- in other words a frontend API key that is not environment specific. So how do you make it environment specific? 

**Here’s how in 4 steps:** 

(1) In the root of your directory in your React app, created a file called .env

![file directory in react](https://dev-to-uploads.s3.amazonaws.com/i/p766awjoncdzt7isgaa2.png)

(2) Inside of this file, type: `REACT_APP_API_KEY=[key]`. Make sure to remove the brackets `[ ]`.Example: 

![.env file](https://dev-to-uploads.s3.amazonaws.com/i/fch1yn90tba2xdfyxspl.png)

(3) In your .gitignore file, add `.env` on a new line (see line 18)

![.gitignore file](https://dev-to-uploads.s3.amazonaws.com/i/qkueitevc73jfywnl2s1.png)

(4) You can then use your key in your app by declaring a variable and set it equal to: `process.env.REACT_APP_API_KEY`
Below is an example of how it might declared and used. 

![example of using key in app.js](https://dev-to-uploads.s3.amazonaws.com/i/1931w25r0s7qb8rnyhxq.png)
Day 2 of #30DaysOfCode
Tags: go, codenewbie, motivation, challenge
Published: 2020-06-27 18:11:37

Today, I started my day with writing Go Code. I learnt about Byte data type, saving data to a file and then reading them. I wrote some error handler function to handle errors in my program. After writing code for all of this, I wrote a function to generate pseudo-random numbers. I had to dig into the documentation a lot deeper than I expected to get it working. Fun fact: Randon number generation in Computer Science still is an impossible task.

After generating pseudo-random numbers, my program was almost over but it needed a bit of testing. So, I learnt some testing in Go. One thing that I want you to take out of this post is that testing is a bit different in Go than other languages. You don't need any testing frameworks like mocha, jasmine, selenium or RSpec. Go has a built-in testing functionality that lets you test Go code. All you need to do is to end your code file with _test.go and run the go test command to test your program. Go will automatically run all the tests in your files.

After writing my test and verifying them, I was happy and satisfied with myself and I started writing this post. So, here we are.

Alright! that's all for today and hopefully, I will see you in my next post.

<br/>
Image Credit: <a href="https://www.instagram.com/dev.kyle" target="_blank" rel="noopener noreferrer">Kyle The Dev</a>

Connect With Me:
Youtube: <a href="https://www.youtube.com/c/ShubhamSauravYT" target="_blank" rel="noopener noreferrer">ShubhamSauravYT</a>.
Twitter: <a href="https://www.twitter.com/hiShubhamSaurav" target="_blank" rel="noopener noreferrer">@hiShubhamSaurav</a>
Instagram: <a href="https://www.instagram.com/hiShubhamSaurav" target="_blank" rel="noopener noreferrer">@hiShubhamSaurav</a>
Facebook: <a href="https://facebook.com/hiShubhamSaurav" target="_blank" rel="noopener noreferrer">@hiShubhamSaurav</a>
Creating a CSS Typing Effect (video tutorial)
Tags: css, html, codenewbie, beginners
Published: 2020-06-27 17:53:43

Typing effects on websites' landing page are common nowadays. In the following tutorial I will show you how easy it is to animate text using CSS.

You Enjoy the content? [Help me reach 1k subscribers on my YouTube Channel] (https://www.youtube.com/channel/UCe8uN9zoKksCb1hfw61myRw?sub_confirmation=10)

{% youtube LGZ5tZV4sKs %}
Array slice v/s splice once and for all!
Tags: javascript, webdev, tutorial
Published: 2020-06-27 17:32:44

Hey There! 👋🏽

If you are like me and have spent most of your recent years coding in Javascript you definitely have come across this conundrum: There is this array and you want to do an operation on it to get a transformed version. You know there exists a **slice** as well as a **splice** method on the **Array** prototype but still, open google, type *javascript array slice*, then *javascript array splice*, compare them and then make your decision, **every single time**!

Do you wish to break this loop and become a JS array ninja who just *knows* which one of the two is to be used in which case? Then follow along.

### Backdrop
To the uninitiated, Javascript provides us with two methods on the **Array** prototype which look ever so similar but function worlds apart. There is

#### Array.prototype.slice
| Returns a section of the original string **without** changing the original string
```
let str = [1,2,3,4,5,6,7];
console.log(str.slice(4)); // [5, 6, 7]
console.log(str) // [1,2,3,4,5,6,7];
```

#### Array.prototype.splice
| Changes the contents of the array by **removing/replacing** existing items
```
let str = [1,2,3,4,5,6,7];
console.log(str.slice(4)); // [5, 6, 7]
console.log(str) // [1,2,3,4];
```

Here is a **mnemonic** technique that you can use so that there is no need for another Google search in your entire life while working on JS arrays. 

### Slice v/s Splice
Notice that splice has an extra **p** in the method name. Because of that, it **pulls** the items out of the original array and hence modifies it, and thus, slice does **not** pull items out of the original array.
Also, because it *pulls* items, it can also *push* items into the array. 

So let's sort this out:

#### slice(startIndex, endIndex)
It takes a start index and an end index (excluded) and slices those array items and gives back to you. 
```
let str = [1,2,3,4,5,6,7];
console.log(str.slice(2, 4)); // [3, 4]
console.log(str) // [1,2,3,4,5,6,7]; // not modified
```

#### splice(startIndex, number, items)
It takes a start index too, but, also pulls the items out of the original array (the number of items can be specified in the number argument) and all the other arguments after than will be pushed into the array!
```
let str = [1,2,3,4,5,6,7];
console.log(str.slice(2,4,8,9)); // [3, 4, 5, 6]
console.log(str) // [1, 2, 8, 9, 7];
```
Here's a graphic to cement that understanding
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/8d0r07xdvrs91zd486xb.png)

If you liked that, feel free to follow me on twitter where I post my other JS related sketchnotes frequently.
{% twitter 1276471152517341184 %}

Cheers!
Go - Safe truncate string
Tags: go
Published: 2020-06-27 17:31:47

---
title: Go - Safe truncate string
published: true
description: 
tags: go
//cover_image: https://direct_url_to_image.jpg
---

```go
package main

import (
	"fmt"
)

// Truncate string.
func TruncateString(str string, length int) string {
    if length <= 0 {
        return ""
    }

    // This code cannot support Japanese
    // orgLen := len(str)
    // if orgLen <= length {
    //     return str
    // }
    // return str[:length]

    // Support Japanese
    // Ref: Range loops https://blog.golang.org/strings
    truncated := ""
    count := 0
    for _, char := range str {
	truncated += string(char)
        count++
        if count >= length {
            break
        }
    }
    return truncated
}

// Main
func main() {
	dataList := [][]interface{} {
		{"drink", 3, "dri"},
		{"drink", 6, "drink"},
		{"drink", 0, ""},
		{"drink", -1, ""},
		{"drink", 100, "drink"},
		{"pub", 100, "pub"},
		{"こんにちは", 3, "こんに"},
	}
	for _, dl := range dataList {
		r := TruncateString(dl[0].(string), dl[1].(int))
		if r != dl[2].(string) {
			fmt.Printf("ERROR: got=%s, want=%s", r, dl[2].(string))
		}
	}
}
```

~~https://play.golang.org/p/QHFLlXr8v8i~~
https://play.golang.org/p/iakC8xxTlFI

**Reference**
https://play.golang.org/p/EzvhWMljku

The below code raises an error of slice.

```go
package main

import (
	"fmt"
)

func main() {
	s := "drink"
	r := s[:20] // error
	fmt.Println(r)
}
```

https://play.golang.org/p/7IfclYXADoW