teleren/devto huggingface dataset:
Day 82 : #100DaysofCode - Received Help and Problem Solved
Published: 2020-08-22 01:31:50

Today was a good day. I woke up this morning and had a meeting with someone who helped me move forward on an issue that I was struggling with: 

{% link https://dev.to/sincerelybrittany/day-80-100daysofcode-stuck-on-a-rails-problem-3cj9 %}

The individual who helped me asked to remain anonymous and spent time showing me how to iterate through the Unsplash gem and displaying it using Javascript instead of Ruby. 

First we saved the response from the Unsplash gem into a variable in the photos controller:

``@photos = Unsplash::Photo.search("cats")``

Then within the views, we iterated through the response to get what we needed. (please note, I definitely plan to move all the logic from my views into a helper when I am refactoring) 
In addition, we added a ``class`` to the checkbox and an ``id`` to the submit button so that we could reference it with an eventListener in javascript/jquery. 

```
 <% @photos.each do |p| %>
            <img src="<%= p["urls"].full %>" alt="random" ><br>
            <div><p> <%= p["alt_description"] %> </p></div><br>
            <%= check_box_tag "data", 1, false, data: {url: p["urls"].full, description: p["alt_description"]}, class: "add-photo"  %>
    <% end %>
  <button id="submit"> Submit </button>
```

Within the ``application.js`` we added an initial function that will run on load. We added a click eventListener on the ``add-photo`` class and saved the url and description into an array. 

```
$(document).on("turbolinks:load", function() {
    const photos = []
    $( ".add-photo" ).click(function(e) {
        const photo = {url: e.target.dataset.url, quote: e.target.dataset.description }
        photos.push(photo)
    });
```

Then we added a click eventListener on the submit button which saved the photos object into a hash and made a fetch post request to ``/photos``.

```
    $("#submit").click(function(e){
    fetch('/photos', {
        method: 'POST', // or 'PUT'
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify({data: photos}),
        })
        .then(response => response.json())
        .then(data => {
        console.log('Success:', data);
        })
        .catch((error) => {
        console.error('Error:', error);
        });
    })
})
``` 

I put a byebug in my create method within my photos controller and IT WORKED. I had all the information I needed to proceed with my project. 

I am so grateful for their help and I know I would not have been able to proceed with my project anytime soon without their help.

{% github SincerelyBrittany/photo-app no-readme %}

I am happy that I learned something new and it made me excited to continue to learn with my bootcamp as I move on to Javascript next week. 

I will continue with this project this weekend with high hopes to finish it by Sunday. 

As always, thank you for reading!

Sincerely, 
Brittany

Song of the Day: 

{% soundcloud https://soundcloud.com/brasstracks/missed-your-call %}
use-one: a new state share library for react app...
Tags: react, typescript
Published: 2020-08-22 00:54:48

Hello, everyone! Today, I will share a new state library for react. I already thought this a few years ago until hooks showed up, I can make it real now. The [source code](https://github.com/suhaotian/use-one) is really simple. 

**Features**

- Easy share state anywhere
- No more complex concepts, only useHook
- Write in TypeScript
- Tiny size (with Dependencies together only gzip 2KB!)


## Install

**npm**

```bash
npm install use-one eventemitter3 --save
```

**yarn**

```bash
yarn add use-one eventemitter3
```

## Usage

**Create one hook**

```ts
// useCount.ts
import { create } from "use-one";

const initialState = { count: 0 };

type CountStateType = typeof initialState;

const [useCount, countStore] = create<CountStateType>(initialState);

export { useCount, countStore };

export const actions = {
  increment: () => {
    // `countStore.getState().count`, we can write to selectors
    countStore.setState({ count: countStore.getState().count + 1 });
  },
  decrement: () => {
    countStore.setState({ count: countStore.getState().count - 1 });
  },
};
```

**Use the hook**

```tsx
// CountExample.tsx
import * as React from "react";
import { useCount, countStore, actions } from "./useCount";

const CountExample = () => {
  const [countState, setCountState] = useCount();

  const { count } = countState;

  return (
    <div>
      <button onClick={actions.increment}>+1</button>
      <span>{count}</span>
      <button onClick={actions.decrement}>-1</button>
      <button
        onClick={() => {
          setTimeout(() => {
            setCountState({
              count: countStore.getState().count + 2,
            });
          }, 2000);
        }}>
        async +2
      </button>
    </div>
  );
};

const ShowCountInOtherPlace = () => {
  const [countState] = useCount();
  const { count } = countState;

  return <span>Count: {count}</span>;
};

export default function App() {
  return (
    <Fragment>
      <ShowCountInOtherPlace />
      <CountExample />
    </Fragment>
  );
}
```

### Online Example

[**Count**](https://codesandbox.io/embed/hidden-hooks-i4z28?fontsize=14&hidenavigation=1&theme=dark)

[**TextInput**](https://codesandbox.io/embed/use-one-text-input-demo-fhfph?fontsize=14&hidenavigation=1&theme=dark)

#### Dependencies

- [eventemitter3](https://github.com/primus/eventemitter3)
Using SQL with ActiveRecord for performance gains
Tags: rails, ruby
Published: 2020-08-22 00:52:01

While working on a side project, I had a need to count items by day of the month. While this can likely be achieved in Ruby, I reached for SQL instead.

I have a table called `journal_entries`. It has the following columns.

```
   Column   |              Type              | Collation | Nullable |                   Default
------------+--------------------------------+-----------+----------+---------------------------------------------
 id         | bigint                         |           | not null | nextval('journal_entries_id_seq'::regclass)
 journal_id | bigint                         |           |          |
 body       | text                           |           | not null |
 created_at | timestamp(6) without time zone |           | not null |
 updated_at | timestamp(6) without time zone |           | not null |
 metadata   | jsonb                          |           | not null | '"{}"'::jsonb
```

For a given `journal`, I wanted to count the number of journal entries per day. To do that, I ended up with a method called `entries_by_day`.

```ruby
def entries_by_day
  journal
    .journal_entries
    .where(created_at: interval)
    .group("extract(day from created_at AT TIME ZONE '#{Time.zone.formatted_offset}')::int")
    .count
end
```

For the most part, this is a normal ActiveRecord query. We're querying for a journal's journal entries within a given interval. In our case, an interval would be something like July 1, 2020 to July 31, 2020.

Then, we use the `group` method [which is pretty cool](https://guides.rubyonrails.org/active_record_querying.html#group). This translates to a `GROUP BY` in SQL. To group the rows, we use the `extract` function provided by PostgreSQL ([documentation](https://www.postgresql.org/docs/8.1/functions-datetime.html)).

What we're saying is this. Give me the day (1, 2, 3, ..., 31) based on the timestamp. If the timestamp is `2020-08-11 19:05:59.508883`, `extract` would give us `11`.

What we end up with is a `Hash` with the days as keys and the count as values.

```ruby
{25=>3, 29=>2, 27=>2, 23=>2, 24=>2}
```

This has the advantage of offloading performance concerns to the database. PostgreSQL can typically do these types of operations faster.

If we were to attempt the same in Ruby, we would need to query for all of the records within the month of July. Then, we'd have to use Ruby's `group_by` method to finish the job.
🎹🎵 I made a new HTML & CSS only drawing 🎵🎹
Tags: codepen, css, html
Published: 2020-08-22 00:38:42

Photorealistic illustration of a [Roland MC-500](https://i.pinimg.com/564x/a2/02/a4/a202a4ab33dff87b53ba54db33518b78.jpg).

I wrote a few tutorials on how to create art like this:
- [How to make a Polaroid camera in CSS](https://fossheim.io/writing/posts/css-polaroid-camera/)
- [How to recreate a Macintosh in CSS](https://fossheim.io/writing/posts/css-macintosh/)

{% codepen https://codepen.io/fossheim/pen/BaKQGZJ %}

[Patreon](https://www.patreon.com/fossheim) | [Buy me a coffee](https://www.buymeacoffee.com/fossheim) | [Blog](https://fossheim.io/writing/) | [Twitter](https://twitter.com/liatrisbian) | [CodePen](https://codepen.io/collection/nwzQJq) | [GitHub](https://github.com/sarahfossheim/art.css)
It's roguelike boilerplate launch day, yay!
Tags: roguelike, webdev, gamedev, javascript
Published: 2020-08-22 00:06:08

I've been working hard on this thing for the past few months and I'm so excited to finally be bringing it to you!

It's a web app template for creating your own roguelike game using JavaScript and web tech. It comes with a PDF guide and I'm currently recording a [screencast series](https://www.youtube.com/watch?v=d1zhoXwOdtQ&list=PL5dyN9XHelZOl2yTZQu9IA4SQFcA3giac&index=2) to show you how to modify everything to make your own game.

{% twitter 1296729232450568193 %}

Here's a link to the final product: https://chr15m.itch.io/roguelike-browser-boilerplate

Thanks for reading!
Sass vs Scss
Tags: css, html, sass, scss
Published: 2020-08-22 00:05:56

The major reason Sass was developed was to make writing CSS more efficient and awesome. If you are looking for a preprocessor language to learn, I would strongly recommend Sass. Why Sass? Read why [here](https://css-tricks.com/sass-vs-less/). Before I proceed to explain the difference between Sass and Scss and which one is more preferable to use, I will first want to explain what Sass is all about.
******
## Sass
**Sass** stands for **S**yntactically **A**wesome **S**tyle **s** heet. Sass is a preprocessor scripting language that is interpreted or compiled into Cascading Style Sheets. It is completely compatible with all versions of CSS. It is free to download and use. 

Stylesheets are getting larger, more complex, and harder to maintain. This is where a CSS pre-processor can help.

It allows you to use [variables](https://sass-lang.com/documentation/variables), [nested rules](https://sass-lang.com/documentation/style-rules#nesting), [mixins](https://sass-lang.com/documentation/at-rules/mixin), [functions](https://sass-lang.com/documentation/modules), and more, all with a fully CSS-compatible syntax.

***Sass has two syntaxes which are Sass and Scss.***
******
## Sass vs Scss
The most commonly used syntax is known as “SCSS” (for “Sassy CSS”), and it takes the CSS syntax we are used to and gives it the super powers that come with Sass. This means that every valid CSS3 stylesheet is valid SCSS as well. SCSS files use the extension **.scss**. This is really handy as it becomes a lot easier to convert our regular CSS styles to Scss.




```css
/* SCSS */
$primary-color: #3bbfce;
$secondary-color: #ff8700;

.content {
  background-color: $primary-color;
  color: darken($secondary-color, 9%);
}
```




The second syntax(older syntax) is Sass which was created to make CSS a bit more awesome and writing of CSS codes more efficient by taking away the use of **curly-braces & semi-colons**, it uses the indentation of lines to specify blocks. Files in the indented syntax use the extension **.sass**.




```css
/* SASS */
$primary-color: #3bbfce
$secondary-color: #ff8700

.content-navigation
  background-color: $primary-color
  color: darken($secondary-color, 9%)
```



With the above explanation, you can properly see the difference between Sass and Scss,  the next question would be which one should I learn or which one should I use.
*******
The truth is no one should answer that question for you, You should know what best works for you and which one suits your pattern of writing codes. 

>For me, I've never loved the Sass syntax because I'm already used to opening curly-braces and making use of semi-colons. And the fact that Scss is always beneficial when working as a team, I just couldn't stop using it. 

**But you are the one to make the decision for yourself!**

You might want to learn more about Sass. Please check their [documentation](https://sass-lang.com/guide)!

****

As always, any questions or suggestions, please feel free to leave a response or [tweet me](https://twitter.com/olawanle_joel) 🤭! Be sure to connect with me on socials! 😎
How to use the calc() function in CSS?
Tags: css
Published: 2020-08-22 00:00:00

---
  title: How to use the calc() function in CSS?
  published: true
  tags: CSS
  date: Sat Aug 22 2020 05:30:00 GMT+0530 (India Standard Time)
  canonical_url: https://melvingeorge.me/blog/calc()-method-css
  cover_image: https://melvingeorge.me/_next/static/images/main-93057509b3b3b22bf22087263e0f0d5c.jpg
  ---
  [Originally posted here!](https://melvingeorge.me/blog/calc()-method-css)
  
The `calc()` function is used to dynamically calculate CSS property values.

You can pass any valid CSS units as arguments to the `calc()` function.

For example, you can use an expression to substract `50px - 20px`.

```css
h1 {
  margin: calc(50px - 20px); // the value calculated will be 30px
}
```

You can use any valid CSS property values like `px`, `percentage`, `number`, `em`, `vw`, `rem`, etc.

One of the best usecases i have found with the `calc()` css function is to center the container element like this,

```css
// centering the container
.container {
  width: calc(100% - 50px);
  margin: 0 auto;
}
```

The width of the container is calculated to the full width of the viewing device and then `50px` is subtracted from `100%`.

### Feel free to share if you found this useful 😃.

---
What have you always wanted to see in your CI?
Published: 2020-08-21 23:20:18

Disclaimer: I'm looking for ideas for the [GitHub actions hackathon](https://dev.to/devteam/announcing-the-github-actions-hackathon-on-dev-3ljn). 

Personally I would love a solution that intelligently figures out which tests need to be run to verify that a code change is safe, rather than just blindly running all of the tests. Some test suites can take *ages*. I asked the #python discord channel but people weren't interested. Que lastima!

What are your ideas?
Day 201: Laid Back
Tags: hiphop, code, coding, lifelongdev
Published: 2020-08-21 22:27:28

_liner notes_:
- Professional : Had another pretty chill and laid back, but productive day today. Just worked on tickets for most of the day. One was to modify a tutorial to use another method that would make it easier to get through. That took a minute, but got it done. I'm going to run through it on Monday to make sure everything still works and do a pull request with my changes.

- Personal : Last night, I went through a bunch of tracks for this week's radio show. Also, figured out a bug I was having with my side project. There was an issue where I would stop using my webcam, but when I tried to switch to a new camera, I would get an error. I could still select the previously used camera, just not switch to a new one. Turns out that I had to close the camera in another section of the code. I'm using the camera feed to stream to the other participants and viewers, but also to the dashboard so that the host can see it. I wasn't clearing the feed to the dashboard. Stayed in the van in the back of my parent's place. It was nice to be able to keep my screens open and let the cool night air come in.

![The cliffs of Maui, Hawaii with the sun setting](https://dev-to-uploads.s3.amazonaws.com/i/iksz36yhds2qnbghlkeb.png)

So, my battery is currently at about 45% full. Being plugged into the outlet isn't charging as fast as I would like. I did use my induction for about 5 minutes to boil some water for a cup of noodles for lunch. Didn't take as much as I thought. I'll be using the microwave for dinner. We'll see how that goes. After work, I went through and cleaned up the van and took stuff out of boxes. There's a lot more room to move around now. Things are falling into the places where I think they will be when I do the framing. Speaking of which, I'll probably take some time off in September so I can travel down south to the place that sells the material I'll be using. We'll see. Going to stay at my parents place tonight, because I'm supposed to be getting a package later today and another tomorrow. Alright, going to continue working on the radio show.

Have a great night and weekend!

peace piece
Dwane / conshus
https://dwane.io / https://HIPHOPandCODE.com
{% youtube XqOhfoExCf0 %}
Truncate string with ellipsis
Tags: css, webdev, codenewbie, 100daysofcode
Published: 2020-08-21 22:01:58

Sometimes we required to adjust long strings in one line and show ellipsis(...) at the end of the string as a symbol that this text is long.

Then we can use the `title` attribute to show the full string on the hover of text.

##**To truncate long strings we will use the following CSS properties:**
1. `text-overflow`: describes how hidden content should be shown to the user. 
2. `white-space`: sets how white space inside an element is handled.
3. `overflow`: property specifies whether to clip the content or to add scrollbars when the content of an element is too big to fit in the specified area.
4. `width`: width of the content.

```css
div {
  width: 100%;
  text-overflow: ellipsis;
  white-space: nowrap;
  overflow: hidden;
}
```
> text-overflow property is used with white-space and overflow to show this ellipsis signal if the content is clipped.

- `white-space: nowrap`: text will not be wrapped.
- `overflow: hidden`: hide/clip the content in fix width.
- Finally`text-overflow: ellipsis`: will show the sign (...) stating that this text is clipped.


###**Inform user about full-text content:**
- For that use the `title` attribute. 
- If used, the long string will be shown to the user if hovered on `div` like the example below.

```javascript
const longText = Hey everyone, This code shows how we can truncate long strings so that they can show as an ellipsis. we can use 100% width to adjust the text in one line.

<div title={longText}>{longText}</div>
```

###Both examples in codepen
{% codepen https://codepen.io/ip127001/pen/GRZNYrR default-tab=css,result %}


##Ellipsis in input element:
Just use `text-overflow: ellipsis` directly.

```css
input {
  text-overflow: ellipsis;
}
```

Happy coding!

Thanks for reading!
Help creating helloworld library with reusable component
Published: 2020-08-21 21:50:39

I don't know if this is the right forum, but I am 
struggling with creating an angular library with some reusable components.
When I simply do:
ng generate library testlib
ng build
create a new project
do an ln -s path/dist/testlib node_modules/testlib
import and use the component
I get:
ERROR in node_modules/testlib/lib/testlib.component.d.ts:3:22 - error NG6002: Appears in the NgModule.imports of AppModule, but could not be resolved to an NgModule class.
    
    This likely means that the library (testlib) which declares TestlibComponent has not been processed correctly by ngcc, or is not compatible with Angular Ivy. Check if a newer version of the library is available, and update if so. Also consider checking with the library's authors to see if the library is expected to be compatible with Ivy.
export declare class TestlibComponent implements OnInit {
Day 36
Tags: 100daysofcode
Published: 2020-08-21 21:29:12

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/seqt8tqw4gyxc7yfdaox.png)
I come bearing good news. I am excited to be taking part in a build for sustainable development goals [sdg's](https://sustainabledevelopment.un.org/topics/sustainabledevelopmentgoals) program, working on a real world product with a team of developers across Africa. 

I've been torn between brainstorming ideas and understanding how to use [Codacy](https://www.codacy.com/). Codacy is a tool to automate code review. I would love to write about how to use it but i am trying to find my around it.

My days will definitely be longer and posts shorter, but i'll still be on a learning journey. 

To new opportunities.
_Day 36_
C# - Handy Features
Tags: csharp, beginners, dotnet, productivity
Published: 2020-08-21 21:28:43

C# has been improved greatly over the years with useful features that have increased productivity for developers.

Below I’ll explain a few of my favorite features.

##String Interpolation
>In many programming languages, writing a string with embedded variables can be cumbersome. The longer the string, the more noise is added affecting readability like so:

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

>C# 6.0 introduced a new string interpolation feature in which the variables can be written as expressions without the need for awkward string concatenation:

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

>This results in the same output, but the code is much easier to read and maintain. To use this feature the string must begin with the $ symbol . String formatters may also be applied as shown in the `Score` variable.

>As a plus – expressions will be highlighted within the whole string for better visibility in Visual Studio.


##Expression-bodied function members

>If you’ve created a few C# POCO classes over the years, I’m willing to bet many of the properties you’ve written are single read only statements.

>Here’s a typical example where `FullName` is a read only property:

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


>...And now here’s the same example using the `FullName` property as an expression-bodied function member:

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

>The output is identical to the previous example. The code has been compacted down to one line, reducing noise.


##Null-conditional operators

>Null checking is an important subject for producing stable apps. Until now, null checking has often been verbose. Here’s a typical null checking statement combined with a ternary operator:

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

>With C# 6.0 null checking becomes more succinct:

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

>In this example the variable `firstName` is assigned null if the person object is null. If the person object is not null, the value of the `FirstName` property will be applied. This works thanks to the `?` operator.

>But what if we want to supply a substituted value for null values, similar to the ternary operator approach? 

>This can be solved by using the null coalescing operator:

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

>Here, the expression always returns a string. The rules of the `?` operator ensure that the left-hand side of the operator is evaluated only once.


Happy Coding 🤓
Building a Link Shortener
Tags: showdev, laravel, vue
Published: 2020-08-21 21:11:29

When I read that Google was shutting down its URL shortener service in March 2019, I decided that there would be a big demand for another link shortener service. This news gave me the idea to build my own link shortener.

The first step to build a URL shortener is to get a short domain. Fortunately, I was able to get [T.LY](https://t.ly/) an amazing 1 letter domain. The next step was to build an API with subscriptions, teams, custom domains, stats, and all the functionality you would expect from a link shortener. I also built a [link shortener extension](https://t.ly/extension) that allows you to shorten any URL in 1 click! 

If you are building an application that needs to shorten links, check out the simple to use [T.LY API](http://t.ly/docs).

I would love your feedback on [T.LY](https://t.ly/)!
Thanks