teleren/devto huggingface dataset:
Discuss: How should you handle errors in your library code?
Tags: discuss, javascript, errors
Published: 2019-05-09 15:11:37

---
title: Discuss: How should you handle errors in your library code?
published: true
description: 
tags: discuss, javascript, errors, error handling
---

I like to work on open source projects in my free time and thus have created a few JavaScript modules in the past. Most of the times, they're like really small libraries and only serve one purpose. As the main point about a library is being used somewhere else, it is quite likely that somewhere else will be somebody else's code, codebase, project, you name it. As such, it's of course very important to document your API (which I always try my best at, I swear! 😄). Still though, there's this one question I regularly have when creating a library API:

### What if something goes wrong?

Let's think of a scenario here to illustrate my problem. Recently, I've been working on a little JS library that takes a string with a time and timezone, and gives back an object providing converted versions for UTC and local time. The usage looks like this:

```javascript
import tizo from 'tizo';

tizo("19:30 cest").utc;
// → '[ 17, 30 ]'
```

As you can see, in the above example the timezone `cest` was provided. What I've been thinking of was, what if the timezone that is passed to the library does not exist? Be it because it actually doesn't exist, or `tizo` doesn't know about it.

__The two ways I see here are:__
1. __a "hard error", clearly interrupting execution, for example via Promise rejection, error throwing or `process.exit(1)`__
2. __a "soft error", doing your best regardless, for example giving back a string stating the error, ignoring the parameter in question and work with default values, etc__

What do you think? Lemme know!
RSpecの have_content? と has_content? は違う
Published: 2019-05-01 02:47:07

---
title: RSpecの have_content? と has_content? は違う
published: true
description: 
tags: 
---

# `have_content?` and `has_content?` is different in RSpec


RSpecのsystem specで `have_content?` と `has_content?` を間違えていて、ドハマりしました。 💥💥

# 結論

`has_content?` と `have_content?` は別物！条件分岐に使うときは注意!

# 環境

    🌸 ruby -v
    ruby 2.5.1p57 (2018-03-29 revision 63029) [x86_64-darwin17]
    🌸 bin/rails -v
    Rails 5.2.0
    🌸 be rspec -v
    RSpec 3.7
      - rspec-core 3.7.1
      - rspec-expectations 3.7.0
      - rspec-mocks 3.7.0
      - rspec-rails 3.7.2
      - rspec-support 3.7.1

# 問題のコード

system spec内にこのようなコードを書いていました。

    ~略~
    
    visit user_group_path(user_group)
    
    10.times do 
      break if have_content?("愛島セシル")
      
      sleep 1
      visit user_group_path(user_group)
    end
    
    expect(page).to have_content("愛島 セシル")
    
    ~略~

非同期の処理を行っているページです。
処理が終わったあとページを更新すると結果が反映されます。
目的の文字列が出てくるまでページを更新し、その文字列の存在を確かめるコードです。
`have_content?("愛島セシル")` で文字列の存在を確かめて、もし文字列が存在すればbreakし、なければ1秒待ってからページを更新します。
次の処理 `expect(page).to have_content("愛島 セシル")` でページに"愛島 セシル"という文字列があるかどうかテストしています。

このコードがCIで何度も落ちていました。 :scream:

# 結論

Rubyは`nil`と`false`がfalse、それ以外はtrueです。
今回の場合、`have_content?("愛島 セシル")` により、 `#<RSpec::Matchers::BuiltIn::Has:0x00007f8ac84536e8 @args=["愛島 セシル"], @block=nil, @method_name=:have_content?>` のオブジェクトが返ってしまっていました。
つまり、`if have_content?("愛島 セシル")` は true になり、 "愛島 セシル" の描画にかかわらずループを抜けてしまっていましたのです！ :eyes:
ページを更新するコードは一度も読まれていませんでした :sob:

# 詳しく

