teleren/devto huggingface dataset:
How to handle Enum in ActiveRecord
Tags: rails
Published: 2020-05-22 01:59:54

---
title: How to handle Enum in ActiveRecord
published: true
description: 
tags: rails
---

## Overview
How to store values in models that inherit from ActiveRecord, and which validations are responded to when you enter a value.


### Prerequisites.

Rails: 5.2
Ruby: 2.6.1

# main topic.
Sample User Table Definitions


```ruby
create_table :users do |t|
  t.string :name
  t.integer :state
  t.timestamps
end
```

Defining the user model

There's a variation of the empty character check for name.

```ruby
class User < ApplicationRecord
  validates :name, presence: true
  enum state: { show: 0, hide: 1 }
end
```


Take one model and explain it based on it.

```ruby
> u = User.first
  User Load (0.2ms) SELECT "users". * FROM "users" ORDER BY "users"." "id" ASC LIMIT ? id" ASC LIMIT ?  [["LIMIT", 1]]]
=> #<User id: 2, name: "Test 1", created_at: "2019-01-29 03:56:08", updated_at: "2019-03-11 02:52:09", state: "hide">
```

### If you simply output state, you will see the string defined by enum instead of the number stored in the DB.

```ruby
> u.state.
=> "hide"
```

### Assignment Method

You can substitute symbols defined by enum, strings, or numbers actually stored in the DB.


In the case of symbols

```ruby
u.state = :hide
=> :hide
irb(main):038:0> u.state
=> "hide"
```

In the case of a string

```ruby
u.state = "show"
=> "show"
irb(main):046:0> u.state
=> "show"
```

In the case of numbers

```ruby
> u.state = 0
=> 0
> u.state.
=> "show"
```

### Assigning an undefined value
If you try to assign a number outside the range defined by enum, you get an error.

```ruby
> u.state = "show2"
ArgumentError ('show2' is not a valid state)

irb(main):047:0> u.state = "show2"
Traceback (most recent call last):
        1: from (irb):47
ArgumentError ('show2' is not a valid state)

> u.state = :show2
ArgumentError ('show2' is not a valid state)

> u.state = 2
ArgumentError ('2' is not a valid state)
```

### Refer to the actual stored value

You can use `u.state` for debugging or testing to check which value is actually stored.
Use `read_attribute_before_type_cast` or `attribute_name_before_type_cast`.

```ruby
> u.state.
=> "hide"

 u.read_attribute_before_type_cast(:state)
=> 1
irb(main):070:0> u.state_before_type_cast
=> 1
```
How to Fix a Bug in a New Codebase
Tags: ruby, rails, opensource
Published: 2020-05-22 02:19:48

---
title: How to Fix a Bug in a New Codebase
published: true
description: Video series for junior developers on how to fix a bug
tags: ruby, rails, ruby on rails, open source
---

