teleren/devto huggingface dataset:
Pass Request buffer through Redis
Tags: javascript, redis, express, snippet
Published: 2020-01-20 13:24:36

_Originally posted on November 13th, 2017_ ([more info](https://dev.to/adamkdean/migrating-to-dev-to-190))

In a follow up to my [last post](https://dev.to/adamkdean/pipe-stream-to-express-1jm6), the following code takes an Express request, performs an external request, stores that response in a buffer which it then stores in Redis, which it then reads back, converts back into a buffer and sends that back to the Express response.

This doesn't store the headers or status code in Redis but it could easily be done.

This allows playback of a request/response cycle. Interesting concept really.

```
'use strict'

const express = require('express')
const request = require('request')
const streamBuffers = require('stream-buffers')
const through2 = require('through2')
const redis = require('redis')

const client = redis.createClient()
client.on('connect', () => { console.log('redis connected' )})
client.on('ready', () => { console.log('redis ready' )})
client.on('reconnecting', () => { console.log('redis reconnecting' )})
client.on('error', () => { console.log('redis error' )})
client.on('end', () => { console.log('redis end' )})

const app = express()
app.use('/', (incomingRequest, outgoingResponse) => {
  const outgoingRequest = request('http://via.placeholder.com/800x600?text=example')
  const randomKey = Math.random().toString(36).substr(2)
  const stream = new streamBuffers.WritableStreamBuffer()
  
  let _statusCode = null
  let _headers = null
  
  outgoingRequest.pipe(through2(function (chunk, enc, callback) {
    stream.write(chunk)
    callback()
  }))
  
  outgoingRequest.on('end', () => {
    const contents = stream.getContents()
    const base64 = contents.toString('base64')
    client.set(randomKey, base64)
    client.get(randomKey, (err, reply) => {
      const newBuffer = new Buffer(reply, 'base64')
      outgoingResponse.set(_headers).status(_statusCode)
      outgoingResponse.end(newBuffer)
      client.del(randomKey)
    })
  })
  
  outgoingRequest.on('response', (incomingResponse) => {
    _statusCode = incomingResponse.statusCode
    _headers = incomingResponse.headers
  })
})

app.listen(8000, () => {
  console.log('listening on 8000')
})
```
Pipe Stream to Express
Tags: javascript, streams, express, snippet
Published: 2020-01-20 13:23:20

_Originally posted on November 13th, 2017_ ([more info](https://dev.to/adamkdean/migrating-to-dev-to-190))

As part of a project I'm working on, I need to grab some data via HTTP/S and transmit it as binary, but with access to it's headers. The following is a quick proof of concept to listen for HTTP requests with Express, request an external image on request, and pipe the response back through to the Express response socket while having access to response metadata such as headers.

```
'use strict'

const express = require('express')
const request = require('request')
const through2 = require('through2')

const app = express()
const imageUrl = 'http://via.placeholder.com/800x600?text=example'

app.use((incomingRequest, outgoingResponse) => {
  const outgoingRequest = request(imageUrl)
  const bufferOnPipe = through2(function (chunk, enc, callback) {
    this.push(chunk)
    callback()
  })
  const bufferedResponse = outgoingRequest.pipe(bufferOnPipe)
  
  outgoingRequest.on('response', (incomingResponse) => {
    if (incomingResponse.statusCode === 200) {
      console.log('statusCode:', incomingResponse.statusCode)
      console.log('headers:', incomingResponse.headers)
      bufferedResponse.pipe(outgoingResponse)
    } else {
      console.log('non-200 statusCode:', incomingResponse.statusCode)
    }
  })
})

app.listen(8000, () => {
  console.log('listening on 8000')
})
```

Next post in series: [Pass Request buffer through Redis](https://dev.to/adamkdean/pass-request-buffer-through-redis-1mhh)
How to force Laravel database layer to retry queries that have canceled because of replication error
Tags: help
Published: 2020-01-20 13:20:01

I have a postgresql server that I am unable to manage it. Though it has master-slave replication and I set up my laravel application with the correct connection credentials. 

But sometimes replication comes up with unwanted errors. Therefore, how I can configure my Laravel application to recconect in case that replication-based sql errors happen?

{% stackoverflow 59821684 %}
Proper sorting with JavaScript
Tags: sorting, algorithms, javascript
Published: 2020-01-20 13:18:57

_Originally posted on April 8th, 2014_ ([more info](https://dev.to/adamkdean/migrating-to-dev-to-190))

If we're trying to sort an array, we're going to have a bad time. JavaScript doesn't do a good job of sorting out of the tin, so we're going to have to implement our own sorting algorithm. It's not really advanced enough to use the term algorithm, but let's get to it.

First, let's take an array. We can either have numbers, numbers in strings, or strings. Regardless of whether we have numbers in strings or actual numbers, the sorting will still be back to front by default. For example, [1, 8, 10, 12] will still become [1, 10, 12, 8] when we run `sort()`.

So let's get that array.

    var list = ['10', '12', '14', '16', '18', '20', '8'];

So now we have an array. It isn't sorted how you'd expect it to be. If we run `sort()`, we'll end up with a peculiar result. 10 will come before 8, as will 20, all the way up to 7...

    // what we'll see
    ["10", "12", "14" "16", "18", "20", "8"]

    // what we want to see
    ["8", "10", "12", "14", "16", "18", "20"]

To sort this, we're going to have to write our own sorting algorithm. We need to account for strings, numbers inside strings, numbers. The good thing about JavaScript `sort()` is that you can pass your own predicate. A predicate is an expression which returns either true or false. Is a greater than b? 

A simple way to perform a numerical sort is:

    list.sort(function (a, b) {
        return a - b;
    });

But this isn't going to work properly for strings. A more advanced way of sorting it, which will account for strings as well, will check whether numbers are involved, and if so, convert the strings to numbers before comparing.

    list.sort(function (a, b) {
        var ai = parseFloat(a), bi = parseFloat(b);
        return (isNaN(ai) || isNaN(bi)) 
            ? a > b ? 1 : a < b ? -1 : 0
            : ai > bi ? 1 : ai < bi ? -1 : 0;
    });

Using either of these predicates with numbers/numbers-in-strings will output what you'd expect:

    ["8", "10", "12", "14", "16", "18", "20"]

But if we're using letters, such as a list of bra cup sizes, the advanced predicate will come out on top. Let's take a look at another example. In this, we're going to use said list of bra cup sizes and sort them. We'll see how the numerical predicate falls on it's face, and how the combined predicate doesn't.

    var list = ['FF', 'GG', 'F', 'DD', 'K', 'E', 'G', 'D', 'JJ', 'J', 'HH', 'KK', 'H'];

    list.sort(function(a, b) { return a - b; });
    // outputs: 
    // ["FF", "H", "F", "DD", "K", "E", "GG", "D", "JJ", "J", "HH", "KK", "G"]

    list.sort(function (a, b) {
        var ai = parseFloat(a), bi = parseFloat(b);
        return (isNaN(ai) || isNaN(bi)) 
            ? a > b ? 1 : a < b ? -1 : 0
            : ai > bi ? 1 : ai < bi ? -1 : 0;
    });
    // outputs: 
    // ["D", "DD", "E", "F", "FF", "G", "GG", "H", "HH", "J", "JJ", "K", "KK"]
 
It would be interesting to know why `sort()` doesn't use something like this by default. Maybe this will be the subject of a further blog post.
Daily Developer Jokes - Monday, Jan 20, 2020
Tags: jokes, dailydeveloperjokes
Published: 2020-01-20 13:00:00

---
title: "Daily Developer Jokes - Monday, Jan 20, 2020"
description: "Check out today's daily developer joke! (a project by Fred Adams at xtrp.io)"
series: "Daily Developer Jokes"
cover_image: "https://private.xtrp.io/projects/DailyDeveloperJokes/thumbnail_generator/?date=Monday%2C%20Jan%2020%2C%202020"
published: true
tags: #jokes, #dailydeveloperjokes
---

Generated by Daily Developer Jokes, a project by [Fred Adams](https://xtrp.io/) ([@xtrp](https://dev.to/xtrp) on DEV)

___Read about Daily Developer Jokes on [this blog post](https://xtrp.io/blog/2020/01/12/daily-jokes-bot-release/), and check out the [Daily Developer Jokes Website](https://dailydeveloperjokes.github.io/).___
### Today's Joke is...
![Joke Image](https://private.xtrp.io/projects/DailyDeveloperJokes/public_image_server/images/5e1258999910d.png)

---
*Have a joke idea for a future post? Email ___[xtrp@xtrp.io](mailto:xtrp@xtrp.io)___ with your suggestions!*

*This joke comes from [Dad-Jokes GitHub Repo by Wes Bos](https://github.com/wesbos/dad-jokes) (thank you!), whose owner has given me permission to use this joke with credit.*

<!-- 
Joke text:
___Q:___ Why did 10 get paid less than "10"?

___A:___ There was workplace inequality.
 -->
Fear of asking questions? What mindset should you have?
Tags: beginners, career, discuss
Published: 2020-01-20 12:41:38

Hi, I'm having problems about approaching my manager, or other colleagues in work that I don't know of (or haven't talked to yet).

Eventually there will come a time that I will have to come ask them of a subject matter they are specialized in.

But it seems that, whenever I do, I always have that mindset that I'm technically disturbing them whenever I ask questions, whether it's a noob question or a question that actually makes sense.

These questions may be technical in code or not, but of course mostly refers to questions in code and etc.

Because there are times that asking a question once doesn't work, they have many people to support to, and I'm just one of them, so sometimes you have to bug them, it depends..

One advice that I had from my colleague is that, if you don't remind of ask them constantly about your query, you're the one who will be delayed on your end at your task.

But that's quite a negative remark in my perspective.

For intermediate developers, and also senior managers, I would like to ask some advice on what beginner devs and new people in the office on what mindset should they have on approach when asking questions and assistance.. especially if you don't know who to approach to and such..

This is also a good discussion for us developers, mentors and managers alike.

Thank you so much!
How to Set up a Free Website with GitHub Pages - How I Created quanticdev.com
Tags: github, githubpages, website, tutorial
Published: 2020-01-20 12:40:57

Video Tutorial: https://www.youtube.com/watch?v=jPhmR3TiGq8
Article: https://quanticdev.com/articles/website-with-github-pages

I have recently published quanticdev.com using only GitHub Pages and markdown and decided to create a guide to preserve this knowledge in the form of a video/article so I can reuse it in my future projects. GitHub Pages is a free and a pretty good hosting service. It is an add-on for regular GitHub repositories, and you can host your website as well as code and other things in one repo, which is pretty good. I must warn that GitHub Pages is intended for techies. If you want something much simpler, go with Google Sites, or Blogger.com, or WordPress. In the first part of this video/article, I will discuss the strengths and weaknesses of GitHub Pages. In the second part, I will deploy a brand-new website using GitHub Pages and simple markdown. Everything will be done through GitHub's UI and online code editor. I will also demonstrate a sample React website hosted on GitHub Pages.

Outline of this video/article:
  • QuanticDev.com Intro
  • Why GitHub Pages
  • Advantages
  • Disadvantages
  • GitHub Pages Setup & How I Created quanticdev.com
  • My Recommendations
  • Conclusion

Free website hosting:
  • GitHub Pages (for techies): https://pages.github.com
    o Supports Jekyll: https://jekyllrb.com
    o Supports Static HTML + CSS + JavaScript
    o Supports React (and anything that compiles to static HTML/JS/CSS): https://create-react-app.dev/docs/deployment/#github-pages
  • Google Sites (non-techies): https://sites.google.com
  • Alternatives for Bloggers
    o Blogger (basic): https://blogger.com
    o WordPress (more advanced): https://wordpress.com
  • Alternatives for Programmers
    o Heroku: https://www.heroku.com
    o Firebase: https://firebase.google.com
what is the best gnu/linux distro in the world ever (you ALREADY know the answer !)
Published: 2020-01-20 12:25:48

there is no need for endless arguments / discussions / fisticuffs ! the answer is your-distro its the one YOU use everyday its the one YOU that works with 512M ram its the one YOU have been using for the last N years on pentium 3's , core2's and i7's ! and for me thats [xubuntu](xubuntu.org)

AND here's why it never pays to be unfaithful to YOUR distro !

take this example of a 2 bugs i found within 4 minutes of having a fling with a unnamed alt distro !

lets start our unnamed distro and run chromium browser 
![Alt Text](https://thepracticaldev.s3.amazonaws.com/i/wxpdobta7vip82fy8cd6.png)

1) look at the above screenshot didnt we already report the chromium keychain bug ?  yes we did ! see [link to chromium keychain bug](link to chromium keychain bug)

2) look carefully at this next screenshot 
![Alt Text](https://thepracticaldev.s3.amazonaws.com/i/zpl9vi9mi6ka5uinx4hg.png)

can you see the broken unicode characters in chromium title bar

* maybe its a bug in chromium ?

3) lets try firefox

* nope its the same in firefox

what about your-distro ? say xubuntu

your-distro distro / xubuntu is good ! (your-distro / xubuntu is ALWAYS good - its the best distro in the world ever ... see above)

so we will conclude it is a gnu/linux distro unicode font issue then we will remember that we blogged about a unnamed distro unicode font issue a FEW years ago 
* https://osde8info.wordpress.com/2018/03/01/linuxlite-xubuntu-kannanda-font-install/ 

...

THEN 

we remember life is to short 

(or our manager has just asked us when we will be finishing the prohect we are suupposed to be working on) 
* do we really care about another distro ?
* has your-distro ever let us down ?
* why are we wasting our time having a fling ?
* why are we even blogging this on devto ?

never stray BECAUSE we live for OUR distro ! OUR distro is the best !
Easy Peasy Git for Github with clix
Tags: git, github
Published: 2020-01-20 11:51:05

# Original Question asked by student 

Is there a way to show that folder structure in git? I'm struggling to visualize how it looks in git and how we would push that structure to git. Are there instructions for how to create the structure on our computers then push it to git?

#Answer

Git is a version control tool. For example when you write an essay you have many versions on your desktop, for example 5 versions. You might decide that essay #1-3 are no good and put them in a folder called "rough_draft" and put essay #4 and #5 in a folder called "final_edit". 
In this case you are versioning/controlling what versions you want **manually**.

However, when you code and have many sub-folders within a main folder and multiple files, it is not possible to manually control what versions you want. Unless you copy paste the project folder and it's contents each time that you make a change. Which is tedious and impracticable when working with teams. 

Therefore, using a version control tool like git is a good choice. Git provides you with a workflow to code without worrying about if the latest version of your code has been saved. Git only stores a snapshot of your current changes , it's like a camera that will take a picture when clicked of any changes that you make in any file in whatever folder they may be.

So git does not organize your files or folders. That you will have to do manually. Git will only take "snapshots" of changes of your files. If you move files around into different folders, it does not matter.

Github is an online platform where people can upload their code. This is called pushing. It's like saving pictures in an album and then uploading the album to facebook. 


To do this the easy way:

1. Make an account on github.com 
2. Make a repository 

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


3. Name your repository and "click on create repository"

![Alt Text](https://thepracticaldev.s3.amazonaws.com/i/7u9sb2eeg6hxm91men6n.PNG)

4. Click on "uploading on existing file"

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

5. Now you can either drag or drop your files into the middle area or click on "Choose files" **AND** then click on the green "Commit changes" button

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

6. ![Alt Text](https://thepracticaldev.s3.amazonaws.com/i/x8vjqu1ddaqhkqc77w9d.png)

7. You will be redirected to your repository **OR** project folder on github if you may, where you will now see your file uploaded on github.com in your repository

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


## Git workflow on the terminal

![Alt Text](https://thepracticaldev.s3.amazonaws.com/i/raq1u7rwgpjvie2scg0j.jpg)
Intro a Swift.
Tags: swift, ios
Published: 2020-01-20 11:47:56

---
title: Intro a Swift.
published: true
description: El inicio de una serie de tuturiales para aprender a programar en Swift.
tags: swift, ios
---

<h1>Swift</h1>
<p><br></p>
<p>Este es el primer tutorial de una serie de guías de Swift para principiantes.</p>
<p><br></p>
<p>Swift es un lenguaje de programación intuitivo y de propósito general basado en protocolos (POP).</p>
<p>El lenguaje de Swift apareció en 2014, fue creado por Christ Lattner y desarrollado por Apple. Es un lenguaje principalmente utilizado en para el desarrollo de apps dentro del ecosistema de Apple como lo son los sistemas iOS, MacOS, iPadOS, watchOS y otros futuros dispositivos de Apple.</p>
<p><br></p>
<p>Su código es seguro por diseño y al mismo tiempo esto hace que sea muy rápido en ejecución. Escribir Swift es interactivo y divertido, la sintaxis es concisa pero expresiva.</p>
<p><br></p>
<p>Como todo buen lenguaje de programación <em>moderno</em>, Swift cuenta con todos los tipos de datos fundamentales que se encuentran tanto en C como en Objective-C por lo que podríamos decir que Swift es simplemente <em>Objetivo. </em></p>

<p>Swift cuenta con sus propias versiones de estos tipos de datos fundamentales como lo son <em>Int</em> para los números enteros, <em>Doble</em> y <em>Float</em> para los datos con valor flotante o decimal, así como <em>String</em> para la información textual y Bool para los valores Booleanos.</p>
<p><br></p>
<p><br></p>
<h2>Los Basicos.</h2>
<p>En este primer capitulo hablaremos de los asuntos básicos de Swift. Me refiero a lo necesario y esencial para entender las primeras lineas de código y los primeros proceso lógicos del lenguaje.</p>
<p><br></p>
<p>Durante este tutorial escribiremos código en la interfaz de desarrollo (IDE) de Apple, Xcode. Si aun no tienes Xcode instalado puedes descargarlo fácilmente desde la Mac AppStore.</p>
<p><br></p>
<p>De vuelta a la lección.</p>
<p>Es tradición que la primera linea de código para cualquier persona que inicia en cualquier lenguaje sea algo similar a esta:</p>
<p><br></p>
<p><code>var greet = "Hello World"</code></p>
<p><br></p>
<p>Esta linea de código es suficiente para arrancar con Swift y avanzar hacia asuntos mas complejos.</p>
<p>Primero, <em>var</em> se refiere a el tipo de valor que tiene la propiedad la cual llamamos <em>grey.</em></p>
<p>Este tipo de valor significa que se trata de una variable, es decir, que su valor puede cambiar en cualquier momento. Lo opuesto a una variable es el tipo de valor constante, <em>let</em>.</p>
<p><br></p>
<p><code>let greet = "Hello World"</code></p>
<p><br></p>
<p>esto significa que el valor ("Hello World") no podrá cambiar dentro de la app.</p>
<p><br></p>
<p>El valor asignado a la propiedad, <em>Hello World</em>, es un conjunto de caracteres al cual es de tipo <em>String.</em></p>
<p>Con esto hemos cubierto lo mas básico de Swift. A continuación hablaremos de los principales tipos de valor que existen en Swift.</p>
The Medium Blog Post Clone (Dark Mode)🤓
Tags: html, css, webdev, clone
Published: 2020-01-20 11:35:02

We all know that medium has one of the best typeface and UI out there.

Here in this quick project in which I've tried to clone the Dark Mode of Medium, although I've changed some of the styles but at the end I think it's nearly impossible to distinguish between the two unless you keep them both aside.

## Live demo link

https://sharadcodes.github.io/jekyll-theme-medium/article.html
To the point - generating random numbers in golang
Tags: go, tutorial, codenewbie, rand
Published: 2020-01-20 11:34:46

## Generating random numbers 
(integers for the sake of this post)

## Usually

Most commonly, you would use the math/rand and the time pkg to seed the rand generator in go. This is shown below:
```go
// code#1
package main

import (
	"fmt"
	"math/rand"
	"time"
)

func main() {
	rand.Seed(time.Now().UnixNano())
	x := rand.Intn(5) // An int between [0,5)
	fmt.Println(x)
}
```

## Unusually

Most of times, code#1 will do the job, BUT what if your randomness cannot depend on time alone. 

## Problem

As an example, suppose you want to create a function that must return two random numbers between 0 and n

### Thought 1

You could math/rand.Perm(n) seeded with time.Now().UnixNano() to obtain a slice of n integers. And then pick the first two. Something like:

```go
//code#2

func main() {
	rand.Seed(time.Now().UnixNano())
	x := rand.Perm(5)
	fmt.Println(x[0], x[1])
}
```

BUT, this is highly inefficient especially for large values of n.

### Thought 2

Make use of the crypto/rand package to **generate a truly random int**. 
Something like:
```go
// code#3
package main

import (
	"fmt"
	"crypto/rand"
	"math/big"
)

func main() {
	x, _ := rand.Int(rand.Reader, big.NewInt(5))
	y, _ := rand.Int(rand.Reader, big.NewInt(5))
	fmt.Println(x, y)
}
```

That's all! Happy randomizing!
uplifting post of the year !
Tags: entrepreneur, inventor, creator, recognition
Published: 2020-01-20 11:34:10

just read this uplifting post !

https://dev.to/conradj/a-2-billion-fintech-keeps-copying-my-ideas-and-i-feel-fine-3k29

btw how much money did the honey & piggy chromium browser and firefox browser extensions save you last year ?
* honey [for chromium]() [for firefox]()
* piggy [for chromium]() [for firefox]()
Why the distributed company is a viable option?
Tags: remote
Published: 2020-01-20 11:23:32

<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>

Remotely managed companies nowadays have benefits.

As an employer:
- you don't need an office
- you don't need hardware for your employees
- you don't have to select employees only from the local area
- your employees are already equipped with hardware
- you don't need to pay for bandwidth enough for comfortable work of many people
- you don't need to buy fancy stuff for an office, e.g. ping-pong table, watercooler, etc.
- you need less money to start your business
- you can afford to run several businesses
- you can travel and keep growing your business
- you can decrease your carbon footprint to zero!

As an employee:
- you can work with any company in the world
- you don't need to spend time to commute
- you can organize your workspace to your needs
- you can benefit from online services such as codesandbox.io to start working at no cost
- you do not need to bother about dress-code
- you can spend more time with your relatives and beloved
- you will eat healthy food of your choice
- you can work out as many times a day as you want
- you choose the time to work - no more 9 to 5 schedule
- you can attend conferences and keep working
- no problem with scheduling a visit to a doctor, advocate, etc.
- you can decrease your carbon footprint to zero!

These are the benefits of remote working.

The only thing that you should choose wisely the software stack that will allow you to achieve all of these advantages!

And which advantages in remote lifestyle do you know/fond of?