RSpecの仕様で
`have_なんとか` と書くと、内部で `なんとか?` が呼び出されます。
[https://github.com/rspec/rspec-expectations/blob/3-8-maintenance/lib/rspec/matchers/built_in/has.rb#L71](https://github.com/rspec/rspec-expectations/blob/3-8-maintenance/lib/rspec/matchers/built_in/has.rb#L71)

    def predicate
              # On 1.9, there appears to be a bug where String#match can return `false`
              # rather than the match data object. Changing to Regex#match appears to
              # work around this bug. For an example of this bug, see:
              # <https://travis-ci.org/rspec/rspec-expectations/jobs/27549635>
              @predicate ||= :"has_#{Matchers::HAS_REGEX.match(@method_name.to_s).captures.first}?"
            end

# have_content?

    pry > have_content?("愛島 セシル")
    => #<RSpec::Matchers::BuiltIn::Has:0x00007f8ac84536e8 @args=["愛島 セシル"], @block=nil, @method_name=:have_content?>

# has_content?

    pry > has_content?("愛島 セシル")
    => true
    
    # has_text? と一緒
    pry > has_text?("愛島 セシル")
    => true
Architecture diagrams for Github README.md?
Tags: help, github
Published: 2019-05-09 13:28:38

---
title: Architecture diagrams for Github README.md?
published: true
description: 
tags: #help #github
---

Does anyone have a recommendation for a tool that can make architecture diagrams (flowcharts) like the one found here?

https://github.com/donnemartin/system-design-primer

Ideally, I would like the diagrams to be hosted somewhere, instead of attaching them to an Issue as described here:

https://stackoverflow.com/questions/14494747/add-images-to-readme-md-on-github

Also, this might be asking a lot, but it would be nice to have these images (preferably SVG) remain editable (similar to a Visio diagram) that I can put Auth in front of (since I would like to use it for my company too).

Does something like this exist?
Google season of Docs
Tags: help, suggestion, googleseasonofdocs
Published: 2019-05-09 13:07:22

---
title: Google season of Docs
published: True 
description: Need some suggestions for Google season of docs 2019.
tags: help, suggestion, googleseasonofdocs
---

Hello, everyone, I need a suggestion 
Actually, I want to know something. I'm preparing for Google season of Docs 2019 so can you help me how to write or some tips?


Here the sample of the article I wrote on LinkedIn and Dev.to community 

https://www.linkedin.com/pulse/digital-data-storagenatural-resources-naturalresource-abhishek-shukla/

https://dev.to/abhishekalbert
Changing the Git history
Tags: git, productivity, bash, script
Published: 2019-05-09 13:06:25

---
title: Changing the Git history
published: true
description: 
tags: #git #productivity #bash #script
cover_image: https://thepracticaldev.s3.amazonaws.com/i/nyrghqc56huphvaug1rc.png
---

After a month of having formatted my work computer, I noticed that my mail configured in GIT was wrong. This caused my commits to not recognize me as the author and not appear on my account activity.

If this error is detected after a single commit, it can be easily solved with the following command:

``` bash
git commit --amend --author="Correct Name <youremail@example.com>"
```


If it is detected after several commits, as happened to me, the best solution is this:

{% gist https://gist.github.com/eesnaola/4da1bc0849f8e543229e0024d27edd40 file=changing_author_git.sh %}

I hope you enjoyed my first post ever on dev.to!
SOLVED:Uploading images from Django-Admin
Tags: help, django, python, beginners
Published: 2019-05-09 13:02:37

I'm almost done fixing my Django portfolio when I bumped into a problem when choosing a photo for one of the pages of my site

![](https://thepracticaldev.s3.amazonaws.com/i/73l0zli66t214r6xdoox.png)

The problem here is the dropdown doesn't show anything! 

My models.py is
<pre>
from django.db import models


class Project(models.Model):
    title = models.CharField(max_length=100)
    description = models.TextField()
    technology = models.CharField(max_length=20)
    image = models.FilePathField(path='/img')
</pre>

I have an **/img** folder on the main project folder and the static folder.

Someone from StackOverflow asked if I had read & write access on the folder and I definitely have. 

Did I miss anything?
Introducing Brushable Histogram
Tags: react, javascript, opensource
Published: 2019-05-09 11:11:37

---
title: Introducing Brushable Histogram
published: true
description: Brushable Histogram, a new type of histogram
tags: react,javascript,opensource
---

Hey, just wanted to share our first React open source component: Brushable Histogram!

![Previews of the histogram](https://thepracticaldev.s3.amazonaws.com/i/9lb2ffn7q4kq8iq9ztsz.png)

The Brushable Histogram is a time histogram with a brushable preview of the whole dataset below it.

Besides React, the component also uses a lot of d3.

If you want to know more about it you can read the launch [blog post](https://medium.com/feedzaitech/introducing-brushable-histogram-6c6b0f0f60ca).

You can checkout the [Github repo](https://github.com/feedzai/brushable-histogram) or the [demos](https://feedzai.github.io/brushable-histogram) as well.

Let me know if you have any feedback!
Are you building Docker images? here's how to avoid leaking sensitive information into Docker images
Tags: docker, secrets, leak, image
Published: 2019-05-09 10:23:15

---
title: Are you building Docker images? here's how to avoid leaking sensitive information into Docker images
published: true
description: 
tags: docker, secrets, leak, image
canonical_url: https://www.lirantal.com/blog/2019-05-09_avoid-leaking-sensitive-information-when-building-docker-images
---

> This tip is part of a complete [10 Docker image security best practices](https://snyk.io/blog/10-docker-image-security-best-practices/) you should adopt. Thanks for reading and to [Omer Levi Hevroni](https://twitter.com/omerlh) who worked with me on it.


Sometimes, when building an application inside a Docker image, you need secrets such as an SSH private key to pull code from a private repository, or you need tokens to install private packages.

If you copy them into the Docker intermediate container they are cached on the layer to which they were added, even if you delete them later on. These tokens and keys must be kept outside of the `Dockerfile`.

## Using multi-stage builds
By leveraging Docker support for multi-stage builds, fetch and manage secrets in an intermediate image layer that is later disposed of so that no sensitive data reaches the image build.

Use code to add secrets to said intermediate layer, such as in the following example:

```
FROM: ubuntu as intermediate

WORKDIR /app
COPY secret/key /tmp/
RUN scp -i /tmp/key build@acme/files .

FROM ubuntu
WORKDIR /app
COPY --from=intermediate /app .
```

## Using Docker secret commands

Use an alpha feature in Docker for managing secrets to mount sensitive files without caching them, similar to the following:

```
# syntax = docker/dockerfile:1.0-experimental
FROM alpine

# shows secret from default secret location
RUN --mount=type=secret,id=mysecret cat /run/secrets/mysecre

# shows secret from custom secret location
RUN --mount=type=secret,id=mysecret,dst=/foobar cat /foobar
```

## Beware of recursive copy

You should also be mindful when copying files into the image that is being built. 

For example, the following command copies the entire build context folder, recursively, to the Docker image, which could end up copying sensitive files as well:

```
COPY . .
```

If you have sensitive files in your folder, either remove them or use `.dockerignore` to ignore them:


```
private.key
appsettings.json
```

---

The original blog post includes a high-resolution printable PDF like the snippet you see below. [Check it out](https://snyk.io/blog/10-docker-image-security-best-practices/)
An Excel interop trick
Tags: softwaredevelopment, windows
Published: 2019-10-01 11:21:59

---
title: An Excel interop trick
published: true
tags: software development,windows
canonical_url: 
---

Yesterday I had a nice little evening spent with a silent failure of my program. The program needed to create an Excel document, save it and export as a PDF. It should also run periodically and automatically, so as a scheduled task right? Yes, and it works fine for me on my Windows 10 PC, but on clients Windows Server 2012? Not really.

### What’s wrong?

First thing I saw is that Excel file was created, but PDF wasn’t. The Excel file was still in use by an Excel program in background. My scheduled task was still shown as running, and log files didn’t have any new lines after creating Excel file. It meant export to PDF method failed, but why?

I browsed the web and found a lot of complaints and users telling that you can’t automate Excel with a scheduled task without a user logged in. It made sense, but my task could open Excel, generate a file and save it. It’s just that when it tried to export it to a PDF it halted. And only when ran unattended, meaning when no user is logged in.

### The printer

I can’t remember all the things I tried to workaround this problem, but after a few hours I got to this [StackOverflow question](https://stackoverflow.com/questions/10272415/excel-exportasfixedformat-pdf). There was that one answer that pointed that Excel is not able to print to PDF and I should set Microsoft XPS document writer as a default printer. So I tried that and it worked! These kind of problems make you feel alive and put you out of your comfort zone writing those lines of code :)
Why ReactJS is Better for Web Development?
Tags: whyreactjs, webdev, appdevelopment, react
Published: 2019-05-09 09:35:57

---
title: Why ReactJS is Better for Web Development?
published: True
description: Why ReactJS is Better For Web Application Development? In the course of recent years, React.js has turned out to be a standout amongst the most prevalent instruments out there for structure web applications. 
tags: Why reactjs, web development, app development, reactjs
---
<img src="https://thepracticaldev.s3.amazonaws.com/i/u7tl27teb4v5vz5i6vfs.png" alt="Why ReactJS is Better for Web Development?">

Why ReactJS is Better For Web Application Development? In the course of recent years, React.js has turned out to be a standout amongst the most prevalent instruments out there for structure web applications.

Why ReactJS is Better For Application Development?

What Is ReactJS?

ReactJS is an open-source JavaScript structure, the motivation behind which is to make connecting with and rich web applications that can run effectively with insignificant coding. Prior, Angular was viewed as the most favoured alternative for creating single page web applications, however, with the presentation of React, which centres around the highlights of individual parts, engineers found their recently created website pages rendered quicker.

Read the full article here: https://www.decipherzone.com/blog-detail/Why-ReactJS-is-Better-For-Web-Application-Development-
Cấu hình kết nối HTTPS để test Facebook app trên localhost
Published: 2019-05-09 09:27:33

---
title: Cấu hình kết nối HTTPS để test Facebook app trên localhost
published: true
description: 
tags: 
---


Trong quá trình tìm hiểu về lập trình chat bot sử dụng các API của Facebook Messenger thì việc test chat bot trên localhost là một trở ngại.  

Khi tạo một subscription cho app chat bot, Facebook sẽ gửi một request đến server mà chat bot đang chạy để xác nhận có đúng là chat bot của bạn không. Cũng như sau đó, tất cả những tin nhắn của nguời dùng sẽ đuợc gửi tới chat bot thông qua `callback url`. Và vấn đề là khi dev và test trên localhost thì làm sao để server local của bạn có thể nhận và phản hồi request của Facebook.

Một giải pháp đơn giản là sử dụng dịch vụ của [https://ngrok.com](https://ngrok.com/) để chuyển các request về máy localhost. `ngrok.com` cung cấp gói miễn phí test vô tư, hơn nữa `ngrok` hỗ trợ cả `https`.
Điều này rất quan trọng, bởi vì từ 2018 thì tất cả các `callback url` khi đăng ký ứng dụng trên Facebook Developer đều phải sử dụng kết nối `TLS`.

## Buớc 1: Đăng ký tài khoản
- Đăng ký tại [https://ngrok.com/pricing](https://ngrok.com/pricing)
Vì là tài khoản miễn phí nên sẽ có một số giới hạn:
- 40 kết nối / phút
- Mỗi lần chỉ chạy được 1 `ngrok` process

## Bước 2: Download ngrok và cấu hình API key
- Download tại [https://ngrok.com/download](https://ngrok.com/download)
- Giải nén file vừa Download bạn sẽ có file `ngrok`
- Thêm token vào ngrok config bằng lệnh
 
```shell
$ ./ngrok authtoken <YOUR_AUTH_TOKEN>
```

Bạn có thể copy command trên từ [Dashboard](https://dashboard.ngrok.com/get-started) trong phần `Connect your account`

## Bước 3: Khởi chạy ngrok process
**Chạy lệnh**

```shell
./ngrok http <PORT>
```

trong đó `PORT` là port number của server localhost mà bạn muốn test.
	
**Ouput mẫu của `ngrok`**

![ngrok](http://bluzky.github.io/img/ngrok.png)

`ngrok` cung cấp cho bạn 2 public URL để kết nối vào server localhost. 1 URL với giao thức `http` và 1 URL với `https`.
Ngon không nào!

Bây giờ bạn đã có thể cấu hình Facebook để test trên localhost rồi.

**Lưu ý:**  
Khi sử dụng tài khoản Free, mỗi lần chạy `ngrok` thì forwarding URL sẽ khác nhau nên sẽ phải sửa lại sửa lại cấu hình app trên Facebook Developer. Đồ chùa thường là đồ chua mà. Khi sử dụng gói có phí bạn có thể cấu hình forwarding URL theo ý mình. Mình nghèo nên chịu khó thôi.
Return Status Code with Laravel Resource
Tags: php, laravel, laravelresource
Published: 2019-05-09 09:27:04

---
title: Return Status Code with Laravel Resource
published: true
description: Laravel Resource is one of the best features in Laravel. It makes it easy to modify the output of the result. If you're using an API, you need to have a status code to let the front-end know what the status of the request is. 
tags: php, laravel, laravel resource
---

Laravel Resource is one of the best features in Laravel. It makes it easy to modify the output of the result. If you're using an API, you need to have a status code to let the front-end know what the status of the request is. 

Example of Status Code
202 - Created
401 - Unauthorized
404 - Not Found

You may find a list of HTTP status code over here.

For example, you have a User Model, and the controller wants to return user information of specific id. You want to let the front-end know that you found the data based on the status code. 

Api.php 
```
Route::get('user/{user}', 'UserController@show');
```

UserController.php
```
public function show(User $user) {
    return (new UserResource($user))
        ->response()
        ->setStatusCode(202);
}
```


## How about if there is no ID in the database?

It could be like this. We should check it first whether the ID is available in our database and if not, it should return a status code of **not found**. If yes, we may proceed with the previous system. 

UserController.php
```
public function show(User $user) {
    
    // If user not found
    if(!$user){
    return response(array(
        'message' => 'Not Found',
     ), 410);
    } else {
        // If user is found
        return (new UserResource($user))
            ->response()
            ->setStatusCode(202);
    }
}
```


It is writing with if else block is troublesome during debugging. It's a best practice to check for the negative result first and then returns the correct output at last. If the if else get deeper it will get worse for the developer. 

### Refactor

```
public function show(User $user) {
    
    // If user not found
    if(!$user){
    return response(array(
        'message' => 'Not Found',
     ), 410);
    }
    
    // If user is found
    return (new UserResource($user))
        ->response()
        ->setStatusCode(202);
}
```

Hope it may help you understand how to send the status code through laravel resource or without it. 

Original submitted from [my blog](https://jakzaizzat.com/how-to-return-status-code-with-laravel-resource/)
Solve LeetCode problems using Visual Studio Code, TypeScript, and TDD
Tags: leetcode, typescript, javascript, computerscience
Published: 2019-05-09 08:56:10

---
title: Solve LeetCode problems using Visual Studio Code, TypeScript, and TDD
published: true
description: Getting into LeetCode with TypeScript and TDD style programming.
tags: leetcode, typescript, javascript, computerscience
---

[LeetCode workspace written in TS / Mocha / TDD](https://github.com/mjmaix/leetcode-typescript-tdd-starter).

I encourage beginners and enthusiasts to use this project. Some of the things that made me set up this project are:

    1. In line debugging. It's not every time that we can get the correct solution straight away and I'm not a fan of `console.log` debugging.
    2. Ability to use my favorite text editor (Visual Studio Code) with dark mode
    3. TDD style development. Solve fast but have the ability to re-factor my code with confidence in my (TDD).
    4. Version control your project.

Bonus is that I translated 3 problem examples to Test Cases.


I also want to encourage everyone to share their Test Cases via [Pull Request](https://github.com/mjmaix/leetcode-typescript-tdd-starter/pulls), especially the failed problem test cases from failed submissions.


![Initial test cases should fail](https://thepracticaldev.s3.amazonaws.com/i/loautuxk9zo9qw749yt7.png)

![I have my own GitHub project with my solutions](https://thepracticaldev.s3.amazonaws.com/i/du1za9qvhrio7gacla85.png)


Have a great time coding!
Js versioning doubt
Published: 2019-05-09 08:14:30

---
title: Js versioning doubt
published: true
description: 
tags: 
---
Hi Guys,

I have seen something which i didnt understand.
I have a website abc.com/script.js which is working fine in aws using cloudflare as cdn.

After some days I changed script.js but it is not reflecting immedieatly in abc.com/script.js but it is reflecting in abc.com/scrpit.js?1 

Can some one explain?
I cleared the cache in cdn also still script.js is not reflecting to new one.
best five laptops under £700 for programming in 2019
Tags: webdev, laptop, code
Published: 2019-05-10 12:44:57

---
title: best five laptops under £700 for programming in 2019
published: true
tags: Web Development, laptop, code
canonical_url: https://theworldwidecode.com/blog/2019/best-five-laptops-under-700-for-programming-in-2019/
---

When searching for an affordable laptop to code with, you try to get the best you can for your money. With the technological advancements in 2019
#CodepenChallenge Star Rating
Tags: codepen, javascript, css, vue
Published: 2019-05-09 06:24:29

---
title: #CodepenChallenge Star Rating
published: true
tags: codepen, javascript, css, vue
---

<p>Recently, I started to study VueJS, and this is (somehow) the opportunity to apply it.</p>

<p>I created a Vue component for rating.</p>

{% codepen https://codepen.io/takaneichinose/pen/Mdwxma %}
ES Next Series - Introduction
Tags: javascript, es6
Published: 2019-05-09 06:05:48

---
title: ES Next Series - Introduction
published: true
description: Introduction to ES6 and beyond
tags: javascript, es6
series: ES Next
---
(This post is originally published on my [blog](https://kirankumarambati.me/blog))

JavaScript remained unchanged for many years. There were no major updates to the language until ES6 got released in 2015. ES6 and the next versions introduced lot of new features to JS. This series is an exploration of the new features the ES Next had introduced to the JS world. Hope you guys like it !
Call for Alpha Testers for Heroku IPFS
Tags: ipfs, heroku, opensource, web3
Published: 2019-05-09 04:56:22

---
title: Call for Alpha Testers for Heroku IPFS
published: true
description: 
tags: IPFS, Heroku, opensource, web3
---

At FISSION, we’re building a Heroku add-on that makes it easy to integrate InterPlanetary File System (IPFS) into apps you host there.

Heroku doesn't have a permanent file system, so anyone hosting there already has to figure out how / where to store files, so we think it's a good place to start.

We're looking for alpha testers to try out our add-on. The types of people we're looking for fall roughly into three categories:

1. You are a maintainer / contributor for an existing open source app and are interested in adding IPFS support for it (and getting it running on Heroku if it doesn't already)
1. You are a developer looking to experiment with IPFS and build a small open source test app on Heroku.
1. You are less technical/not a developer but can follow instructions on copy/pasting a basic open source app and like trying out new things

Head on over to our [Product Hunt Upcoming page at tools.fission.codes to signup to be an alpha user »](https://tools.fission.codes/)

If you haven’t used Deploy to Heroku before, you can read more about [on our blog](https://blog.fission.codes/call-for-alpha-testers-heroku-ipfs-add-on/).