When I mentor junior developers, one thing I've noticed is how eye-opening it's been for them to see how I approach solving programming problems. So, I made this [video series](https://www.youtube.com/playlist?list=PLCjYibwL-b3OXjgaXMXAUF1JRV_gjPUPa) where I walk through the process of fixing a bug in the dev.to site from beginning to end.

There are a few prerequisites for this, you don't need to know much but you will need basic familiarity with Ruby, Rails and HTML to follow.

The videos are unscripted and I've made some ridiculous mistakes in there but it's all part of the process!
CPR Training in VR
Tags: octograd2020
Published: 2020-05-22 02:15:57

[Comment]: # (All of this is placeholder text. Use this format or any other format of your choosing to best describe your project and experience.)

[Note]: # (If you used the GitHub Student Developer Pack on your project, add the "#githubsdp" tag above. We’d also love to know which services you used and how you used it!)

## My Final Project

This was a hackathon project done in a team of 4 a few years back.

We wanted to make CPR training more engaging. In classrooms, we can learn all the basic steps of how to perform CPR, but we do not get the full immersive experience. I have had CPR training before, but I don't think I can calmly help someone in need in an actual stressful situation.

Moreover, we wanted to make CPR training more accessible. This one headset can be used by many people who might need this sort of training, whether it's for personal learning or for the workplace.

We used Unity, and Leap Motion, meant to be used with Google Cardboard.

{% github  https://github.com/WilliamLQin/CPR-VR %}

[Note]: # (Our markdown editor supports pretty embeds. If you're sharing a GitHub repo, try this syntax: `{% github link_to_your_repo %}`) 

[Final Note]: # (CONGRATULATIONS!!! You are amazing!)
Error handling in begin rescue verifies that errors encountered during rescue can be rescued.
Tags: ruby
Published: 2020-05-22 01:57:58

---
title: Error handling in begin rescue verifies that errors encountered during rescue can be rescued.
published: true
description: 
tags: ruby
---

## Prerequisites.
Verification Version: Ruby2.6.1

# Summary
We can do it.

Validation Methods
raise raises the error, rescue catches the error, in which it raises the error again, and rescue catches it

```rb.
def method
  p 'init'
  begin
    raise "first error"
  rescue
    P "FIRST RESCUE"
    begin
      raise 'second error'
    rescue
      P 'SECOND RESCUE'
    end
  end
end
```

execution result

```rb.
> method
"init,"
"FIRST RESCUE,"
"SECOND RESCUE"
```

There's also a way to write a RESCUE one step out of the block without writing a BEGIN like this

```rb.
def method2
  p 'init'
  raise "first error"
rescue
  P "FIRST RESCUE"
  begin
    raise 'second error'
  rescue
    P 'SECOND RESCUE'
  end
end
```

execution result

```rb.
> method2
"init,"
"FIRST RESCUE,"
"SECOND RESCUE"
```
Force to Use yarn
Tags: yarn, npm
Published: 2020-05-22 01:57:05

### `package.json`
```json
{
  "name": "nonpm",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "engines": {
    "npm": "⚠️please-use-yarn⚠️",
    "yarn": ">= 1.17.3"
  },
  "keywords": [],
  "author": "koji",
  "license": "ISC",
  "dependencies": {
    "uuid": "^8.1.0"
  }
}
```

### `.npmrc`
https://docs.npmjs.com/misc/config#engine-strict
```
engine-strict = true
```


```zsh
$ npm i
npm ERR! code ENOTSUP
npm ERR! notsup Unsupported engine for nonpm@1.0.0: wanted: {"npm":"⚠️please-use-yarn⚠️","yarn":">= 1.17.3"} (current: {"node":"12.10.0","npm":"6.10.3"})
npm ERR! notsup Not compatible with your version of node/npm: nonpm@1.0.0
npm ERR! notsup Not compatible with your version of node/npm: nonpm@1.0.0
npm ERR! notsup Required: {"npm":"⚠️please-use-yarn⚠️","yarn":">= 1.17.3"}
npm ERR! notsup Actual:   {"npm":"6.10.3","node":"12.10.0"}

npm ERR! A complete log of this run can be found in:
npm ERR!     /Users/koji.kanao/.npm/_logs/2020-05-22T01_52_57_062Z-debug.log
```

However, still, we can install a package 🤣🤣🤣
```zsh
$ npm i uuid
npm WARN nonpm@1.0.0 No description
npm WARN nonpm@1.0.0 No repository field.

+ uuid@8.1.0
updated 1 package and audited 1 package in 0.663s
found 0 vulnerabilities
```

Tried another command.
```zsh
$ npm audit

                       === npm audit security report ===

found 0 vulnerabilities
 in 1 scanned package

```

### Also check out 👇!
thanks @patarapolw
I recreated React's class component lifecycle methods with hooks
Tags: showdev, react, reactnative
Published: 2020-05-22 01:54:09

 {% twitter 1263327984640946177 %} 

Project - [lifecycle-hooks](https://github.com/DaniAkash/lifecycle-hooks), also available in [npm](https://www.npmjs.com/package/@daniakash/lifecycle-hooks)

I recently started working on an old react native project where I had to upgrade **react-navigation** from v3 to v5. 

To take advantage of the new **navigation hooks** in version 5, I had to migrate existing class components to react hooks.

At first, it seemed like a straight forward case of refactoring some bit of code. However, I quickly realized how difficult the task at hand is...

Class component to hooks conversion is just not straight forward. Hooks are *awesome when you are building new components* but they are definitely not created with migrating class components in mind.

As [react documentation](https://reactjs.org/docs/hooks-intro.html#no-breaking-changes) says, class components aren't going away, so you probably won't have to migrate your project to functional components in most cases.

But if you run into a situation like me where you need the powerful hooks from *react-navigation*, *react-spring* or any other similar library, [lifecycle-hooks](https://github.com/DaniAkash/lifecycle-hooks) will make your migration a lot easier.

## traditional class state

```jsx
// Initialization
this.state = {
  name: "",
  email: "",
};
 
// updating name
this.setState({
  name: "John Doe",
});
```

## lifecycle-hook's `useState`

```jsx
import { useState } from "@daniakash/lifecycle-hooks"

// Initialization
const [state, setState] = useState({
  name: "",
  email: "",
});
 
// updating name
setState({
  name: "John Doe",
});
```

Likewise, I have also created hooks for `componentDidMount`, `componentDidUpdate` & `componentWillUnmount` which will let you quickly move code without having to worry about dependency arrays of `useEffect`

You can try these hooks in the following codesandbox playground. Let me know your thoughts! Feedbacks & PRs welcome ✨

{% codesandbox lifecycle-hooks-playground-n6qes %}
What’s your alternative solution? Challenge #47
Tags: challenge, javascript, codenewbie, learntocode
Published: 2020-05-22 00:50:10

# About this series

This is series of daily JavaScript coding challenges... for both beginners and advanced users.

Each day I’m gone present you a very simple coding challenge, together with the solution. The solution is intentionally written in a didactic way using classic JavaScript syntax in order to be accessible to coders of all levels.

Solutions are designed with increase level of complexity.

## Today’s coding challenge

```
Create a function that will return a Boolean value indicating if two circles defined by center coordinates and radius are intersecting

```

(scroll down for solution)

## Code newbies

If you are a code newbie, try to work on the solution on your own. After you finish it, or if you need help, please consult the provided solution.

## Advanced developers

Please provide alternative solutions in the comments below. 

You can solve it using functional concepts or solve it using a different algorithm... or just solve it using the latest ES innovations.

By providing a new solution you can show code newbies different ways to solve the same problem.

## Solution

```javascript
// Solution for challenge42

println(collisionCircleCircle(200, 200, 100, 300, 300, 50));

function collisionCircleCircle(circle1X, circle1Y, circle1R, circle2X, circle2Y, circle2R)
{
    return getDistance(circle1X, circle1Y, circle2X, circle2Y) <= circle1R + circle2R;
}

// Calculate the distance between the two specified points
function getDistance(x1, y1, x2, y2)
{
    var l1 = x2 - x1;
    var l2 = y2 - y1;
    
    return Math.sqrt(l1 * l1 + l2 * l2);
}

```


To quickly verify this solution, copy the code above in this coding [editor](https://codeguppy.com/code.html) and press "Run".

> Note: The solution was originally designed for [codeguppy.com](https://codeguppy.com) environment, and therefore is making use of `println`. This is the almost equivalent of `console.log` in other environments. Please feel free to use your preferred coding playground / environment when implementing your solution.
Tips for contributing to TypeScript
Tags: javascript, typescript
Published: 2020-05-22 00:43:58


- Architecture
    - [Architectural Overview](https://github.com/microsoft/TypeScript/wiki/Architectural-Overview)
    - [sandersn/mini-typescript](https://github.com/sandersn/mini-typescript) - A miniature model of the Typescript compiler, intended to teach the structure of the real Typescript compiler
    - [How the TypeScript Compiler Compiles - understanding the compiler internal - YouTube](https://www.youtube.com/watch?v=X8k_4tZ16qU)
- Start Contributing
    - [Contributing to TypeScript · microsoft/TypeScript Wiki](https://github.com/microsoft/TypeScript/wiki/Contributing-to-TypeScript)
    - [TypeScript/CONTRIBUTING.md at master · microsoft/TypeScript](https://github.com/Microsoft/TypeScript/blob/master/CONTRIBUTING.md)
- [Building](https://github.com/microsoft/TypeScript#building)
  - Use `npx gulp` for those who don't want to install gulp globally.
- Use TDD with running specific test cases, it's faster.
- Managing the Baselines
  - Compiler test cases generate baselines which are;
    - `.js` - generated JavaScript
    - `.types` - the type of each expression in the file.
    - `.symbols` - generated [symbols](https://github.com/microsoft/TypeScript/wiki/Architectural-Overview#data-structures)
    - `.errors.txt` - the errors produced by the compiler
  - You can inspect changes and the expected baselines
  - After verifying that the changes in the baselines are correct, run `gulp baseline-accept`
- Enable `Code Lens` in VSCode. [`Show On All Functions`](https://github.com/microsoft/vscode/pull/84689) is useful because compiler's code are written with a lot of functions.
- Disable eslint auto fix, it's slow. (Anybody who knows how to speed up?)
Facebook and more big tech companies are going to lean into distributed work. What is going to suck about this?
Tags: career, discuss, news
Published: 2020-05-22 00:35:33

## [Verge: Facebook says it will permanently shift tens of thousands of jobs to remote work](https://www.theverge.com/facebook/2020/5/21/21265699/facebook-remote-work-shift-workforce-permanent-covid-19-mark-zuckerberg-interview)

This will likely be a pleasant shift for many affected... But without seeding the conversation with too many of my own thoughts, what do you foresee as possibly bad consequences from this?
What Do Front-End Devs Think About Safari?
Tags: safari, discuss, webdev
Published: 2020-05-22 00:19:25

---
title: What Do Front-End Devs Think About Safari?
published: true
description: 
tags: Safari
---

I'm mostly a back-end guy, and have by and large worked with Firefox and Chrome being the browsers of choice, and have only had two issues with Safari (see below). As of today, I may have a third, but I may just have a configuration issue. So, please, what do you think about Safari? Is it the new IE 6? Is it considered decent? What do you think?

* Look at this URI: `http:/~foo/` It's **wrong**. You stick it in the browser and it doesn't work, but put it in a page and it will just assume the current server. It's just one step away from `/~foo/`, right? At least that's the logic my coworker had, but it broke the page for some users. When I had this issue in 2012, it worked in Firefox and Chrome and Opera and IE, but, I figured out by the logs, not Safari. The issue is that every other browser supported it — I don't know if they still do — and Safari didn't.

* HTML5 added an Audio API. To learn it, I created a page where, when you go there, you got an old-school pre-VOIP dial tone, which is actually two tones. But the [Secret Masters of HTML decided that pages making noise without us saying "you can make noise" is a _bad_ thing](https://developers.google.com/web/updates/2017/09/autoplay-policy-changes
), and so I rewrote it so that, and I asked my wife to check on the iPhone and it wouldn't play. I never fully figured out the issue between iOS Safari and my HTML5 stuff, but I installed a WebKit-based browser on my Linux box to try to work it out, and I don't believe I ever fully did.

So, that's my bits. What do you think about Safari? Do you have any Safari stories?
Quickwords — an open-source productivity app
Tags: productivity, vue, javascript, githubsdp
Published: 2020-05-22 00:28:20

In 2020 I graduated from my alma mater and, currently, I am holding a Bachelor of Engineering degree in Computer Science. During the course, my friend [Grzegorz Tłuszcz](https://github.com/gtluszcz) and I created a desktop app _Quickwords_. It is an open-source project that is available to everyone for free.

{% github https://github.com/quickwords/quickwords %}

The app helps you substitute common words, phrases and paragraphs with just few key strokes. The only thing you have to do is to create snippets that you want to be replaced and you are all set! As a trivial example you may, in your day-to-day work, write out your physical address very often. If you think about it, addresses can be very long, so they take a lot of time to type out by hand. Quickwords can help with that. You can create a so-called snippet, that would replace ;address with your actual address. The possibilities are endless!

![](https://i.imgur.com/IVklThU.gif)

The app is built using Electron, Vue.js and TailwindCSS. We are also using some open-source packages written in C++ (that we contributed to during the development of Quickwords). During the development one of us used the IntelliJ IDEA editor, which wouldn't be possible without #githubsdp and JetBrains.

![](https://camo.githubusercontent.com/51a5bbc37ca446c3c38e24d80f68e3aa0867d102/68747470733a2f2f692e696d6775722e636f6d2f6173436b3144732e706e67)

You can download Quickwords from [our official website](https://quickwords.co) and read more about it [in the documentation](https://quickwords.co/docs). Currently, we support only macOS, but the Windows version is almost ready and we are looking for feedback and help with its development. If you want to join our team, read [this thread](https://github.com/quickwords/quickwords/pull/26).
CSS trick: resizing elements without using JS
Tags: css, javascript
Published: 2020-05-22 00:27:01

actually there is a funny and easy way to resizing elements in your page, just by assigning one css class to your elements like so.
***html:***
```
<div class="resizable"></div>
```
***css:***
```
div {
    height: 300px;
    width: 300px;
    background-color: #f00;
}
.resizable {
    resize: both;
    overflow: scroll /* or auto */;
    border: 2px solid #000;
}
```

for more info [MDN](https://developer.mozilla.org/en-US/docs/Web/CSS/resize)

***but there is somthing anoying, its how can you styling that's little span on the bottom of the resizable element ?***
Live LeetCode Practice Interview for Software Engineers
Tags: career, challenge, beginners, interview
Published: 2020-05-22 00:13:19

Play along at home while I interview a brave software engineer and explain what they're doing well and how they can better impress an interviewer. 

In this week's session I ask the candidate a coding question that is similar in complexity to what Facebook asks (so I'm told). Here it is:

Write a function that takes two lists of colors called `secret` and `guess`.

The function returns a list of pegs, which imperfectly indicate how close the guess is to the secret:
- 'O' peg: one of the secret colors is in the guess, BUT in the wrong location
- '1' peg: one of the secret colors is in the guess, AND in the correct location

This question is intentional ambiguous and complicated, to mimic a situation where the candidate needs to clarify the question and load a lot of new context into their brain.

Note: I've even reworded the question above to make it a little bit kinder

Watch the video to find out how things resolve, or ask a friend to learn [MasterMind](https://www.webgamesonline.com/mastermind/index.php) and ask you this question so you can practice communicating about an ambiguous and confusing question under pressure.

CANDIDATE PLANET:
Empowering candidates to ace interviews and negotiate offers. Leave a comment or email Lusen@CandidatePlanet.com with questions you want me to answer.

DANGOORMENDEL:
One-on-one success-based coaching for technical and tech-adjacent candidates applying to tech companies. We specialize in interview preparation and offer negotiation.

SALARY NEGOTIATION PLAYLIST ☆ https://www.youtube.com/playlist?list=PLY0uEDNh-Haqes9eEvyGtzrUWOHv-c1op

SUBSCRIBE:
☆ Youtube ☆ https://youtube.com/c/CandidatePlanet
☆ Newsletter ☆ https://dangoormendel.com/newsletter
☆ LinkedIn ☆ https://linkedin.com/in/lus

MORE INFO:
☆ Website ☆ https://dangoormendel.com
☆ Speaking Inquiries ☆ lusen@candidateplanet.com
☆ Client Inquiries ☆ hello@dangoormendel.com

{% youtube uRrPvXgViNg %}
WWDC 2020 Wish-list
Tags: swift, apple, wwdc, wwdc2020
Published: 2020-05-29 05:15:32

---
title: WWDC 2020 Wish-list
published: true
date: 2020-05-22 00:00:00 UTC
tags: swift,apple,wwdc,wwdc2020
canonical_url: https://blog.rizwan.dev/2020-05-22_wwdc-2020-wishlist/
---

I wrote my thoughts on WWDC 2020 wish-list on twitter. Here is the list not in any particular order but hope to see it in real.

Also, did I tell you? This will be my first ever WWDC. Since It’s online and free for everyone.

{% twitter 1258537074556194818 %}
{% twitter 1258537254894485504 %}
{% twitter 1258537413271416832 %}
{% twitter 1258537588513619968 %}
{% twitter 1258538534295621633 %}
{% twitter 1258538768350375937 %}
{% twitter 1259826268444307456 %}
Viewing Kafka messages bytes as hex
Tags: apachekafka, kafkacat
Published: 2020-06-23 09:31:51

---
title: Viewing Kafka messages bytes as hex
published: true
date: 2020-05-22 00:00:00 UTC
tags: apachekafka, kafkacat
canonical_url: https://rmoff.net/2020/05/22/viewing-kafka-messages-bytes-as-hex/
---

I’ve been playing around with the new SerDes (serialisers/deserialisers) that shipped with Confluent Platform 5.5 - [Protobuf, and JSON Schema](https://docs.confluent.io/current/schema-registry/serdes-develop/index.html) (these were added to the existing support for Avro). The serialisers (and associated [Kafka Connect converters](https://docs.confluent.io/current/schema-registry/connect.html)) take a payload and serialise it into bytes for sending to Kafka, and I was interested in what those bytes look like. For that I used my favourite Kafka swiss-army knife: kafkacat.

Here’s a message serialised to JSON Schema:

```
$ kafkacat -b kafka:29092 -t pageviews-js -C -c1

{"viewtime":1,"userid":"User_9","pageid":"Page_57"}
```

Looks just like a message from another topic serialised as regular JSON, right?

```
$ kafkacat -b kafka:29092 -t pageviews-j -C -c1

{"viewtime":1,"userid":"User_3","pageid":"Page_77"}
```

Except it’s not! We can confirm this by looking at the raw bytes on the message itself by piping the output from kafkacat into hexdump.

Check out these magical, pesky, bytes on the front of the JSON Schema-encoded message, and note that they’re not there on the JSON message:

```
$ kafkacat -b kafka:29092 -t pageviews-js -C -c1 | hexdump -C

00000000 00 00 00 00 02 7b 22 76 69 65 77 74 69 6d 65 22 |.....{"viewtime"|
00000010 3a 31 2c 22 75 73 65 72 69 64 22 3a 22 55 73 65 |:1,"userid":"Use|
00000020 72 5f 39 22 2c 22 70 61 67 65 69 64 22 3a 22 50 |r_9","pageid":"P|
00000030 61 67 65 5f 35 37 22 7d 0a |age_57"}.|
00000039

$ kafkacat -b kafka:29092 -t pageviews-j -C -c1 | hexdump -C

00000000 7b 22 76 69 65 77 74 69 6d 65 22 3a 31 2c 22 75 |{"viewtime":1,"u|
00000010 73 65 72 69 64 22 3a 22 55 73 65 72 5f 33 22 2c |serid":"User_3",|
00000020 22 70 61 67 65 69 64 22 3a 22 50 61 67 65 5f 37 |"pageid":"Page_7|
00000030 37 22 7d 0a |7"}.|
00000034
```

The five extra bytes (`00 00 00 00 02`) are defined in the [wire format](https://docs.confluent.io/current/schema-registry/serdes-develop/index.html#wire-format) used by the Schema Registry serdes:

- **Byte 0** : Magic Byte - Confluent serialization format version number; currently always 0.

- **Bytes 1-4** : 4-byte schema ID as returned by Schema Registry.